about summary refs log tree commit diff
path: root/pkgs/test/make-binary-wrapper/prefix.c
blob: 8ca0ad94a6d7058a9b15fe4fc596976721d5a804 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// makeCWrapper /path/to/executable \
    --prefix PATH : /usr/bin/ \
    --prefix PATH : /usr/local/bin/

#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdio.h>

#define assert_success(e) do { if ((e) < 0) { perror(#e); abort(); } } while (0)

char *concat3(char *x, char *y, char *z) {
    int xn = strlen(x);
    int yn = strlen(y);
    int zn = strlen(z);
    char *res = malloc(sizeof(*res)*(xn + yn + zn + 1));
    assert(res != NULL);
    strncpy(res, x, xn);
    strncpy(res + xn, y, yn);
    strncpy(res + xn + yn, z, zn);
    res[xn + yn + zn] = '\0';
    return res;
}

void set_env_prefix(char *env, char *sep, char *val) {
    char *existing = getenv(env);
    if (existing) val = concat3(val, sep, existing);
    assert_success(setenv(env, val, 1));
    if (existing) free(val);
}

int main(int argc, char **argv) {
    set_env_prefix("PATH", ":", "/usr/bin/");
    set_env_prefix("PATH", ":", "/usr/local/bin/");
    argv[0] = "/path/to/executable";
    return execv("/path/to/executable", argv);
}