File: symbol_loader.c

package info (click to toggle)
libpulp 0.3.16-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,976 kB
  • sloc: ansic: 11,792; python: 1,216; sh: 881; makefile: 871; cpp: 582; asm: 387
file content (415 lines) | stat: -rw-r--r-- 13,092 bytes parent folder | download
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
/*
 *  libpulp - User-space Livepatching Library
 *
 *  Copyright (C) 2021-2025 SUSE Software Solutions GmbH
 *
 *  This file is part of libpulp.
 *
 *  libpulp is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  libpulp is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with libpulp.  If not, see <http://www.gnu.org/licenses/>.
 */

#define _GNU_SOURCE

#include <dlfcn.h>
#include <elf.h>
#include <err.h>
#include <fcntl.h>
#include <fnmatch.h>
#include <gnu/libc-version.h>
#include <grp.h>
#include <limits.h>
#include <link.h>
#include <pthread.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include <sys/param.h>
#include <stdarg.h>

#include "symbol_loader.h"
#include "ld_rtld.h"
#ifndef WARN
#include "ulp_common.h"
#include "error.h"
#endif

extern const char *__progname;

/** @brief Get symbol by its name
 *
 * Example: calling this function with name = 'printf' will return
 * the ELF symbol referring to the printf function.
 *
 * @param dynsym: The symbol table.
 * @param dynstr: The symbol string table.
 * @param len: The length of dynsym
 * @param name: Name of the symbol to search.
 *
 * @return a pointer to the wanted symbol in the symbol table.
 */
static Elf64_Sym *
get_symbol_by_name(Elf64_Sym dynsym[], const char *dynstr, int len,
                   const char *name)
{
  int i;
  for (i = 0; i < len; i++) {
    /* st_name contains the offset of the symbol's name on the dynstr table. */
    if (!strcmp(dynstr + dynsym[i].st_name, name))
      return &dynsym[i];
  }

  /* Symbol not found.  */
  return NULL;
}

/** struct containing the parameters that will be passed to dl_find_symbol.  */
struct dl_iterate_arg
{
  /* Input.  */

  /** Name of the .so file to find the symbol. */
  const char *library;

  /** The name of the wanted symbol. */
  const char *symbol;

  /* Output.  */

  /** The address of the symbol in the program. */
  void *symbol_addr;

  /** The size of the symbol.  */
  size_t symbol_size;

  /** The address bias where the library was loaded.  */
  uintptr_t bias_addr;

  /** The TLS module index of the library.  */
  int tls_index;
};

/** @brief dl_iterate_phdr callback.
 *
 * This function do the hard work into gathering the necessary informations
 * about the symbols in the process. It works by being a callback to
 * dl_iterate_phdr (read its manpage), which pass into "info" the ELF program
 * headers (phdr) of:
 *  1. The current binary.
 *  2. Each dynamic library (.so) loaded with the program.
 *
 * Then it parses the structures there to find the .dynsym, .dynstr, and .hash
 * sections containing respectively:
 *
 *  1. The dynamic symbol table.
 *  2. The symbol string table with the name of each symbol.
 *  3. The hash table (only used to find the number of symbol in .dynsym).
 *
 * The library name which we want to find its symbol, and the wanted symbol
 * is passed on struct dl_iterate_arg, which is passed on the "data" argument.
 * If library name is NULL, this function will find the first occurence of
 * "symbol" in the entire program. The output of this function is also written
 * on the struct pointed by "data", and it is a pointer to the symbol in the
 * program.
 *
 * Good references to understeand how to parse the ELF program headers are:
 *  1. The elf.h header.
 *  2. 'dl_iterate_phdr' manpage.
 *  3. 'Learing Linux Binary Analysis' (Elfmaster, 2016).
 *  4. 'Linkers and Loaders' (Levine, 1999).
 *
 * @param info: Program header infos (see dl_iterate_phdr).
 * @param size: sizeof(dl_phdr_info).
 * @param data: Data to this function. Also used as return value.
 *
 * @return 1 when done; 0 to request next library.
 */
static int
dl_find_symbol(struct dl_phdr_info *info, size_t size, void *data)
{
  /* We call the symbol table as dynsym because that is most likely to be the
   * section in DT_SYMTAB.  However, this is not necessary true in all cases.
   */
  Elf64_Sym *dynsym = NULL;
  const char *dynstr = NULL;
  int *hash_addr;

  int i;
  int num_symbols = 0;
  struct dl_iterate_arg *args = (struct dl_iterate_arg *)data;

  /* Sanity check if size matches the size of the struct.  */
  if (size != sizeof(*info)) {
    libpulp_errx(EXIT_FAILURE, "dl_phdr_info size is unexpected");
    return 0;
  }

  /* Initialize output value as being NULL (symbol not found).  */
  args->symbol_addr = NULL;
  args->symbol_size = 0;

  /* Initialize TLS index with invalid value.  */
  args->tls_index = -1;

  /* Check if the current info is the library we want to find the symbols.  */
  if (args->library && !strstr(info->dlpi_name, args->library))
    return 0;

  /* Pointers to linux-vdso.so are invalid, so skip this library.  */
  if (!strcmp(info->dlpi_name, "linux-vdso.so.1"))
    return 0;

  /* Iterate each program headers to find the information we need. */
  for (i = 0; i < info->dlpi_phnum; i++) {
    const Elf64_Phdr *phdr_addr = &info->dlpi_phdr[i];

    /* We are interested in symbols, so look for the dynamic symbols in the
     * PT_DYNAMIC tag. */
    if (phdr_addr->p_type == PT_DYNAMIC) {

      /* The address in p_paddr is relative to the .so header, so we need to
       * add the base address where the .so was mapped in the process. In case
       * it is the binary itself, dlpi_addr is zero.  */
      Elf64_Dyn *dyn = (Elf64_Dyn *)(info->dlpi_addr + phdr_addr->p_paddr);

      /* Iterate over each tag in this section.  */
      for (; dyn->d_tag != DT_NULL; dyn++) {
        switch (dyn->d_tag) {
          case DT_SYMTAB:
            dynsym = (Elf64_Sym *)dyn->d_un.d_ptr;
            break;

          case DT_STRTAB:
            dynstr = (const char *)dyn->d_un.d_ptr;
            break;

          case DT_SYMENT:
            /* This section stores the size of a symbol entry. So compare it
             * with the size of Elf64_Sym as a sanity check.  */
            if (dyn->d_un.d_val != sizeof(Elf64_Sym)) {
              libpulp_errx(EXIT_FAILURE, "DT_SYMENT value of %s is unexpected",
                           info->dlpi_name);
              return 0;
            }
            break;

          case DT_HASH:
            /* Look at the hash section for the number of the symbols in the
             * symbol table.  This section structure in memory is:
             *
             * hash_t nbuckets;
             * hash_t nchains;
             * hash_t buckets[nbuckets];
             * hash_t chain[nchains];
             *
             * hash_t is either int32_t or int64_t according to the arch.
             * On x86_64 it is 32-bits.
             * */
            hash_addr = (int *)dyn->d_un.d_ptr;
            num_symbols = hash_addr[1]; /* Get nchains.  */
            break;
        }
      }
    }
  }

  /* With the symbol table identified, find the wanted symbol.  */
  if (dynstr && dynsym) {
    Elf64_Sym *sym;
    args->tls_index = info->dlpi_tls_modid;

    sym = get_symbol_by_name(dynsym, dynstr, num_symbols, args->symbol);
    if (sym) {
      args->symbol_addr = (void *)(sym->st_value);
      args->symbol_size = sym->st_size;
    }

    args->bias_addr = info->dlpi_addr;
    /* Alert dl_iterate_phdr that we are finished.  */
    return 1;
  }
  return 0;
}

/** @brief Get the address of a loaded symbol from library.
 *
 * This function will return the address where the symbol with the name
 * "symbol" from the library "library" was allocated in memory.
 *
 * Example: calling this function with symbol = "printf" will return
 * the address where the printf function is.
 *
 * @param library: name of the library where the symbol is from.
 * @param symbol: name of the wanted symbol
 * @param old_faddr: Offset of symbol, as found during packing.
 * @param psize: pointer to a size_t which will hold the size of the symbol.
 *
 * @return the address where the symbol was allocated nn the program.
 */
void *
get_loaded_symbol_addr_size(const char *library, const char *symbol,
                            void *old_faddr, size_t *psize)
{
  /* Check if the current info is the program's binary itself.  In that case
   * we must handle things somewhat differently.  */
  if (library == NULL || !strcmp(library, __progname)) {
    library = "";
  }

  struct dl_iterate_arg arg = { .library = library, .symbol = symbol };
  dl_iterate_phdr(dl_find_symbol, &arg);

  if (old_faddr != NULL && arg.symbol_addr != old_faddr) {
    WARN("Symbol requested not found in .dynsym. Using address from .ulp");

    if (psize)
      *psize = 0; // There is no way we know the symbol size.
    return arg.bias_addr + old_faddr;
  }

  if (arg.symbol_addr == NULL) {
    if (psize)
      *psize = 0;

    /* Symbol not found.  */
    return NULL;
  }

  if (psize)
    *psize = arg.symbol_size;

  return arg.bias_addr + arg.symbol_addr;
}

static int
dl_find_base_addr(struct dl_phdr_info *info, size_t size, void *data)
{
  struct dl_iterate_arg *args = (struct dl_iterate_arg *)data;

  /* Highly improvable that any library will have this base address.  */
  args->bias_addr = 0xFF;

  /* Initialize TLS index with an incorrect value.  */
  args->tls_index = -1;

  /* Sanity check if size matches the size of the struct.  */
  if (size != sizeof(*info)) {
    libpulp_errx(EXIT_FAILURE, "dl_phdr_info size is unexpected");
    return 0;
  }

  /* Pointers to linux-vdso.so are invalid, so skip this library.  */
  if (!strcmp(info->dlpi_name, "linux-vdso.so.1"))
    return 0;

  /* Check if the current info is the library we want to find the symbols.  */
  if (args->library && !strstr(info->dlpi_name, args->library))
    return 0;

  /* Found.  Set symbol_addr as the base address of library.  */
  args->bias_addr = info->dlpi_addr;
  args->tls_index = info->dlpi_tls_modid;

  /* Alert dl_iterate that we are finished.  */
  return 1;
}

void *
get_loaded_library_base_addr(const char *library)
{

  /* Check if the current info is the program's binary itself.  In that case
   * we must handle things somewhat differently.  */
  if (library == NULL || !strcmp(library, __progname)) {
    library = "";
  }

  struct dl_iterate_arg arg = { .library = library };
  dl_iterate_phdr(dl_find_base_addr, &arg);

  return (void *)arg.bias_addr;
}

int
get_loaded_library_tls_index(const char *library)
{
  /* Check if the current info is the program's binary itself.  In that case
   * we must handle things somewhat differently.  */
  if (library == NULL || !strcmp(library, __progname)) {
    library = "";
  }

  struct dl_iterate_arg arg = { .library = library };
  dl_iterate_phdr(dl_find_base_addr, &arg);

  return arg.tls_index;
}

/** @brief Find address of dl functions lock.
 *
 * This function finds the locks which are held when dlsym and dlmsym functions
 * are called. This is necessary because of:
 *   * dlsym behaviour changes depending of where it is being called.
 * Proof of this can be found in glibc's dlfcn/dlsym.c. Notice that
 * RETURN_ADDRESS(0) is passed to internal functions, which gets the previous
 * frame address. The practical behaviour is that if we interpose dlsym, then
 * software that interposes functions from glibc will find libpulp functions
 * instead, and libpulp will find the software interposed functions, creating
 * an infinite recursion.
 *
 * Therefore, we can not interpose dlsym and use a custom lock, as we do for
 * the other functions, and we instead check if the dlsym lock is held.
 */
void
get_ld_global_locks(pthread_mutex_t **dl_load_lock, pthread_mutex_t **dl_load_write_lock)
{
  char libc_ver[32];
  const char *tok;
  int major, minor;

  void *rtld_global = get_loaded_symbol_addr(LD_LINUX, "_rtld_global", NULL);
  if (!rtld_global) {
    libpulp_crash("symbol _rtld_global not found in " LD_LINUX "\n");
  }

  strcpy(libc_ver, gnu_get_libc_version());

  tok = strtok(libc_ver, ".");
  major = atoi(tok);
  tok = strtok(NULL, ".");
  minor = atoi(tok);

  if (major == 2) {
    if (31 <= minor && minor < 35) {
      struct rtld_global__2_31 *rtld = rtld_global;
      *dl_load_lock = &rtld->_dl_load_lock.mutex;
      *dl_load_write_lock = &rtld->_dl_load_write_lock.mutex;
    }
    else if (35 <= minor && minor < 42) {
      struct rtld_global__2_35 *rtld = rtld_global;
      *dl_load_lock = &rtld->_dl_load_lock.mutex;
      *dl_load_write_lock = &rtld->_dl_load_write_lock.mutex;
    }
    else if (42 <= minor) {
      struct rtld_global__2_42 *rtld = rtld_global;
      *dl_load_lock = &rtld->_dl_load_lock.mutex;
      *dl_load_write_lock = &rtld->_dl_load_write_lock.mutex;
    }
    else {
      libpulp_crash("glibc version %d.%d is unsupported\n", major, minor);
    }
  }
}