File: patcher_linux_module.c

package info (click to toggle)
openmpi 4.1.0-10
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 126,560 kB
  • sloc: ansic: 685,465; makefile: 42,952; f90: 19,220; sh: 7,002; java: 6,360; perl: 3,524; cpp: 2,227; python: 1,350; lex: 989; fortran: 61; tcl: 12
file content (397 lines) | stat: -rw-r--r-- 13,695 bytes parent folder | download | duplicates (3)
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil -*- */
/*
 * Copyright (C) Mellanox Technologies Ltd. 2001-2015.  ALL RIGHTS RESERVED.
 * Copyright (c) 2016      Los Alamos National Security, LLC. All rights
 *                         reserved.
 * $COPYRIGHT$
 *
 * Additional copyrights may follow
 *
 * $HEADER$
 */
/*
 * Copied from OpenUCX
 */

#include "patcher_linux.h"

#include "opal/mca/patcher/base/base.h"

#include "opal/constants.h"
#include "opal/util/sys_limits.h"
#include "opal/util/output.h"
#include "opal/prefetch.h"

#if defined(HAVE_SYS_AUXV_H)
#include <sys/auxv.h>
#endif

#include <elf.h>

#include <sys/mman.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dlfcn.h>
#include <fcntl.h>
#include <link.h>

static void *mca_patcher_linux_dlopen(const char *filename, int flag);

typedef struct mca_patcher_linux_dl_iter_context {
    mca_patcher_linux_patch_t *patch;
    bool remove;
    int status;
} mca_patcher_linux_dl_iter_context_t;

OBJ_CLASS_INSTANCE(mca_patcher_linux_patch_got_t, opal_list_item_t, NULL, NULL);

static void mca_patcher_linux_patch_construct (mca_patcher_linux_patch_t *patch)
{
    OBJ_CONSTRUCT(&patch->patch_got_list, opal_list_t);
}

static void mca_patcher_linux_patch_destruct (mca_patcher_linux_patch_t *patch)
{
    OPAL_LIST_DESTRUCT(&patch->patch_got_list);
}

OBJ_CLASS_INSTANCE(mca_patcher_linux_patch_t, mca_patcher_base_patch_t, mca_patcher_linux_patch_construct,
                   mca_patcher_linux_patch_destruct);

/* List of patches to be applied to additional libraries */
static void *(*orig_dlopen) (const char *, int);

static const ElfW(Phdr) *
mca_patcher_linux_get_phdr_dynamic(const ElfW(Phdr) *phdr, uint16_t phnum, int phent)
{
    for (uint16_t i = 0 ; i < phnum ; ++i, phdr = (ElfW(Phdr)*)((intptr_t) phdr + phent)) {
        if (phdr->p_type == PT_DYNAMIC) {
            return phdr;
        }
    }

    return NULL;
}

static void *mca_patcher_linux_get_dynentry(ElfW(Addr) base, const ElfW(Phdr) *pdyn, ElfW(Sxword) type)
{
    for (ElfW(Dyn) *dyn = (ElfW(Dyn)*)(base + pdyn->p_vaddr); dyn->d_tag; ++dyn) {
        if (dyn->d_tag == type) {
            return (void *) (uintptr_t) dyn->d_un.d_val;
        }
    }

    return NULL;
}

static void * mca_patcher_linux_get_got_entry (ElfW(Addr) base, const ElfW(Phdr) *phdr, int16_t phnum,
                                               int phent, const char *symbol)
{
    const ElfW(Phdr) *dphdr;
    void *jmprel, *strtab;
    ElfW(Sym)  *symtab;
    size_t pltrelsz;

    dphdr = mca_patcher_linux_get_phdr_dynamic (phdr, phnum, phent);

    jmprel = mca_patcher_linux_get_dynentry (base, dphdr, DT_JMPREL);
    symtab = (ElfW(Sym) *) mca_patcher_linux_get_dynentry (base, dphdr, DT_SYMTAB);
    strtab = mca_patcher_linux_get_dynentry (base, dphdr, DT_STRTAB);
    pltrelsz = (size_t) (uintptr_t) mca_patcher_linux_get_dynentry (base, dphdr, DT_PLTRELSZ);

    for (ElfW(Rela) *reloc = jmprel; (intptr_t) reloc < (intptr_t) jmprel + pltrelsz; ++reloc) {
#if SIZEOF_VOID_P == 8
        uint32_t relsymidx = ELF64_R_SYM(reloc->r_info);
#else
        uint32_t relsymidx = ELF32_R_SYM(reloc->r_info);
#endif
        char *elf_sym = (char *) strtab + symtab[relsymidx].st_name;

        if (0 == strcmp (symbol, elf_sym)) {
            return (void *)(base + reloc->r_offset);
        }
    }

    return NULL;
}

static int mca_patcher_linux_get_aux_phent (void)
{
#if !defined(HAVE_SYS_AUXV_H)
#define MCA_PATCHER_LINUX_AUXV_BUF_LEN 16
    static const char *proc_auxv_filename = "/proc/self/auxv";
    static int phent = 0;
    ElfW(auxv_t) buffer[MCA_PATCHER_LINUX_AUXV_BUF_LEN];
    unsigned count;
    ssize_t nread;
    int fd;

    /* Can avoid lock here - worst case we'll read the file more than once */
    if (phent == 0) {
        fd = open(proc_auxv_filename, O_RDONLY);
        if (fd < 0) {
            opal_output_verbose (MCA_BASE_VERBOSE_ERROR, opal_patcher_base_framework.framework_output,
                                 "failed to open '%s' for reading: %s", proc_auxv_filename,
                                 strerror (errno));
            return OPAL_ERROR;
        }

        /* Use small buffer on the stack, avoid using malloc() */
        do {
            nread = read(fd, buffer, sizeof(buffer));
            if (nread < 0) {
                opal_output_verbose (MCA_BASE_VERBOSE_ERROR, opal_patcher_base_framework.framework_output,
                                     "failed to read %" PRIsize_t " bytes from %s (ret=%ld): %s", sizeof (buffer),
                                      proc_auxv_filename, nread, strerror (errno));
                break;
            }

            count = nread / sizeof(buffer[0]);
            for (unsigned i = 0 ; i < count && AT_NULL != buffer[i].a_type ; ++i) {
                if (AT_PHENT == buffer[i].a_type) {
                    phent = buffer[i].a_un.a_val;
                    opal_output_verbose (MCA_BASE_VERBOSE_ERROR, opal_patcher_base_framework.framework_output,
                                         "read phent from %s: %d", proc_auxv_filename, phent);
                    break;
                }
            }
        } while ((count > 0) && (phent == 0));

        close(fd);
    }

    return phent;
#else
    return getauxval (AT_PHENT);
#endif
}

static int
mca_patcher_linux_modify_got (ElfW(Addr) base, const ElfW(Phdr) *phdr, const char *phname,
                              int16_t phnum, int phent, mca_patcher_linux_dl_iter_context_t *ctx)
{
    long page_size = opal_getpagesize ();
    void **entry, *page;
    int ret;

    entry = mca_patcher_linux_get_got_entry (base, phdr, phnum, phent, ctx->patch->super.patch_symbol);
    if (entry == NULL) {
        return OPAL_SUCCESS;
    }

    page = (void *)((intptr_t)entry & ~(page_size - 1));
    ret = mprotect(page, page_size, PROT_READ|PROT_WRITE);
    if (ret < 0) {
        opal_output_verbose (MCA_BASE_VERBOSE_ERROR, opal_patcher_base_framework.framework_output,
                             "failed to modify GOT page %p to rw: %s", page, strerror (errno));
        return OPAL_ERR_NOT_SUPPORTED;
    }

    if (!ctx->remove) {
        if (*entry != (void *) ctx->patch->super.patch_value) {
            mca_patcher_linux_patch_got_t *patch_got = OBJ_NEW(mca_patcher_linux_patch_got_t);
            if (NULL == patch_got) {
                return OPAL_ERR_OUT_OF_RESOURCE;
            }

            opal_output_verbose (MCA_BASE_VERBOSE_TRACE, opal_patcher_base_framework.framework_output,
                                 "patch %p (%s): modifying got entry %p. original value %p. new value %p\n", (void *)ctx->patch,
                                 ctx->patch->super.patch_symbol, (void *) entry, *entry, (void *) ctx->patch->super.patch_value);

            patch_got->got_entry = entry;
            patch_got->got_orig = *entry;

            opal_list_append (&ctx->patch->patch_got_list, &patch_got->super);

            *entry = (void *) ctx->patch->super.patch_value;
        }
    } else {
        /* find the appropriate entry and restore the original value */
        mca_patcher_linux_patch_got_t *patch_got;
        OPAL_LIST_FOREACH_REV(patch_got, &ctx->patch->patch_got_list, mca_patcher_linux_patch_got_t) {
            if (patch_got->got_entry == entry) {
                opal_output_verbose (MCA_BASE_VERBOSE_TRACE, opal_patcher_base_framework.framework_output,
                                     "restoring got entry %p with original value %p\n", (void *) entry, patch_got->got_orig);
                if (*entry == (void *) ctx->patch->super.patch_value) {
                    *entry = patch_got->got_orig;
                }
                opal_list_remove_item (&ctx->patch->patch_got_list, &patch_got->super);
                OBJ_RELEASE(patch_got);
                break;
            }
        }
    }

    return OPAL_SUCCESS;
}

static int mca_patcher_linux_phdr_iterator(struct dl_phdr_info *info, size_t size, void *data)
{
    mca_patcher_linux_dl_iter_context_t *ctx = data;
    int phent;

    phent = mca_patcher_linux_get_aux_phent();
    if (phent <= 0) {
        opal_output_verbose (MCA_BASE_VERBOSE_ERROR, opal_patcher_base_framework.framework_output,
                             "failed to read phent size");
        ctx->status = OPAL_ERR_NOT_SUPPORTED;
        return -1;
    }

    ctx->status = mca_patcher_linux_modify_got (info->dlpi_addr, info->dlpi_phdr,
                                                info->dlpi_name, info->dlpi_phnum,
                                                phent, ctx);
    if (ctx->status == OPAL_SUCCESS) {
        return 0; /* continue iteration and patch all objects */
    } else {
        return -1; /* stop iteration if got a real error */
    }
}

/* called with lock held */
static int mca_patcher_linux_apply_patch (mca_patcher_linux_patch_t *patch)
{
    mca_patcher_linux_dl_iter_context_t ctx = {
        .patch    = patch,
        .remove   = false,
        .status   = OPAL_SUCCESS,
    };

    /* Avoid locks here because we don't modify ELF data structures.
     * Worst case the same symbol will be written more than once.
     */
    (void) dl_iterate_phdr(mca_patcher_linux_phdr_iterator, &ctx);

    return ctx.status;
}

static int mca_patcher_linux_remove_patch (mca_patcher_linux_patch_t *patch)
{
    mca_patcher_linux_dl_iter_context_t ctx = {
        .patch    = patch,
        .remove   = true,
        .status   = OPAL_SUCCESS,
    };

    /* Avoid locks here because we don't modify ELF data structures.
     * Worst case the same symbol will be written more than once.
     */
    (void) dl_iterate_phdr(mca_patcher_linux_phdr_iterator, &ctx);

    return ctx.status;
}

static void *mca_patcher_linux_dlopen(const char *filename, int flag)
{
    OPAL_PATCHER_BEGIN;
    mca_patcher_linux_patch_t *patch;
    void *handle;

    handle = orig_dlopen (filename, flag);
    if (handle != NULL) {
        /*
         * Every time a new object is loaded, we must update its relocations
         * with our list of patches (including dlopen itself). This code is less
         * efficient and will modify all existing objects every time, but good
         * enough.
         */
        opal_mutex_lock (&mca_patcher_linux_module.patch_list_mutex);
        OPAL_LIST_FOREACH(patch, &mca_patcher_linux_module.patch_list, mca_patcher_linux_patch_t) {
            if (!patch->super.patch_data_size) {
                opal_output_verbose (MCA_BASE_VERBOSE_INFO, opal_patcher_base_framework.framework_output,
                                     "in dlopen(), re-applying '%s' to %p", patch->super.patch_symbol, (void *) patch->super.patch_value);
                /* ignore hook binary patches */
                mca_patcher_linux_apply_patch (patch);
            }
        }
        opal_mutex_unlock (&mca_patcher_linux_module.patch_list_mutex);
    }

    OPAL_PATCHER_END;
    return handle;
}

static intptr_t mca_patcher_linux_get_orig (const char *symbol, void *replacement)
{
    const char *error;
    void *func_ptr;

    func_ptr = dlsym(RTLD_DEFAULT, symbol);
    if (func_ptr == replacement) {
        (void)dlerror();
        func_ptr = dlsym(RTLD_NEXT, symbol);
        if (func_ptr == NULL) {
            error = dlerror();
            opal_output_verbose (MCA_BASE_VERBOSE_ERROR, opal_patcher_base_framework.framework_output,
                                 "could not find address of original %s(): %s", symbol, error ? error : "Unknown error");
        }
    }

    opal_output_verbose (MCA_BASE_VERBOSE_INFO, opal_patcher_base_framework.framework_output,
                         "original %s() is at %p", symbol, func_ptr);

    return (intptr_t) func_ptr;
}

static int mca_patcher_linux_patch_symbol (const char *symbol_name, uintptr_t replacement, uintptr_t *orig)
{
    mca_patcher_linux_patch_t *patch = OBJ_NEW(mca_patcher_linux_patch_t);
    int rc;

    if (OPAL_UNLIKELY(NULL == patch)) {
        return OPAL_ERR_OUT_OF_RESOURCE;
    }

    patch->super.patch_symbol = strdup (symbol_name);
    if (NULL == patch->super.patch_symbol) {
        OBJ_RELEASE(patch);
        return OPAL_ERR_OUT_OF_RESOURCE;
    }

    patch->super.patch_value = mca_patcher_base_addr_text (replacement);
    patch->super.patch_restore = (mca_patcher_base_restore_fn_t) mca_patcher_linux_remove_patch;

    /* Take lock first to handle a possible race where dlopen() is called
     * from another thread and we may end up not patching it.
     */
    opal_mutex_lock (&mca_patcher_linux_module.patch_list_mutex);
    do {
        rc = mca_patcher_base_patch_hook (&mca_patcher_linux_module, patch->super.patch_value);
        if (OPAL_SUCCESS != rc) {
            OBJ_RELEASE(patch);
            break;
        }

        rc = mca_patcher_linux_apply_patch (patch);
        if (OPAL_SUCCESS != rc) {
            OBJ_RELEASE(patch);
            break;
        }

        *orig = mca_patcher_linux_get_orig (patch->super.patch_symbol, (void *) replacement);

        opal_list_append (&mca_patcher_linux_module.patch_list, &patch->super.super);
    } while (0);
    opal_mutex_unlock (&mca_patcher_linux_module.patch_list_mutex);

    return rc;
}

/* called with lock held */
static int mca_patcher_linux_install_dlopen (void)
{
    return mca_patcher_linux_patch_symbol ("dlopen", (uintptr_t) mca_patcher_linux_dlopen,
                                           (uintptr_t *) &orig_dlopen);
}

static int mca_patcher_linux_init (void)
{
    return mca_patcher_linux_install_dlopen ();
}

mca_patcher_base_module_t mca_patcher_linux_module = {
    .patch_init = mca_patcher_linux_init,
    .patch_symbol = mca_patcher_linux_patch_symbol,
};