1 /* -*- mode: C; c-basic-offset: 3; -*- */
2 
3 /*--------------------------------------------------------------------*/
4 /*--- Launching valgrind                              m_launcher.c ---*/
5 /*--------------------------------------------------------------------*/
6 
7 /*
8    This file is part of Valgrind, a dynamic binary instrumentation
9    framework.
10 
11    Copyright (C) 2000-2017 Julian Seward
12       jseward@acm.org
13 
14    This program is free software; you can redistribute it and/or
15    modify it under the terms of the GNU General Public License as
16    published by the Free Software Foundation; either version 2 of the
17    License, or (at your option) any later version.
18 
19    This program is distributed in the hope that it will be useful, but
20    WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22    General Public License for more details.
23 
24    You should have received a copy of the GNU General Public License
25    along with this program; if not, write to the Free Software
26    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
27    02111-1307, USA.
28 
29    The GNU General Public License is contained in the file COPYING.
30 */
31 
32 /* Note: this is a "normal" program and not part of Valgrind proper,
33    and so it doesn't have to conform to Valgrind's arcane rules on
34    no-glibc-usage etc. */
35 
36 /* Include valgrind headers before system headers to avoid problems
37    with the system headers #defining things which are used as names
38    of structure members in vki headers. */
39 
40 #include "pub_core_debuglog.h"
41 #include "pub_core_vki.h"       // Avoids warnings from
42                                 // pub_core_libcfile.h
43 #include "pub_core_libcproc.h"  // For VALGRIND_LIB, VALGRIND_LAUNCHER
44 #include "pub_core_ume.h"
45 
46 #include <assert.h>
47 #include <ctype.h>
48 #include <elf.h>
49 #include <errno.h>
50 #include <fcntl.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <unistd.h>
55 
56 #ifndef EM_X86_64
57 #define EM_X86_64 62    // elf.h doesn't define this on some older systems
58 #endif
59 
60 #ifndef EM_AARCH64
61 #define EM_AARCH64 183  // ditto
62 #endif
63 
64 #ifndef EM_PPC64
65 #define EM_PPC64 21  // ditto
66 #endif
67 
68 #ifndef E_MIPS_ABI_O32
69 #define E_MIPS_ABI_O32 0x00001000
70 #endif
71 
72 #ifndef E_MIPS_ABI2
73 #define E_MIPS_ABI2    0x00000020
74 #endif
75 
76 /* Report fatal errors */
77 __attribute__((noreturn))
barf(const char * format,...)78 static void barf ( const char *format, ... )
79 {
80    va_list vargs;
81 
82    va_start(vargs, format);
83    fprintf(stderr, "valgrind: Cannot continue: ");
84    vfprintf(stderr, format, vargs);
85    fprintf(stderr, "\n");
86    va_end(vargs);
87 
88    exit(1);
89    /*NOTREACHED*/
90    assert(0);
91 }
92 
93 /* Search the path for the client program */
find_client(const char * clientname)94 static const char *find_client(const char *clientname)
95 {
96    char *fullname;
97    const char *path = getenv("PATH");
98    const char *colon;
99 
100    assert(clientname != NULL);
101 
102    if (path == NULL) return clientname;
103 
104    /* Make the size of the FULLNAME buffer large enough. */
105    unsigned need = strlen(path) + strlen("/") + strlen(clientname) + 1;
106 
107    fullname = malloc(need);
108    if (fullname == NULL)
109       barf("malloc of fullname failed.");
110 
111    while (path)
112    {
113       if ((colon = strchr(path, ':')) == NULL)
114       {
115          strcpy(fullname, path);
116          path = NULL;
117       }
118       else
119       {
120          strncpy(fullname, path, colon - path);
121          fullname[colon - path] = '\0';
122          path = colon + 1;
123       }
124 
125       strcat(fullname, "/");
126       strcat(fullname, clientname);
127 
128       if (access(fullname, R_OK|X_OK) == 0)
129          return fullname;
130    }
131    free(fullname);
132 
133    return clientname;
134 }
135 
136 /* Examine the client and work out which platform it is for */
select_platform(const char * clientname)137 static const char *select_platform(const char *clientname)
138 {
139    int fd;
140    union {
141       char c[4096];
142       Elf32_Ehdr ehdr32;
143       Elf64_Ehdr ehdr64;
144    } header;
145    ssize_t n_bytes;
146    const char *platform = NULL;
147 
148    VG_(debugLog)(2, "launcher", "selecting platform for '%s'\n", clientname);
149 
150    if (strchr(clientname, '/') == NULL)
151       clientname = find_client(clientname);
152 
153    VG_(debugLog)(2, "launcher", "selecting platform for '%s'\n", clientname);
154 
155    if ((fd = open(clientname, O_RDONLY)) < 0)
156       return NULL;
157    //   barf("open(%s): %s", clientname, strerror(errno));
158 
159    VG_(debugLog)(2, "launcher", "opened '%s'\n", clientname);
160 
161    n_bytes = read(fd, header.c, sizeof(header));
162    close(fd);
163    if (n_bytes < 2) {
164       return NULL;
165    }
166 
167    VG_(debugLog)(2, "launcher", "read %ld bytes from '%s'\n",
168                     (long int)n_bytes, clientname);
169 
170    if (header.c[0] == '#' && header.c[1] == '!') {
171       int i = 2;
172 
173       STATIC_ASSERT(VKI_BINPRM_BUF_SIZE < sizeof header);
174       if (n_bytes > VKI_BINPRM_BUF_SIZE)
175          n_bytes = VKI_BINPRM_BUF_SIZE - 1;
176       header.c[n_bytes] = '\0';
177       char *eol = strchr(header.c, '\n');
178       if (eol != NULL)
179          *eol = '\0';
180 
181       // Skip whitespace.
182       while (header.c[i] == ' '|| header.c[i] == '\t')
183          i++;
184 
185       // Get the interpreter name.
186       const char *interp = header.c + i;
187 
188       if (header.c[i] == '\0') {
189          // No interpreter was found; fall back to default shell
190 #  if defined(VGPV_arm_linux_android) \
191       || defined(VGPV_x86_linux_android) \
192       || defined(VGPV_mips32_linux_android) \
193       || defined(VGPV_arm64_linux_android)
194          interp = "/system/bin/sh";
195 #  else
196          interp = "/bin/sh";
197 #  endif
198       } else {
199          while (header.c[i]) {
200             if (header.c[i] == ' ' || header.c[i] == '\t') break;
201             i++;
202          }
203          header.c[i] = '\0';
204       }
205 
206       platform = select_platform(interp);
207 
208    } else if (n_bytes >= SELFMAG && memcmp(header.c, ELFMAG, SELFMAG) == 0) {
209 
210       if (n_bytes >= sizeof(Elf32_Ehdr) && header.c[EI_CLASS] == ELFCLASS32) {
211 
212          if (header.c[EI_DATA] == ELFDATA2LSB) {
213 #           if defined(VGO_solaris)
214             if (header.ehdr32.e_machine == EM_386 &&
215                 (header.ehdr32.e_ident[EI_OSABI] == ELFOSABI_SYSV ||
216                  header.ehdr32.e_ident[EI_OSABI] == ELFOSABI_SOLARIS)) {
217                platform = "x86-solaris";
218             }
219             else
220 #           endif
221             if (header.ehdr32.e_machine == EM_386 &&
222                 (header.ehdr32.e_ident[EI_OSABI] == ELFOSABI_SYSV ||
223                  header.ehdr32.e_ident[EI_OSABI] == ELFOSABI_LINUX)) {
224                platform = "x86-linux";
225             }
226             else
227             if (header.ehdr32.e_machine == EM_ARM &&
228                 (header.ehdr32.e_ident[EI_OSABI] == ELFOSABI_SYSV ||
229                  header.ehdr32.e_ident[EI_OSABI] == ELFOSABI_LINUX)) {
230                platform = "arm-linux";
231             }
232             else
233             if (header.ehdr32.e_machine == EM_MIPS &&
234                 (header.ehdr32.e_ident[EI_OSABI] == ELFOSABI_SYSV ||
235                  header.ehdr32.e_ident[EI_OSABI] == ELFOSABI_LINUX) &&
236                  (header.ehdr32.e_flags & E_MIPS_ABI_O32)) {
237                platform = "mips32-linux";
238             }
239             else
240             if (header.ehdr32.e_machine == EM_MIPS &&
241                 (header.ehdr32.e_ident[EI_OSABI] == ELFOSABI_SYSV ||
242                  header.ehdr32.e_ident[EI_OSABI] == ELFOSABI_LINUX) &&
243                  (header.ehdr32.e_flags & E_MIPS_ABI2)) {
244                platform = "mips64-linux";
245             }
246          }
247          else if (header.c[EI_DATA] == ELFDATA2MSB) {
248             if (header.ehdr32.e_machine == EM_PPC &&
249                 (header.ehdr32.e_ident[EI_OSABI] == ELFOSABI_SYSV ||
250                  header.ehdr32.e_ident[EI_OSABI] == ELFOSABI_LINUX)) {
251                platform = "ppc32-linux";
252             }
253             else
254             if (header.ehdr32.e_machine == EM_MIPS &&
255                 (header.ehdr32.e_ident[EI_OSABI] == ELFOSABI_SYSV ||
256                  header.ehdr32.e_ident[EI_OSABI] == ELFOSABI_LINUX) &&
257                  (header.ehdr32.e_flags & E_MIPS_ABI_O32)) {
258                platform = "mips32-linux";
259             }
260             else
261             if (header.ehdr32.e_machine == EM_MIPS &&
262                 (header.ehdr32.e_ident[EI_OSABI] == ELFOSABI_SYSV ||
263                  header.ehdr32.e_ident[EI_OSABI] == ELFOSABI_LINUX) &&
264                  (header.ehdr32.e_flags & E_MIPS_ABI2)) {
265                platform = "mips64-linux";
266             }
267          }
268 
269       } else if (n_bytes >= sizeof(Elf64_Ehdr) && header.c[EI_CLASS] == ELFCLASS64) {
270 
271          if (header.c[EI_DATA] == ELFDATA2LSB) {
272 #           if defined(VGO_solaris)
273             if (header.ehdr64.e_machine == EM_X86_64 &&
274                 (header.ehdr64.e_ident[EI_OSABI] == ELFOSABI_SYSV ||
275                  header.ehdr64.e_ident[EI_OSABI] == ELFOSABI_SOLARIS)) {
276                platform = "amd64-solaris";
277             }
278             else
279 #           endif
280             if (header.ehdr64.e_machine == EM_X86_64 &&
281                 (header.ehdr64.e_ident[EI_OSABI] == ELFOSABI_SYSV ||
282                  header.ehdr64.e_ident[EI_OSABI] == ELFOSABI_LINUX)) {
283                platform = "amd64-linux";
284             } else if (header.ehdr64.e_machine == EM_MIPS &&
285                 (header.ehdr64.e_ident[EI_OSABI] == ELFOSABI_SYSV ||
286                  header.ehdr64.e_ident[EI_OSABI] == ELFOSABI_LINUX)) {
287                platform = "mips64-linux";
288             } else if (header.ehdr64.e_machine == EM_AARCH64 &&
289                 (header.ehdr64.e_ident[EI_OSABI] == ELFOSABI_SYSV ||
290                  header.ehdr64.e_ident[EI_OSABI] == ELFOSABI_LINUX)) {
291                platform = "arm64-linux";
292             } else if (header.ehdr64.e_machine == EM_PPC64 &&
293                 (header.ehdr64.e_ident[EI_OSABI] == ELFOSABI_SYSV ||
294                  header.ehdr64.e_ident[EI_OSABI] == ELFOSABI_LINUX)) {
295                platform = "ppc64le-linux";
296             }
297          } else if (header.c[EI_DATA] == ELFDATA2MSB) {
298 #           if !defined(VGPV_arm_linux_android) \
299                && !defined(VGPV_x86_linux_android) \
300                && !defined(VGPV_mips32_linux_android) \
301                && !defined(VGPV_arm64_linux_android)
302             if (header.ehdr64.e_machine == EM_PPC64 &&
303                 (header.ehdr64.e_ident[EI_OSABI] == ELFOSABI_SYSV ||
304                  header.ehdr64.e_ident[EI_OSABI] == ELFOSABI_LINUX)) {
305                platform = "ppc64be-linux";
306             }
307             else
308             if (header.ehdr64.e_machine == EM_S390 &&
309                 (header.ehdr64.e_ident[EI_OSABI] == ELFOSABI_SYSV ||
310                  header.ehdr64.e_ident[EI_OSABI] == ELFOSABI_LINUX)) {
311                platform = "s390x-linux";
312             } else if (header.ehdr64.e_machine == EM_MIPS &&
313                 (header.ehdr64.e_ident[EI_OSABI] == ELFOSABI_SYSV ||
314                  header.ehdr64.e_ident[EI_OSABI] == ELFOSABI_LINUX)) {
315                platform = "mips64-linux";
316             }
317 #           endif
318          }
319       }
320    }
321 
322    VG_(debugLog)(2, "launcher", "selected platform '%s'\n",
323                  platform ? platform : "unknown");
324 
325    return platform;
326 }
327 
328 /* Where we expect to find all our aux files */
329 static const char *valgrind_lib = VG_LIBDIR;
330 
main(int argc,char ** argv,char ** envp)331 int main(int argc, char** argv, char** envp)
332 {
333    int i, j, loglevel, r;
334    const char *toolname = NULL;
335    const char *clientname = NULL;
336    const char *platform;
337    const char *default_platform;
338    const char *cp;
339    const char *linkname;
340    char *toolfile;
341    const char *launcher_name;
342    char* new_line;
343    char** new_env;
344 
345    /* Start the debugging-log system ASAP.  First find out how many
346       "-d"s were specified.  This is a pre-scan of the command line.
347       At the same time, look for the tool name. */
348    loglevel = 0;
349    for (i = 1; i < argc; i++) {
350       if (argv[i][0] != '-') {
351          clientname = argv[i];
352          break;
353       }
354       if (0 == strcmp(argv[i], "--")) {
355          if (i+1 < argc)
356             clientname = argv[i+1];
357          break;
358       }
359       if (0 == strcmp(argv[i], "-d"))
360          loglevel++;
361       if (0 == strncmp(argv[i], "--tool=", 7))
362          toolname = argv[i] + 7;
363    }
364 
365    /* ... and start the debug logger.  Now we can safely emit logging
366       messages all through startup. */
367    VG_(debugLog_startup)(loglevel, "Stage 1");
368 
369    /* Make sure we know which tool we're using */
370    if (toolname) {
371       VG_(debugLog)(1, "launcher", "tool '%s' requested\n", toolname);
372    } else {
373       VG_(debugLog)(1, "launcher",
374                        "no tool requested, defaulting to 'memcheck'\n");
375       toolname = "memcheck";
376    }
377 
378    /* Select a platform to use if we can't decide that by looking at
379       the executable (eg because it's a shell script).  VG_PLATFORM is the
380       default_platform. Its value is defined in coregrind/Makefile.am and
381       typically it is the primary build target. Unless the primary build
382       target is not built is not built in which case VG_PLATFORM is the
383       secondary build target. */
384 #  if defined(VGO_linux)
385    if ((0==strcmp(VG_PLATFORM,"x86-linux"))    ||
386        (0==strcmp(VG_PLATFORM,"amd64-linux"))  ||
387        (0==strcmp(VG_PLATFORM,"ppc32-linux"))  ||
388        (0==strcmp(VG_PLATFORM,"ppc64be-linux"))  ||
389        (0==strcmp(VG_PLATFORM,"ppc64le-linux"))  ||
390        (0==strcmp(VG_PLATFORM,"arm-linux"))    ||
391        (0==strcmp(VG_PLATFORM,"arm64-linux"))  ||
392        (0==strcmp(VG_PLATFORM,"s390x-linux"))  ||
393        (0==strcmp(VG_PLATFORM,"mips32-linux")) ||
394        (0==strcmp(VG_PLATFORM,"mips64-linux")))
395       default_platform = VG_PLATFORM;
396 #  elif defined(VGO_solaris)
397    if ((0==strcmp(VG_PLATFORM,"x86-solaris")) ||
398        (0==strcmp(VG_PLATFORM,"amd64-solaris")))
399       default_platform = SOLARIS_LAUNCHER_DEFAULT_PLATFORM;
400 #  else
401 #    error Unknown OS
402 #  endif
403    else
404       barf("Unknown VG_PLATFORM '%s'", VG_PLATFORM);
405 
406    /* Work out what platform to use, or use the default platform if
407       not possible. */
408    if (clientname == NULL) {
409       VG_(debugLog)(1, "launcher",
410                        "no client specified, defaulting platform to '%s'\n",
411                         default_platform);
412       platform = default_platform;
413    } else if ((platform = select_platform(clientname)) != NULL) {
414       VG_(debugLog)(1, "launcher", "selected platform '%s'\n", platform);
415    } else {
416       VG_(debugLog)(1, "launcher",
417                        "no platform detected, defaulting platform to '%s'\n",
418                        default_platform);
419       platform = default_platform;
420    }
421 
422    /* Figure out the name of this executable (viz, the launcher), so
423       we can tell stage2.  stage2 will use the name for recursive
424       invocations of valgrind on child processes. */
425 #  if defined(VGO_linux)
426    linkname = "/proc/self/exe";
427 #  elif defined(VGO_solaris)
428    linkname = "/proc/self/path/a.out";
429 #  else
430 #    error Unknown OS
431 #  endif
432    unsigned bufsiz = 0;
433    char *buf = NULL;
434 
435    while (42) {
436       bufsiz += 500;
437       buf = realloc(buf, bufsiz);
438       if (buf == NULL)
439          barf("realloc of buf failed.");
440       r = readlink(linkname, buf, bufsiz);
441       if (r == -1) {
442         /* If /proc/self/exe (/proc/self/path/a.out) can't be followed, don't
443            give up. Instead continue with an empty string for VALGRIND_LAUNCHER.
444            In the sys_execve wrapper, this is tested, and if found to be empty,
445            fail the execve. */
446         fprintf(stderr, "valgrind: warning (non-fatal): "
447                 "readlink(\"%s\") failed.\n", linkname);
448         fprintf(stderr, "valgrind: continuing, however --trace-children=yes "
449                 "will not work.\n");
450         launcher_name = "";
451         break;
452       }
453       if (r == bufsiz) continue;   // buffer to small; retry
454 
455       assert(r < bufsiz);   // paranoia
456 
457       buf[r] = '\0';
458       launcher_name = buf;
459       break;
460    }
461 
462    /* tediously augment the env: VALGRIND_LAUNCHER=launcher_name */
463    new_line = malloc(strlen(VALGRIND_LAUNCHER) + 1
464                      + strlen(launcher_name) + 1);
465    if (new_line == NULL)
466       barf("malloc of new_line failed.");
467    strcpy(new_line, VALGRIND_LAUNCHER);
468    strcat(new_line, "=");
469    strcat(new_line, launcher_name);
470 
471    for (j = 0; envp[j]; j++)
472       ;
473    new_env = malloc((j+2) * sizeof(char*));
474    if (new_env == NULL)
475       barf("malloc of new_env failed.");
476    for (i = 0; i < j; i++)
477       new_env[i] = envp[i];
478    new_env[i++] = new_line;
479    new_env[i++] = NULL;
480    assert(i == j+2);
481 
482    /* Establish the correct VALGRIND_LIB. */
483    cp = getenv(VALGRIND_LIB);
484 
485    if (cp != NULL)
486       valgrind_lib = cp;
487 
488    /* Build the stage2 invocation, and execve it.  Bye! */
489    toolfile = malloc(strlen(valgrind_lib) + strlen(toolname) + strlen(platform) + 3);
490    if (toolfile == NULL)
491       barf("malloc of toolfile failed.");
492    sprintf(toolfile, "%s/%s-%s", valgrind_lib, toolname, platform);
493 
494    VG_(debugLog)(1, "launcher", "launching %s\n", toolfile);
495 
496    execve(toolfile, argv, new_env);
497 
498    fprintf(stderr, "valgrind: failed to start tool '%s' for platform '%s': %s\n",
499                    toolname, platform, strerror(errno));
500 
501    exit(1);
502 }
503