aboutsummaryrefslogtreecommitdiff
path: root/lib/rpath.c
blob: 637acf4ae12dd9f1f87e6c808955e4b942b3fdc7 (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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
/**
 * @file rpath.c
 */
#include "spm.h"

/**
 * Wrapper function to execute `patchelf` with arguments
 * @param _filename Path to file
 * @param _args Arguments to pass to `patchelf`
 * @return success=Process struct, failure=NULL
 */
Process *patchelf(const char *_filename, const char *_args) {
    char *filename = strdup(_filename);
    char *args = strdup(_args);
    Process *proc_info = NULL;
    char sh_cmd[PATH_MAX];
    sh_cmd[0] = '\0';

    strchrdel(args, SHELL_INVALID);
    strchrdel(filename, SHELL_INVALID);
    sprintf(sh_cmd, "patchelf %s %s 2>&1", args, filename);

    if (SPM_GLOBAL.verbose > 1) {
        printf("         EXEC : %s\n", sh_cmd);
    }

    shell(&proc_info, SHELL_OUTPUT, sh_cmd);

    free(filename);
    free(args);
    return proc_info;
}

/**
 * Wrapper function to execute `install_name_tool` with arguments
 * @param _filename Path to file
 * @param _args Arguments to pass to `install_name_tool`
 * @return success=Process struct, failure=NULL
 */
Process *install_name_tool(const char *_filename, const char *_args) {
    char *filename = strdup(_filename);
    char *args = strdup(_args);
    Process *proc_info = NULL;
    char sh_cmd[PATH_MAX];
    sh_cmd[0] = '\0';

    strchrdel(args, SHELL_INVALID);
    strchrdel(filename, SHELL_INVALID);
    sprintf(sh_cmd, "install_name_tool %s %s 2>&1", args, filename);

    if (SPM_GLOBAL.verbose > 1) {
        printf("         EXEC : %s\n", sh_cmd);
    }

    shell(&proc_info, SHELL_OUTPUT, sh_cmd);

    free(filename);
    free(args);
    return proc_info;
}

/**
 * Determine whether a RPATH or RUNPATH is present in file
 *
 * TODO: Replace with OS-native solution(s)
 *
 * @param _filename path to executable or library
 * @return -1=OS error, 0=has rpath, 1=not found
 */
int has_rpath(const char *_filename) {
    char *rpath = NULL;

    if (_filename == NULL) {
        spmerrno = EINVAL;
        return -1;
    }

    if ((rpath = shlib_rpath(_filename)) == NULL) {
        return 1;
    };

    return 0;
}

/**
 * Returns a RPATH or RUNPATH if one is defined in `_filename`
 *
 * TODO: Replace with OS-native solution(s)
 *
 * @param _filename path to executable or library
 * @return RPATH string, NULL=error (caller is responsible for freeing memory)
 */
char *rpath_get(const char *_filename) {
    if ((has_rpath(_filename)) != 0) {
        return strdup("");
    }
    return shlib_rpath(_filename);
}

/**
 * Generate a RPATH in the form of:
 *
 * `$ORIGIN/relative/path/to/lib/from/_filename/path`
 *
 * @param _filename
 * @return
 */
char *rpath_generate(const char *_filename, FSTree *tree) {
    char *filename = realpath(_filename, NULL);
    if (!filename) {
        return NULL;
    }

    char *result = rpath_autodetect(filename, tree);
    if (!result) {
        free(filename);
        return NULL;
    }

    free(filename);
    return result;
}

/**
 * Set the RPATH of an executable
 * @param filename
 * @param rpath
 * @return
 */
int rpath_set(const char *filename, const char *rpath) {
    int returncode = 0;
    char args[PATH_MAX];

    memset(args, '\0', PATH_MAX);
    sprintf(args, "--set-rpath '%s'", rpath);   // note: rpath requires single-quotes
    Process *pe = patchelf(filename, args);
    if (pe != NULL) {
        returncode = pe->returncode;
    }
    shell_free(pe);
    return returncode;
}

/**
 * Automatically detect the nearest lib directory and set the RPATH of an executable
 * @param filename
 * @param _rpath
 * @return
 */
int rpath_autoset(const char *filename, FSTree *tree) {
    int returncode = 0;

    char *rpath_new = rpath_generate(filename, tree);
    if (!rpath_new) {
        return -1;
    }

    returncode = rpath_set(filename, rpath_new);
    free(rpath_new);

    return returncode;
}

/**
 * Find shared libraries in a directory tree
 *
 * @param root directory
 * @return `FSTree`
 */
FSTree *rpath_libraries_available(const char *root) {
    FSTree *tree = fstree(root, (char *[]) {SPM_SHLIB_EXTENSION, NULL}, SPM_FSTREE_FLT_CONTAINS | SPM_FSTREE_FLT_RELATIVE);
    if (tree == NULL) {
        perror(root);
        fprintf(SYSERROR);
        return NULL;
    }
    return tree;
}

/**
 * Compute a RPATH based on the location `filename` relative to the shared libraries it requires
 *
 * @param filename path to file (or a directory)
 * @return success=relative path from `filename` to nearest lib directory, failure=NULL
 */
char *rpath_autodetect(const char *filename, FSTree *tree) {
    const char *origin = "$ORIGIN";
    char *rootdir = dirname(filename);
    char *start = realpath(rootdir, NULL);
    char *cwd = realpath(".", NULL);
    char *result = NULL;

    char *visit = NULL;                 // Current directory
    char _relative[PATH_MAX] = {0,};    // Generated relative path to lib directory
    char *relative = _relative;         // Pointer to relative path
    size_t depth_to_root = 0;

    // BUG: Perl dumps its shared library in a strange place.
    // This function returns `$ORIGIN/../../../CORE` which is not what we want to see.
    // TODO: We WANT to see this: `$ORIGIN/../lib/perl5/xx.xx.xx/<arch>/CORE` not just the basename()

    // Change directory to the requested root
    chdir(start);

    // Count the relative path distance between the location of the binary, and the top of the root
    visit = strdup(start);
    for (depth_to_root = 0; strcmp(tree->root, visit) != 0; depth_to_root++) {
        // Copy the current visit pointer
        char *prev = visit;
        // Walk back another directory level
        visit = dirname(visit);
        // Free previous visit pointer
        if (prev) free(prev);
    }
    free(visit);

    // return to calling directory
    chdir(cwd);

    StrList *libs = strlist_init();
    if (libs == NULL) {
        fprintf(stderr, "failed to initialize library StrList\n");
        fprintf(SYSERROR);
        return NULL;
    }

    StrList *libs_wanted = shlib_deps(filename);
    if (libs_wanted == NULL) {
        fprintf(stderr, "failed to retrieve list of share libraries from: %s\n", filename);
        fprintf(SYSERROR);
        return NULL;
    }

    for (size_t i = 0; i < strlist_count(libs_wanted); i++) {
        // zero out relative path string
        memset(_relative, '\0', sizeof(_relative));
        // Get the shared library name we are going to look for in the tree
        char *shared_library = strlist_item(libs_wanted, i);

        // Is the shared library in the tree?
        char *match = NULL;
        if ((match = dirname(strstr_array(tree->files, shared_library))) != NULL) {
            // Begin generating the relative path string
            strcat(relative, origin);
            strcat(relative, DIRSEPS);

            // Append the number of relative levels to the relative path string
            if (depth_to_root) {
                for (size_t d = 0; d < depth_to_root; d++) {
                    strcat(relative, "..");
                    strcat(relative, DIRSEPS);
                }
            } else {
                strcat(relative, "..");
                strcat(relative, DIRSEPS);
            }
            // Append the match to the relative path string
            strcat(relative, basename(match));

            // Append relative path to array of libraries (if it isn't already in there)
            if (strstr_array(libs->data, relative) == NULL) {
                strlist_append(libs, relative);
            }
        }
    }

    // Some programs do not require local libraries provided by SPM (i.e. libc)
    // Inject "likely" defaults here
    if (strlist_count(libs) == 0) {
        strlist_append(libs, "$ORIGIN/../lib");
        strlist_append(libs, "$ORIGIN/../lib64");
    }

    // Populate result string
    result = join(libs->data, ":");

    // Clean up
    strlist_free(libs);
    strlist_free(libs_wanted);
    free(rootdir);
    free(cwd);
    free(start);
    return result;
}