utils.c 16.8 KB
Newer Older
1
2
3
4
5
6
// Copyright © 2017 Collabora Ltd

// This file is part of libcapsule.

// libcapsule is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
Simon McVittie's avatar
Simon McVittie committed
7
// published by the Free Software Foundation; either version 2.1 of the
8
9
10
11
12
13
14
15
16
17
// License, or (at your option) any later version.

// libcapsule 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 Lesser General Public
// License along with libcapsule.  If not, see <http://www.gnu.org/licenses/>.

18
#include <assert.h>
19
20
21
22
#include <sys/param.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
23
#include <stdarg.h>
24
#include <stdio.h>
25
#include <stdlib.h>
26
#include "debug.h"
27
#include "utils.h"
28
29

unsigned long debug_flags;
30

31
32
33
34
35
36
// ==========================================================================
// these are for finding entries in the dynamic section
// note that tha d_un.d_ptr member may be pre-offset by the
// linker, or we may beed to adjust it by the value of base ourselves:
// this is effectively private linker information and there's no
// hard and fast rule:
37
38
const void *
fix_addr (const void *base, ElfW(Addr) offset_or_addr)
39
{
40
41
42
43
44
45
46
47
48
49
    if (offset_or_addr < (ElfW(Addr)) base)
    {
        // Assume it's an offset, so an address relative to addr
        return base + offset_or_addr;
    }
    else
    {
        // Assume it's an absolute address
        return (const void *) offset_or_addr;
    }
50
51
}

52
53
54
55
56
57
58
59
60
61
62
63
const ElfW(Dyn) *
find_dyn (ElfW(Addr) base, void *start, int what)
{
    ElfW(Dyn) *entry = start + base;

    for( ; entry->d_tag != DT_NULL; entry++ )
        if( entry->d_tag == what )
            return entry;

    return NULL;
}

Simon McVittie's avatar
Simon McVittie committed
64
size_t
65
66
67
find_value (ElfW(Addr) base, void *start, int what)
{
    const ElfW(Dyn) *entry = find_dyn( base, start, what );
Simon McVittie's avatar
Simon McVittie committed
68
    return entry ? entry->d_un.d_val : (size_t) -1;
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
}

ElfW(Addr)
find_ptr (ElfW(Addr) base, void *start, int what)
{
    const ElfW(Dyn) *entry = find_dyn( base, start, what );

    if( entry )
    {
        if( entry->d_un.d_ptr < base )
            return base + entry->d_un.d_ptr;
        else
            return entry->d_un.d_ptr;
    }

    return (ElfW(Addr)) NULL;
}

87
/*
88
89
 * dynamic_section_find_strtab:
 * @start: Array of dynamic section entries
90
91
92
93
94
95
 * @base: Starting address of the shared object in memory
 * @siz: (out) (optional): Used to return the length of the string
 *  table
 *
 * Find the string table for the given dynamic section.
 *
96
97
98
 * Returns: (nullable): The string table, a series of concatenated
 *  0-terminated strings whose total size is written through @siz if
 *  non-%NULL, or %NULL if not found
99
 */
100
const char *
101
dynamic_section_find_strtab (const ElfW(Dyn) *entries, const void *base, size_t *siz)
102
{
103
    const ElfW(Dyn) *entry;
Simon McVittie's avatar
Simon McVittie committed
104
    ElfW(Addr) stab = 0;
105

106
    for( entry = entries; entry->d_tag != DT_NULL; entry++ )
107
    {
108
        if( entry->d_tag == DT_STRTAB )
109
        {
110
            stab = entry->d_un.d_ptr;
111
        }
112
        else if( entry->d_tag == DT_STRSZ  )
113
114
115
116
117
        {
            if( siz )
                *siz = entry->d_un.d_val;
        }
    }
118

119
    if (stab == 0)
120
    {
121
        return NULL;
122
123
124
125
126
127
128
129
130
    }
    else if (stab < (ElfW(Addr)) base)
    {
        return base + stab;
    }
    else
    {
        return (const char *) stab;
    }
131
132
}

133
134
135
136
/*
 * find_symbol:
 * @idx: The symbol index
 * @stab: (array element-type=ElfW(Sym)): The symbol table
137
 * @symsz: The length of the symbol table in bytes
138
 * @str: The string table
139
 * @strsz: The length of the string table in bytes
140
141
142
143
144
 * @name: (out) (optional): Used to return the name, a pointer into @str
 *
 * If @idx is in-bounds for @stab, return a pointer to the @idx'th
 * entry in @stab. Otherwise return %NULL.
 */
145
const ElfW(Sym) *
146
find_symbol (int idx, const ElfW(Sym) *stab, size_t symsz, const char *str, size_t strsz, const char **name)
147
{
148
    const ElfW(Sym) *target = stab + idx;
149
150
151
152
153
154
155

    if( idx < 0 )
        return NULL;

    // we could just accept the index as legitimate but then we'd
    // run the risk of popping off into an unknown hyperspace coordinate
    // this way we stop if the target is past the known end of the table:
156
157
    if( (idx + 1) * sizeof(*target) > symsz )
        return NULL;
158

159
160
161
162
    if( name )
        *name = str + target->st_name;

    return target;
163
164
165
166
}

// ==========================================================================

167
168
169
// like strncpy except it guarantees the final byte is NUL in
// case we truncated the string. does not yet warn you in any
// way about truncation though, should probably fix that:
170
171
172
173
174
175
176
char *safe_strncpy (char *dest, const char *src, size_t n)
{
    char *rv = strncpy( dest, src, n );
    dest[ n - 1 ] = '\0';
    return rv;
}

177
178
// prefix is the root of the external tree we're patching in
// with libcapsule, path is what we're trying to resolve if
179
// it is a symlink. path must have at least PATH_MAX chars allocated.
180
181
182
183
184
185
//
// Designed to be called repeatedly, starting with an ABSOLUTE
// path the first time. Will write the resolved link back into
// path each time and return true, until fed a path which is
// not a symlink, at which point it will leave path alone and
// return false:
186
int resolve_link(const char *prefix, char path[PATH_MAX])
187
188
189
{
    int dfd;
    char rl[PATH_MAX];
190
    char dir[PATH_MAX];
191
192
193
194
195
196
197
198
199
    char *end = NULL;
    int rv = 0;

    safe_strncpy( dir, path, PATH_MAX );
    end = strrchr( dir, '/' );

    if( end )
        *end = '\0';
    else
200
201
202
203
        strcpy( dir, "." ); // not sure this is right, FIXME?
                            // but as long as the first call to us
                            // in any sequence was an absolute path
                            // this will never come up
204
205
206
207
208
209
210
    dfd = open( dir, O_RDONLY );

    if( dfd < 0 )
        return 0;

    rv = readlinkat( dfd, path, rl, sizeof(rl) );

211
212
213
214
215
216
217
    if( rv == sizeof(rl) )
    {
        // Either rl was truncated, or there is no longer space for '\0'
        rv = -1;
        goto out;
    }

218
219
220
221
222
223
    if( rv >= 0 )
    {
        rl[ rv ] = '\0';

        if( rl[0] == '/' )
        {
224
            if( build_filename( path, PATH_MAX, prefix, rl, NULL ) >= PATH_MAX )
225
226
227
            {
                goto out;
            }
228
229
230
        }
        else
        {
231
            if( build_filename( path, PATH_MAX, dir, rl, NULL ) >= PATH_MAX )
232
233
234
            {
                goto out;
            }
235
236
237
        }
    }

238
out:
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
    close( dfd );

    return rv != -1;
}

// todo - check this properly for actual word boundaries and
// make it warn about unknown debug keywords:
void set_debug_flags (const char *control)
{
    debug_flags = DEBUG_NONE;

    if ( !control )
        return;

    if( strstr( control, "path"     ) ) debug_flags |= DEBUG_PATH;
    if( strstr( control, "search"   ) ) debug_flags |= DEBUG_SEARCH;
    if( strstr( control, "ldcache"  ) ) debug_flags |= DEBUG_LDCACHE;
    if( strstr( control, "capsule"  ) ) debug_flags |= DEBUG_CAPSULE;
    if( strstr( control, "mprotect" ) ) debug_flags |= DEBUG_MPROTECT;
    if( strstr( control, "wrappers" ) ) debug_flags |= DEBUG_WRAPPERS;
    if( strstr( control, "reloc"    ) ) debug_flags |= DEBUG_RELOCS;
260
    if( strstr( control, "elf"      ) ) debug_flags |= DEBUG_ELF;
261
    if( strstr( control, "dlfunc"   ) ) debug_flags |= DEBUG_DLFUNC;
262
    if( strstr( control, "tool"     ) ) debug_flags |= DEBUG_TOOL;
263
264
    if( strstr( control, "all"      ) ) debug_flags |= DEBUG_ALL;

265
266
267
    if( !debug_flags )
        return;

268
269
270
271
272
273
274
    fprintf(stderr, "capsule debug flags: \n"
            "  path    : %c # path manipulation and translation"           "\n"
            "  search  : %c # searching for DSOs"                          "\n"
            "  ldcache : %c # loading/processing the ld cache"             "\n"
            "  capsule : %c # setting up the proxy capsule"                "\n"
            "  mprotect: %c # handling mprotect (for RELRO)"               "\n"
            "  wrappers: %c # function wrappers installed in the capsule"  "\n"
275
            "  reloc   : %c # patching capsule symbols into external DSOs" "\n"
276
            "  dlfunc  : %c # special handling of dlopen/dlsym calls"      "\n"
277
278
            "  elf     : %c # detailed ELF introspection logging"          "\n"
            "  tool    : %c # command-line tools"                          "\n",
279
280
281
282
283
284
            (debug_flags & DEBUG_PATH    ) ? 'Y' : 'n' ,
            (debug_flags & DEBUG_SEARCH  ) ? 'Y' : 'n' ,
            (debug_flags & DEBUG_LDCACHE ) ? 'Y' : 'n' ,
            (debug_flags & DEBUG_CAPSULE ) ? 'Y' : 'n' ,
            (debug_flags & DEBUG_MPROTECT) ? 'Y' : 'n' ,
            (debug_flags & DEBUG_WRAPPERS) ? 'Y' : 'n' ,
285
            (debug_flags & DEBUG_RELOCS  ) ? 'Y' : 'n' ,
286
            (debug_flags & DEBUG_DLFUNC  ) ? 'Y' : 'n' ,
287
288
            (debug_flags & DEBUG_ELF     ) ? 'Y' : 'n' ,
            (debug_flags & DEBUG_TOOL    ) ? 'Y' : 'n' );
289
}
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307

// soname: bare libfoo.so.X style name
// path: [possibly absolute] path to DSO
// return true if soname: libFOO.so.X matches
// path: /path/to/libFOO.so.X.Y or /path/to/libFOO.so.X
int soname_matches_path (const char *soname, const char *path)
{
    const char *path_soname = strrchr( path, '/' );
    const char *pattern = path_soname ? path_soname + 1: path;
    const size_t slen = strlen( soname );

    if( strncmp( soname, pattern, slen ) != 0 )
        return 0;

    const char *end = pattern + slen;

    return ( *end == '\0' || *end == '.' );
}
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
/*
 * build_filename_va:
 * @buf: a buffer
 * @len: length of buffer
 * @first_path: an absolute or relative path
 * @ap: further path segments
 *
 * Fill @buf with a copy of @first_path, with subsequent path segments
 * appended to it.
 *
 * Returns: The number of bytes that would have been used in buf, not
 *  including the '\0', if there was enough space. If this is >= len,
 *  then truncation has occurred.
 */
size_t
build_filename_va (char *buf, size_t len, const char *first_path, va_list ap)
{
    const char *path;
    size_t used = 0;
    int first = 1;
    int need_separator = 0;


    if( len > 0 )
        *buf = '\0';

    for( path = first_path, first = 1;
         path != NULL;
         path = va_arg( ap, const char * ), first = 0)
    {
        size_t path_len;

        // Collapse any leading '//' to '/'
        while( path[0] == '/' && path[1] == '/' )
            path++;

        // If this is not the first path segment, strip any leading '/'
        if( path[0] == '/' && !first )
            path++;

        path_len = strlen( path );

        // Collapse any trailing '/' to nothing, unless this is the
        // first path segment, in which case collapse them to just '/'
        while( path_len > (first ? 1 : 0) && path[path_len - 1] == '/' )
        {
            path_len--;
        }

        // Ensure there is a '/' before we append path if necessary
        if( need_separator )
        {
            used++;
            if( used < len )
            {
                buf[used - 1] = '/';
                buf[used] = '\0';
            }
        }

        // If there's still any space left, try to append the path
        if( used < len )
        {
            strncpy( buf + used, path, MIN( len - used, path_len + 1 ) );
            buf[len - 1] = '\0';
        }

        used += path_len;

        // Next time, we need to append a separator, unless this was
        // the first path segment and it was '/'
        need_separator = (path_len == 0 || path[path_len - 1] != '/');
    }

    va_end( ap );
    return used;
}

/*
 * build_filename:
 * @buf: a buffer
 * @len: length of buffer
 * @first_path: an absolute or relative path
 * @...: further path segments
 *
 * Fill @buf with a copy of @first_path, with subsequent path segments
 * appended to it.
 *
 * Returns: The number of bytes that would have been used in buf, not
 *  including the '\0', if there was enough space. If this is >= len,
 *  then truncation has occurred.
 */
size_t
build_filename (char *buf, size_t len, const char *first_path, ...)
{
    size_t used;
    va_list ap;

    va_start( ap, first_path );
    used = build_filename_va( buf, len, first_path, ap );
    va_end( ap );

    return used;
}

/*
 * build_filename_alloc:
 * @first_path: an absolute or relative path
 * @...: further path segments
 *
 * Allocate and return a string built from @first_path and subsequent
 * segments. Abort if there is not enough memory.
 *
 * Returns: A string that can be freed with free()
 */
char *
build_filename_alloc (const char *first_path, ...)
{
    char *buf;
    size_t allocate;
    size_t len;
    va_list ap;

    // Do a first pass to count how much space we're going to need
    va_start( ap, first_path );
    // We need an extra byte for the "\0" which isn't included in the
    // result, consistent with strlcpy()
    allocate = build_filename_va( NULL, 0, first_path, ap ) + 1;
    va_end( ap );

    buf = xrealloc( NULL, allocate );

    // Iterate over the arguments again to fill buf
    va_start( ap, first_path );
    len = build_filename_va( buf, allocate, first_path, ap );
    va_end( ap );

    // build_filename_va() returns the same thing every time. In
    // particular this means truncation did not occur, because that
    // would be indicated by len >= allocate.
    assert( len + 1 == allocate );

    return buf;
}

454
455
456
ptr_list *
ptr_list_alloc(size_t size)
{
457
    ptr_list *list = xcalloc( 1, sizeof(ptr_list) );
458

459
460
461
462
    list->loc = xcalloc( size, sizeof(ptr_item) );
    list->allocated = size;
    list->next = 0;
    return list;
463
464
465
466
467
468
469
470
471
472
473
474
475
}

void
ptr_list_free (ptr_list *list)
{
    free( list->loc );
    list->loc = NULL;
    list->allocated = 0;
    list->next = 0;
    free( list );
}

void
476
ptr_list_push_addr (ptr_list *list, ElfW(Addr) addr)
477
478
479
{
    if( list->next >= list->allocated )
    {
480
        list->loc = xrealloc( list->loc,
481
482
483
484
485
486
487
                             (list->allocated + 16) * sizeof(ptr_item) );
        list->allocated += 16;
    }

    list->loc[ list->next++ ].addr = addr;
}

488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519

void
ptr_list_push_ptr (ptr_list *list, void *ptr)
{
    if( list->next >= list->allocated )
    {
        list->loc = realloc( list->loc,
                             (list->allocated + 16) * sizeof(ptr_item) );
        if( !list->loc )
        {
            fprintf( stderr, "failed to realloc ptr_list\n" );
            abort();
        }

        list->allocated += 16;
    }

    list->loc[ list->next++ ].ptr = ptr;
}

int
ptr_list_add_ptr (ptr_list *list, void *ptr, ptrcmp equals)
{
    for( size_t n = 0; n < list->next; n++ )
        if( equals( list->loc[ n ].ptr, ptr ) )
            return 0;

    ptr_list_push_ptr( list, ptr );

    return 1;
}

520
521
522
523
524
525
526
527
528
529
530
int
ptr_list_contains (ptr_list *list, ElfW(Addr) addr)
{
    if( list->next == 0 )
        return 0;

    for( size_t n = 0; n < list->next; n++ )
        if( list->loc[ n ].addr == addr )
            return 1;
    return 0;
}
531

532
533
534
535
536
537
538
539
540
void *
ptr_list_nth_ptr (ptr_list *list, size_t nth)
{
    if( nth < list->next )
        return list->loc[ nth ].ptr;

    return NULL;
}

541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
void
oom( void )
{
    fprintf( stderr, "libcapsule: out of memory\n" );
    abort();
}

char *
xstrdup( const char *s )
{
    char *ret = strdup( s );

    if (s != NULL && ret == NULL)
        oom();

    return ret;
}

void *
xrealloc( void *ptr, size_t size )
{
    void *ret = realloc( ptr, size );

    if( ptr != NULL && size != 0 && ret == NULL )
        oom();

    return ret;
}

void *
xcalloc( size_t n, size_t size )
{
    void *ret = calloc( n, size );

    if( n != 0 && size != 0 && ret == NULL )
        oom();

    return ret;
}
580

581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
int
xasprintf( char **dest, const char *format, ...)
{
    int ret;
    va_list ap;

    va_start( ap, format );
    ret = vasprintf( dest, format, ap );
    va_end( ap );

    if( ret < 0 )
        oom();

    return ret;
}

597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
/*
 * _capsule_set_error_literal:
 * @code_dest: (out) (optional): used to return an errno value
 * @message_dest: (out) (optional) (transfer full): used to return an
 *  error message
 * @code: an errno value
 * @message: an error message
 *
 * Set an error code, like g_set_error_literal().
 */
void
_capsule_set_error_literal( int *code_dest, char **message_dest,
                            int code, const char *message )
{
    if( code_dest != NULL )
        *code_dest = code;

    if( message_dest != NULL )
        *message_dest = xstrdup( message );
}

/*
 * _capsule_set_error:
 * @code_dest: (out) (optional): used to return an errno value
 * @message_dest: (out) (optional) (transfer full): used to return an
 *  error message
 * @code: an errno value
 * @message: an error message
 *
 * Set an error code, like g_set_error().
 */
void
_capsule_set_error( int *code_dest, char **message_dest,
                    int code, const char *format,
                    ... )
{
    va_list ap;

    if( code_dest != NULL )
        *code_dest = code;

    if( message_dest != NULL )
    {
        va_start( ap, format );

        if( vasprintf( message_dest, format, ap ) < 0 )
            oom();

        va_end( ap );
    }
}