Debian Codegraph @

src/binreloc/binreloc.c

raw symbols SCIP
1 /*
2 * BinReloc - a library for creating relocatable executables
3 * Written by: Hongli Lai <[email protected]>
4 * http://autopackage.org/
5 *
6 * This source code is public domain. You can relicense this code
7 * under whatever license you want.
8 *
9 * See http://autopackage.org/docs/binreloc/ for
10 * more information and how to use this.
11 */
12
13 #ifndef __BINRELOC_C__
14 #define __BINRELOC_C__
15
16 #ifndef __WIN32__
17 #ifdef HAVE_CONFIG_H
18 #include "config.h"
19 #endif
20 #else
21 #include "../win32/config.h"
22 #endif
23
24 #ifdef ENABLE_BINRELOC
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <unistd.h>
28 #endif /* ENABLE_BINRELOC */
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <limits.h>
32 #include <string.h>
33 #include "binreloc.h"
34
35 #ifdef __cplusplus
36 extern "C" {
37 #endif /* __cplusplus */
38
39
40
41 /** @internal
42 * Find the canonical filename of the executable. Returns the filename
43 * (which must be freed) or NULL on error. If the parameter 'error' is
44 * not NULL, the error code will be stored there, if an error occured.
45 */
46 static char *
47 _br_find_exe (BrInitError *error)
48 {
49 #ifndef ENABLE_BINRELOC
50 if (error)
51 *error = BR_INIT_ERROR_DISABLED;
52 return NULL;
53 #else
54 char *path, *path2, *line, *result;
55 size_t buf_size;
56 ssize_t size;
57 struct stat stat_buf;
58 FILE *f;
59
60 /* Read from /proc/self/exe (symlink) */
61 if (sizeof (path) > SSIZE_MAX)
62 buf_size = SSIZE_MAX - 1;
63 else
64 buf_size = PATH_MAX - 1;
65 path = (char *) malloc (buf_size);
66 if (path == NULL) {
67 /* Cannot allocate memory. */
68 if (error)
69 *error = BR_INIT_ERROR_NOMEM;
70 return NULL;
71 }
72 path2 = (char *) malloc (buf_size);
73 if (path2 == NULL) {
74 /* Cannot allocate memory. */
75 if (error)
76 *error = BR_INIT_ERROR_NOMEM;
77 free (path);
78 return NULL;
79 }
80
81 strncpy (path2, "/proc/self/exe", buf_size - 1);
82
83 while (1) {
84 int i;
85
86 size = readlink (path2, path, buf_size - 1);
87 if (size == -1) {
88 /* Error. */
89 free (path2);
90 break;
91 }
92
93 /* readlink() success. */
94 path[size] = '\0';
95
96 /* Check whether the symlink's target is also a symlink.
97 * We want to get the final target. */
98 i = stat (path, &stat_buf);
99 if (i == -1) {
100 /* Error. */
101 free (path2);
102 break;
103 }
104
105 /* stat() success. */
106 if (!S_ISLNK (stat_buf.st_mode)) {
107 /* path is not a symlink. Done. */
108 free (path2);
109 return path;
110 }
111
112 /* path is a symlink. Continue loop and resolve this. */
113 strncpy (path, path2, buf_size - 1);
114 }
115
116
117 /* readlink() or stat() failed; this can happen when the program is
118 * running in Valgrind 2.2. Read from /proc/self/maps as fallback. */
119
120 buf_size = PATH_MAX + 128;
121 line = (char *) realloc (path, buf_size);
122 if (line == NULL) {
123 /* Cannot allocate memory. */
124 free (path);
125 if (error)
126 *error = BR_INIT_ERROR_NOMEM;
127 return NULL;
128 }
129
130 f = fopen ("/proc/self/maps", "r");
131 if (f == NULL) {
132 free (line);
133 if (error)
134 *error = BR_INIT_ERROR_OPEN_MAPS;
135 return NULL;
136 }
137
138 /* The first entry should be the executable name. */
139 result = fgets (line, (int) buf_size, f);
140 if (result == NULL) {
141 fclose (f);
142 free (line);
143 if (error)
144 *error = BR_INIT_ERROR_READ_MAPS;
145 return NULL;
146 }
147
148 /* Get rid of newline character. */
149 buf_size = strlen (line);
150 if (buf_size <= 0) {
151 /* Huh? An empty string? */
152 fclose (f);
153 free (line);
154 if (error)
155 *error = BR_INIT_ERROR_INVALID_MAPS;
156 return NULL;
157 }
158 if (line[buf_size - 1] == 10)
159 line[buf_size - 1] = 0;
160
161 /* Extract the filename; it is always an absolute path. */
162 path = strchr (line, '/');
163
164 /* Sanity check. */
165 if (strstr (line, " r-xp ") == NULL || path == NULL) {
166 fclose (f);
167 free (line);
168 if (error)
169 *error = BR_INIT_ERROR_INVALID_MAPS;
170 return NULL;
171 }
172
173 path = strdup (path);
174 free (line);
175 fclose (f);
176 return path;
177 #endif /* ENABLE_BINRELOC */
178 }
179
180
181 /** @internal
182 * Find the canonical filename of the executable which owns symbol.
183 * Returns a filename which must be freed, or NULL on error.
184 */
185 static char *
186 _br_find_exe_for_symbol (const void *symbol, BrInitError *error)
187 {
188 #ifndef ENABLE_BINRELOC
189 if (error)
190 *error = BR_INIT_ERROR_DISABLED;
191 return (char *) NULL;
192 #else
193 #define SIZE PATH_MAX + 100
194 FILE *f;
195 size_t address_string_len;
196 char *address_string, line[SIZE], *found;
197
198 if (symbol == NULL)
199 return (char *) NULL;
200
201 f = fopen ("/proc/self/maps", "r");
202 if (f == NULL)
203 return (char *) NULL;
204
205 address_string_len = 4;
206 address_string = (char *) malloc (address_string_len);
207 found = (char *) NULL;
208
209 while (!feof (f)) {
210 char *start_addr, *end_addr, *end_addr_end, *file;
211 void *start_addr_p, *end_addr_p;
212 size_t len;
213
214 if (fgets (line, SIZE, f) == NULL)
215 break;
216
217 /* Sanity check. */
218 if (strstr (line, " r-xp ") == NULL || strchr (line, '/') == NULL)
219 continue;
220
221 /* Parse line. */
222 start_addr = line;
223 end_addr = strchr (line, '-');
224 file = strchr (line, '/');
225
226 /* More sanity check. */
227 if (!(file > end_addr && end_addr != NULL && end_addr[0] == '-'))
228 continue;
229
230 end_addr[0] = '\0';
231 end_addr++;
232 end_addr_end = strchr (end_addr, ' ');
233 if (end_addr_end == NULL)
234 continue;
235
236 end_addr_end[0] = '\0';
237 len = strlen (file);
238 if (len == 0)
239 continue;
240 if (file[len - 1] == '\n')
241 file[len - 1] = '\0';
242
243 /* Get rid of "(deleted)" from the filename. */
244 len = strlen (file);
245 if (len > 10 && strcmp (file + len - 10, " (deleted)") == 0)
246 file[len - 10] = '\0';
247
248 /* I don't know whether this can happen but better safe than sorry. */
249 len = strlen (start_addr);
250 if (len != strlen (end_addr))
251 continue;
252
253
254 /* Transform the addresses into a string in the form of 0xdeadbeef,
255 * then transform that into a pointer. */
256 if (address_string_len < len + 3) {
257 address_string_len = len + 3;
258 address_string = (char *) realloc (address_string, address_string_len);
259 }
260
261 memcpy (address_string, "0x", 2);
262 memcpy (address_string + 2, start_addr, len);
263 address_string[2 + len] = '\0';
264 sscanf (address_string, "%p", &start_addr_p);
265
266 memcpy (address_string, "0x", 2);
267 memcpy (address_string + 2, end_addr, len);
268 address_string[2 + len] = '\0';
269 sscanf (address_string, "%p", &end_addr_p);
270
271
272 if (symbol >= start_addr_p && symbol < end_addr_p) {
273 found = file;
274 break;
275 }
276 }
277
278 free (address_string);
279 fclose (f);
280
281 if (found == NULL)
282 return (char *) NULL;
283 else
284 return strdup (found);
285 #endif /* ENABLE_BINRELOC */
286 }
287
288
289 #ifndef BINRELOC_RUNNING_DOXYGEN
290 #undef NULL
291 #define NULL ((void *) 0) /* typecasted as char* for C++ type safeness */
292 #endif
293
294 static char *exe = (char *) NULL;
295
296
297 /** Initialize the BinReloc library (for applications).
298 *
299 * This function must be called before using any other BinReloc functions.
300 * It attempts to locate the application's canonical filename.
301 *
302 * @note If you want to use BinReloc for a library, then you should call
303 * br_init_lib() instead.
304 *
305 * @param error If BinReloc failed to initialize, then the error code will
306 * be stored in this variable. Set to NULL if you want to
307 * ignore this. See #BrInitError for a list of error codes.
308 *
309 * @returns 1 on success, 0 if BinReloc failed to initialize.
310 */
311 int
312 br_init (BrInitError *error)
313 {
314 exe = _br_find_exe (error);
315 return exe != NULL;
316 }
317
318
319 /** Initialize the BinReloc library (for libraries).
320 *
321 * This function must be called before using any other BinReloc functions.
322 * It attempts to locate the calling library's canonical filename.
323 *
324 * @note The BinReloc source code MUST be included in your library, or this
325 * function won't work correctly.
326 *
327 * @param error If BinReloc failed to initialize, then the error code will
328 * be stored in this variable. Set to NULL if you want to
329 * ignore this. See #BrInitError for a list of error codes.
330 *
331 * @returns 1 on success, 0 if a filename cannot be found.
332 */
333 int
334 br_init_lib (BrInitError *error)
335 {
336 exe = _br_find_exe_for_symbol ((const void *) "", error);
337 return exe != NULL;
338 }
339
340
341 /** Find the canonical filename of the current application.
342 *
343 * @param default_exe A default filename which will be used as fallback.
344 * @returns A string containing the application's canonical filename,
345 * which must be freed when no longer necessary. If BinReloc is
346 * not initialized, or if br_init() failed, then a copy of
347 * default_exe will be returned. If default_exe is NULL, then
348 * NULL will be returned.
349 */
350 char *
351 br_find_exe (const char *default_exe)
352 {
353 if (exe == (char *) NULL) {
354 /* BinReloc is not initialized. */
355 if (default_exe != (const char *) NULL)
356 return strdup (default_exe);
357 else
358 return (char *) NULL;
359 }
360 return strdup (exe);
361 }
362
363
364 /** Locate the directory in which the current application is installed.
365 *
366 * The prefix is generated by the following pseudo-code evaluation:
367 * \code
368 * dirname(exename)
369 * \endcode
370 *
371 * @param default_dir A default directory which will used as fallback.
372 * @return A string containing the directory, which must be freed when no
373 * longer necessary. If BinReloc is not initialized, or if the
374 * initialization function failed, then a copy of default_dir
375 * will be returned. If default_dir is NULL, then NULL will be
376 * returned.
377 */
378 char *
379 br_find_exe_dir (const char *default_dir)
380 {
381 if (exe == NULL) {
382 /* BinReloc not initialized. */
383 if (default_dir != NULL)
384 return strdup (default_dir);
385 else
386 return (char *) NULL;
387 }
388
389 return br_dirname (exe);
390 }
391
392
393 /** Locate the prefix in which the current application is installed.
394 *
395 * The prefix is generated by the following pseudo-code evaluation:
396 * \code
397 * dirname(dirname(exename))
398 * \endcode
399 *
400 * @param default_prefix A default prefix which will used as fallback.
401 * @return A string containing the prefix, which must be freed when no
402 * longer necessary. If BinReloc is not initialized, or if
403 * the initialization function failed, then a copy of default_prefix
404 * will be returned. If default_prefix is NULL, then NULL will be returned.
405 */
406 char *
407 br_find_prefix (const char *default_prefix)
408 {
409 char *dir1, *dir2;
410
411 if (exe == (char *) NULL) {
412 /* BinReloc not initialized. */
413 if (default_prefix != (const char *) NULL)
414 return strdup (default_prefix);
415 else
416 return (char *) NULL;
417 }
418
419 dir1 = br_dirname (exe);
420 dir2 = br_dirname (dir1);
421 free (dir1);
422 return dir2;
423 }
424
425
426 /** Locate the application's binary folder.
427 *
428 * The path is generated by the following pseudo-code evaluation:
429 * \code
430 * prefix + "/bin"
431 * \endcode
432 *
433 * @param default_bin_dir A default path which will used as fallback.
434 * @return A string containing the bin folder's path, which must be freed when
435 * no longer necessary. If BinReloc is not initialized, or if
436 * the initialization function failed, then a copy of default_bin_dir will
437 * be returned. If default_bin_dir is NULL, then NULL will be returned.
438 */
439 char *
440 br_find_bin_dir (const char *default_bin_dir)
441 {
442 char *prefix, *dir;
443
444 prefix = br_find_prefix ((const char *) NULL);
445 if (prefix == (char *) NULL) {
446 /* BinReloc not initialized. */
447 if (default_bin_dir != (const char *) NULL)
448 return strdup (default_bin_dir);
449 else
450 return (char *) NULL;
451 }
452
453 dir = br_build_path (prefix, "bin");
454 free (prefix);
455 return dir;
456 }
457
458
459 /** Locate the application's superuser binary folder.
460 *
461 * The path is generated by the following pseudo-code evaluation:
462 * \code
463 * prefix + "/sbin"
464 * \endcode
465 *
466 * @param default_sbin_dir A default path which will used as fallback.
467 * @return A string containing the sbin folder's path, which must be freed when
468 * no longer necessary. If BinReloc is not initialized, or if the
469 * initialization function failed, then a copy of default_sbin_dir will
470 * be returned. If default_bin_dir is NULL, then NULL will be returned.
471 */
472 char *
473 br_find_sbin_dir (const char *default_sbin_dir)
474 {
475 char *prefix, *dir;
476
477 prefix = br_find_prefix ((const char *) NULL);
478 if (prefix == (char *) NULL) {
479 /* BinReloc not initialized. */
480 if (default_sbin_dir != (const char *) NULL)
481 return strdup (default_sbin_dir);
482 else
483 return (char *) NULL;
484 }
485
486 dir = br_build_path (prefix, "sbin");
487 free (prefix);
488 return dir;
489 }
490
491
492 /** Locate the application's data folder.
493 *
494 * The path is generated by the following pseudo-code evaluation:
495 * \code
496 * prefix + "/share"
497 * \endcode
498 *
499 * @param default_data_dir A default path which will used as fallback.
500 * @return A string containing the data folder's path, which must be freed when
501 * no longer necessary. If BinReloc is not initialized, or if the
502 * initialization function failed, then a copy of default_data_dir
503 * will be returned. If default_data_dir is NULL, then NULL will be
504 * returned.
505 */
506 char *
507 br_find_data_dir (const char *default_data_dir)
508 {
509 char *prefix, *dir;
510
511 prefix = br_find_prefix ((const char *) NULL);
512 if (prefix == (char *) NULL) {
513 /* BinReloc not initialized. */
514 if (default_data_dir != (const char *) NULL)
515 return strdup (default_data_dir);
516 else
517 return (char *) NULL;
518 }
519
520 dir = br_build_path (prefix, "share");
521 free (prefix);
522 return dir;
523 }
524
525
526 /** Locate the application's localization folder.
527 *
528 * The path is generated by the following pseudo-code evaluation:
529 * \code
530 * prefix + "/share/locale"
531 * \endcode
532 *
533 * @param default_locale_dir A default path which will used as fallback.
534 * @return A string containing the localization folder's path, which must be freed when
535 * no longer necessary. If BinReloc is not initialized, or if the
536 * initialization function failed, then a copy of default_locale_dir will be returned.
537 * If default_locale_dir is NULL, then NULL will be returned.
538 */
539 char *
540 br_find_locale_dir (const char *default_locale_dir)
541 {
542 char *data_dir, *dir;
543
544 data_dir = br_find_data_dir ((const char *) NULL);
545 if (data_dir == (char *) NULL) {
546 /* BinReloc not initialized. */
547 if (default_locale_dir != (const char *) NULL)
548 return strdup (default_locale_dir);
549 else
550 return (char *) NULL;
551 }
552
553 dir = br_build_path (data_dir, "locale");
554 free (data_dir);
555 return dir;
556 }
557
558
559 /** Locate the application's library folder.
560 *
561 * The path is generated by the following pseudo-code evaluation:
562 * \code
563 * prefix + "/lib"
564 * \endcode
565 *
566 * @param default_lib_dir A default path which will used as fallback.
567 * @return A string containing the library folder's path, which must be freed when
568 * no longer necessary. If BinReloc is not initialized, or if the initialization
569 * function failed, then a copy of default_lib_dir will be returned.
570 * If default_lib_dir is NULL, then NULL will be returned.
571 */
572 char *
573 br_find_lib_dir (const char *default_lib_dir)
574 {
575 char *prefix, *dir;
576
577 prefix = br_find_prefix ((const char *) NULL);
578 if (prefix == (char *) NULL) {
579 /* BinReloc not initialized. */
580 if (default_lib_dir != (const char *) NULL)
581 return strdup (default_lib_dir);
582 else
583 return (char *) NULL;
584 }
585
586 dir = br_build_path (prefix, "lib");
587 free (prefix);
588 return dir;
589 }
590
591
592 /** Locate the application's libexec folder.
593 *
594 * The path is generated by the following pseudo-code evaluation:
595 * \code
596 * prefix + "/libexec"
597 * \endcode
598 *
599 * @param default_libexec_dir A default path which will used as fallback.
600 * @return A string containing the libexec folder's path, which must be freed when
601 * no longer necessary. If BinReloc is not initialized, or if the initialization
602 * function failed, then a copy of default_libexec_dir will be returned.
603 * If default_libexec_dir is NULL, then NULL will be returned.
604 */
605 char *
606 br_find_libexec_dir (const char *default_libexec_dir)
607 {
608 char *prefix, *dir;
609
610 prefix = br_find_prefix ((const char *) NULL);
611 if (prefix == (char *) NULL) {
612 /* BinReloc not initialized. */
613 if (default_libexec_dir != (const char *) NULL)
614 return strdup (default_libexec_dir);
615 else
616 return (char *) NULL;
617 }
618
619 dir = br_build_path (prefix, "libexec");
620 free (prefix);
621 return dir;
622 }
623
624
625 /** Locate the application's configuration files folder.
626 *
627 * The path is generated by the following pseudo-code evaluation:
628 * \code
629 * prefix + "/etc"
630 * \endcode
631 *
632 * @param default_etc_dir A default path which will used as fallback.
633 * @return A string containing the etc folder's path, which must be freed when
634 * no longer necessary. If BinReloc is not initialized, or if the initialization
635 * function failed, then a copy of default_etc_dir will be returned.
636 * If default_etc_dir is NULL, then NULL will be returned.
637 */
638 char *
639 br_find_etc_dir (const char *default_etc_dir)
640 {
641 char *prefix, *dir;
642
643 prefix = br_find_prefix ((const char *) NULL);
644 if (prefix == (char *) NULL) {
645 /* BinReloc not initialized. */
646 if (default_etc_dir != (const char *) NULL)
647 return strdup (default_etc_dir);
648 else
649 return (char *) NULL;
650 }
651
652 dir = br_build_path (prefix, "etc");
653 free (prefix);
654 return dir;
655 }
656
657
658 /***********************
659 * Utility functions
660 ***********************/
661
662 /** Concatenate str1 and str2 to a newly allocated string.
663 *
664 * @param str1 A string.
665 * @param str2 Another string.
666 * @returns A newly-allocated string. This string should be freed when no longer needed.
667 */
668 char *
669 br_strcat (const char *str1, const char *str2)
670 {
671 char *result;
672 size_t len1, len2;
673
674 if (str1 == NULL)
675 str1 = "";
676 if (str2 == NULL)
677 str2 = "";
678
679 len1 = strlen (str1);
680 len2 = strlen (str2);
681
682 result = (char *) malloc (len1 + len2 + 1);
683 memcpy (result, str1, len1);
684 memcpy (result + len1, str2, len2);
685 result[len1 + len2] = '\0';
686
687 return result;
688 }
689
690
691 char *
692 br_build_path (const char *dir, const char *file)
693 {
694 char *dir2, *result;
695 size_t len;
696 int must_free = 0;
697
698 len = strlen (dir);
699 if (len > 0 && dir[len - 1] != '/') {
700 dir2 = br_strcat (dir, "/");
701 must_free = 1;
702 } else
703 dir2 = (char *) dir;
704
705 result = br_strcat (dir2, file);
706 if (must_free)
707 free (dir2);
708 return result;
709 }
710
711
712 /* Emulates glibc's strndup() */
713 static char *
714 br_strndup (const char *str, size_t size)
715 {
716 char *result = (char *) NULL;
717 size_t len;
718
719 if (str == (const char *) NULL)
720 return (char *) NULL;
721
722 len = strlen (str);
723 if (len == 0)
724 return strdup ("");
725 if (size > len)
726 size = len;
727
728 result = (char *) malloc (len + 1);
729 memcpy (result, str, size);
730 result[size] = '\0';
731 return result;
732 }
733
734
735 /** Extracts the directory component of a path.
736 *
737 * Similar to g_dirname() or the dirname commandline application.
738 *
739 * Example:
740 * \code
741 * br_dirname ("/usr/local/foobar"); --> Returns: "/usr/local"
742 * \endcode
743 *
744 * @param path A path.
745 * @returns A directory name. This string should be freed when no longer needed.
746 */
747 char *
748 br_dirname (const char *path)
749 {
750 char *end, *result;
751
752 if (path == (const char *) NULL)
753 return (char *) NULL;
754
755 end = strrchr (path, '/');
756 if (end == (const char *) NULL)
757 return strdup (".");
758
759 while (end > path && *end == '/')
760 end--;
761 result = br_strndup (path, end - path + 1);
762 if (result[0] == 0) {
763 free (result);
764 return strdup ("/");
765 } else
766 return result;
767 }
768
769
770 #ifdef __cplusplus
771 }
772 #endif /* __cplusplus */
773
774 #endif /* __BINRELOC_C__ */