• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 
2 /*--------------------------------------------------------------------*/
3 /*--- Client-space code for the core.               vg_preloaded.c ---*/
4 /*--------------------------------------------------------------------*/
5 
6 /*
7    This file is part of Valgrind, a dynamic binary instrumentation
8    framework.
9 
10    Copyright (C) 2000-2015 Julian Seward
11       jseward@acm.org
12 
13    This program is free software; you can redistribute it and/or
14    modify it under the terms of the GNU General Public License as
15    published by the Free Software Foundation; either version 2 of the
16    License, or (at your option) any later version.
17 
18    This program is distributed in the hope that it will be useful, but
19    WITHOUT ANY WARRANTY; without even the implied warranty of
20    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21    General Public License for more details.
22 
23    You should have received a copy of the GNU General Public License
24    along with this program; if not, write to the Free Software
25    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
26    02111-1307, USA.
27 
28    The GNU General Public License is contained in the file COPYING.
29 */
30 
31 
32 /* ---------------------------------------------------------------------
33    ALL THE CODE IN THIS FILE RUNS ON THE SIMULATED CPU.
34 
35    These functions are not called directly - they're the targets of code
36    redirection or load notifications (see pub_core_redir.h for info).
37    They're named weirdly so that the intercept code can find them when the
38    shared object is initially loaded.
39 
40    Note that this filename has the "vg_" prefix because it can appear
41    in stack traces, and the "vg_" makes it a little clearer that it
42    originates from Valgrind.
43    ------------------------------------------------------------------ */
44 
45 #include "pub_core_basics.h"
46 #include "pub_core_clreq.h"
47 #include "pub_core_debuginfo.h"  // Needed for pub_core_redir.h
48 #include "pub_core_redir.h"      // For VG_NOTIFY_ON_LOAD
49 
50 #if defined(VGO_linux)
51 
52 /* ---------------------------------------------------------------------
53    Hook for running __libc_freeres once the program exits.
54    ------------------------------------------------------------------ */
55 
56 void VG_NOTIFY_ON_LOAD(freeres)( void );
VG_NOTIFY_ON_LOAD(freeres)57 void VG_NOTIFY_ON_LOAD(freeres)( void )
58 {
59 #  if !defined(__UCLIBC__) \
60       && !defined(__ANDROID__)
61    extern void __libc_freeres(void);
62    __libc_freeres();
63 #  endif
64    VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__LIBC_FREERES_DONE,
65                                    0, 0, 0, 0, 0);
66    /*NOTREACHED*/
67    *(volatile int *)0 = 'x';
68 }
69 
70 /* ---------------------------------------------------------------------
71    Wrapper for indirect functions which need to be redirected.
72    ------------------------------------------------------------------ */
73 
74 void * VG_NOTIFY_ON_LOAD(ifunc_wrapper) (void);
VG_NOTIFY_ON_LOAD(ifunc_wrapper)75 void * VG_NOTIFY_ON_LOAD(ifunc_wrapper) (void)
76 {
77     OrigFn fn;
78     Addr result = 0;
79     Addr fnentry;
80 
81     /* Call the original indirect function and get it's result */
82     VALGRIND_GET_ORIG_FN(fn);
83     CALL_FN_W_v(result, fn);
84 
85 #if defined(VGP_ppc64be_linux)
86    /* ppc64be uses function descriptors, so get the actual function entry
87       address for the client request, but return the function descriptor
88       from this function.
89       result points to the function descriptor, which starts with the
90       function entry. */
91     fnentry = *(Addr*)result;
92 #else
93     fnentry = result;
94 #endif
95 
96     /* Ask the valgrind core running on the real CPU (as opposed to this
97        code which runs on the emulated CPU) to update the redirection that
98        led to this function. This client request eventually gives control to
99        the function VG_(redir_add_ifunc_target) in m_redir.c  */
100     VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__ADD_IFUNC_TARGET,
101                                     fn.nraddr, fnentry, 0, 0, 0);
102     return (void*)result;
103 }
104 
105 #elif defined(VGO_darwin)
106 
107 #include "config.h" /* VERSION */
108 
109 /* ---------------------------------------------------------------------
110    Darwin crash log hints
111    ------------------------------------------------------------------ */
112 
113 /* This string will be inserted into crash logs, so crashes while
114    running under Valgrind can be distinguished from other crashes. */
115 __private_extern__ const char *__crashreporter_info__ = "Instrumented by Valgrind " VERSION;
116 
117 /* ---------------------------------------------------------------------
118    Darwin environment cleanup
119    ------------------------------------------------------------------ */
120 
121 /* Scrubbing DYLD_INSERT_LIBRARIES from envp during exec is insufficient,
122    as there are other ways to launch a process with environment that
123    valgrind can't catch easily (i.e. launchd).
124    Instead, scrub DYLD_INSERT_LIBRARIES from the parent process once
125    dyld is done loading vg_preload.so.
126 */
127 #include <string.h>
128 #include <crt_externs.h>
129 
130 // GrP fixme copied from m_libcproc
env_unsetenv(HChar ** env,const HChar * varname)131 static void env_unsetenv ( HChar **env, const HChar *varname )
132 {
133    HChar **from;
134    HChar **to = NULL;
135    Int len = strlen(varname);
136 
137    for (from = to = env; from && *from; from++) {
138       if (!(strncmp(varname, *from, len) == 0 && (*from)[len] == '=')) {
139 	 *to = *from;
140 	 to++;
141       }
142    }
143    *(to++) = *(from++);
144    /* fix the 4th "char* apple" pointer (aka. executable path pointer) */
145    *(to++) = *(from++);
146    *to = NULL;
147 }
148 
149 static void vg_cleanup_env(void)  __attribute__((constructor));
vg_cleanup_env(void)150 static void vg_cleanup_env(void)
151 {
152     HChar **envp = (HChar**)*_NSGetEnviron();
153     env_unsetenv(envp, "VALGRIND_LAUNCHER");
154     env_unsetenv(envp, "DYLD_SHARED_REGION");
155     // GrP fixme should be more like mash_colon_env()
156     env_unsetenv(envp, "DYLD_INSERT_LIBRARIES");
157 }
158 
159 /* ---------------------------------------------------------------------
160    Darwin arc4random (rdar://6166275)
161    ------------------------------------------------------------------ */
162 
163 #include <fcntl.h>
164 #include <unistd.h>
165 
166 int VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib, arc4random)(void);
VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib,arc4random)167 int VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib, arc4random)(void)
168 {
169     static int rnd = -1;
170     int result;
171 
172     if (rnd < 0) rnd = open("/dev/random", O_RDONLY);
173 
174     read(rnd, &result, sizeof(result));
175     return result;
176 }
177 
178 void VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib, arc4random_stir)(void);
VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib,arc4random_stir)179 void VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib, arc4random_stir)(void)
180 {
181     // do nothing
182 }
183 
184 void VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib, arc4random_addrandom)(unsigned char *dat, int datlen);
VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib,arc4random_addrandom)185 void VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib, arc4random_addrandom)(unsigned char *dat, int datlen)
186 {
187     // do nothing
188     // GrP fixme ought to check [dat..dat+datlen) is defined
189     // but don't care if it's initialized
190 }
191 
192 #elif defined(VGO_solaris)
193 
194 /* Declare the errno and environ symbols weakly in case the client is not
195    linked against libc. In such a case it also cannot run replacement
196    functions for set_error() and spawnveg() where these two variables are
197    needed so this is ok. */
198 __attribute__((weak)) extern int errno;
199 __attribute__((weak)) extern char **environ;
200 
201 #include <assert.h>
202 #include <errno.h>
203 #include <spawn.h>
204 #include <sys/syscall.h>
205 #include <sys/signal.h>
206 #include <unistd.h>
207 
208 /* Replace function block_all_signals() from libc. When the client program is
209    not running under valgrind, the function blocks all signals by setting
210    sc_sigblock flag in the schedctl control block. When run under Valgrind
211    this would bypass Valgrind's syscall and signal machinery.
212    Valgrind's signal machinery needs to retain control over which signals are
213    blocked and which not (see m_signals.c and m_scheduler/scheduler.c for more
214    information - typically synchronous signals should not be blocked).
215    Therefore this function replacement emulates lwp_sigmask syscall.
216 */
217 void VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME, block_all_signals)(/*ulwp_t*/ void *self);
VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME,block_all_signals)218 void VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME, block_all_signals)(/*ulwp_t*/ void *self)
219 {
220    syscall(SYS_lwp_sigmask, SIG_SETMASK, ~0U, ~0U, ~0U, ~0U);
221 }
222 
223 /* Replace functions get_error() and set_error() in libc. These functions are
224    internal to the library and are used to work with an error value returned
225    by posix_spawn() (when it is implemented using vfork()). A child calls
226    set_error() to set an error code and the parent then calls get_error() to
227    read it. Accessor functions are used so these trivial store+load operations
228    are not changed by the compiler in any way.
229 
230    Since Valgrind translates vfork() to a normal fork(), calling set_error()
231    by the child would have no effect on the error value in the parent so
232    something must be done to fix this problem.
233 
234    A pipe is created between a child and its parent in the forksys pre-wrapper
235    when a vfork() is encountered. The child's end of the pipe is closed when
236    the child exits or execs (because close-on-exec is set on the file
237    descriptor). Valgrind (the parent) waits on the child's end of the pipe to
238    be closed which preserves the vfork() behaviour that the parent process is
239    suspended while the child is using its resources.
240 
241    The pipe is then used to send an eventual error code set by the child in
242    posix_spawn() to the parent. If there is any error Valgrind returns it as
243    an error from the vfork() syscall. This means the syscall can return errors
244    that it would normally never return but this is not a problem in practice
245    because any error is directly propagated as a return code from
246    posix_spawn().
247 
248    Address of vg_vfork_fildes is found by Valgrind when debug information for
249    vgpreload_core.so is being processed. A value of this variable is set in
250    the forksys pre-wrapper before a fork() call is made and set back to -1
251    before returning from the wrapper by the parent.
252 
253    Newer Solaris versions introduce the spawn syscall and posix_spawn() is
254    implemented using it. The redirect is not needed for these versions.
255 */
256 int vg_vfork_fildes = -1;
257 
258 int VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME, get_error)(int *errp);
VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME,get_error)259 int VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME, get_error)(int *errp)
260 {
261    /* Always return 0 when the parent tries to call get_error(). Any error
262       from the child is returned directly as an error from the vfork child.
263       Value pointed by errp is initialized only by the child so not
264       redirecting this function would mean that the parent gets an
265       uninitialized/garbage value when it calls this function. */
266    return 0;
267 }
268 
269 int VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME, set_error)(int *errp, int err);
VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME,set_error)270 int VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME, set_error)(int *errp, int err)
271 {
272    *errp = err;
273 
274    /* Libc should always call set_error() only after doing a vfork() syscall
275       in posix_spawn(). The forksys pre-wrapper saves a descriptor of the
276       child's end of the pipe in vg_vfork_fildes so it is an error if it is
277       not a valid file descriptor at this point. */
278    assert(vg_vfork_fildes >= 0);
279    /* Current protocol between this function and the forksys pre-wrapper
280       allows to send only errors in range [0, 255] (one byte values). */
281    assert(err >= 0 && err <= 0xff);
282 
283    if (err != 0) {
284       unsigned char w = (unsigned char)(err & 0xff);
285       ssize_t res;
286       do {
287          res = write(vg_vfork_fildes, &w, 1);
288          assert(res == 1 || (errno == EINTR || errno == ERESTART));
289       } while (res != 1);
290    }
291 
292    return err;
293 }
294 
295 /* Replace spawnveg() in libast.so.1. This function is used by ksh to spawn
296    new processes. The library has a build time option to select between
297    several variants of this function based on behaviour of vfork() and
298    posix_spawn() on the system for which the library is being compiled.
299    Unfortunately, Solaris and illumos use the real vfork() variant which does
300    not work correctly with the vfork() -> fork() translation done by Valgrind
301    (see the forksys pre-wrapper for details). Therefore the function is
302    replaced here with an implementation that uses posix_spawn(). This
303    replacement can be removed when a configuration of libast in Solaris and
304    illumos is changed to use the posix_spawn() implementation.
305 */
306 pid_t VG_REPLACE_FUNCTION_ZU(libastZdsoZd1, spawnveg)(const char *command,
307                                                       char **argv,
308                                                       char **envv,
309                                                       pid_t pgid);
VG_REPLACE_FUNCTION_ZU(libastZdsoZd1,spawnveg)310 pid_t VG_REPLACE_FUNCTION_ZU(libastZdsoZd1, spawnveg)(const char *command,
311                                                       char **argv,
312                                                       char **envp,
313                                                       pid_t pgid)
314 {
315    int err = 0;
316    pid_t pid;
317    posix_spawnattr_t attr;
318    int attr_init_done = 0;
319 
320    err = posix_spawnattr_init(&attr);
321    if (err != 0)
322       goto out;
323    attr_init_done = 1;
324 
325    err = posix_spawnattr_init(&attr);
326    if (err != 0)
327       goto out;
328 
329    if (pgid != 0) {
330       if (pgid <= 1)
331          pgid = 0;
332       err = posix_spawnattr_setpgroup(&attr, pgid);
333       if (err != 0)
334          goto out;
335       err = posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETPGROUP);
336       if (err != 0)
337          goto out;
338    }
339 
340    err = posix_spawn(&pid, command, NULL, &attr, argv, envp ? envp : environ);
341 
342 out:
343    if (attr_init_done)
344       posix_spawnattr_destroy(&attr);
345    if (err != 0) {
346       errno = err;
347       return -1;
348    }
349    return pid;
350 }
351 
352 #else
353 #  error Unknown OS
354 #endif
355 
356 /*--------------------------------------------------------------------*/
357 /*--- end                                                          ---*/
358 /*--------------------------------------------------------------------*/
359