• 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-2017 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) || defined(VGO_solaris)
51 
52 /* ---------------------------------------------------------------------
53    Hook for running __gnu_cxx::__freeres() and __libc_freeres() once
54    the program exits.
55    ------------------------------------------------------------------ */
56 
57 void VG_NOTIFY_ON_LOAD(freeres)(Vg_FreeresToRun to_run);
VG_NOTIFY_ON_LOAD(freeres)58 void VG_NOTIFY_ON_LOAD(freeres)(Vg_FreeresToRun to_run)
59 {
60 #  if !defined(__UCLIBC__) && !defined(MUSL_LIBC) \
61       && !defined(VGPV_amd64_linux_android) \
62       && !defined(VGPV_arm_linux_android) \
63       && !defined(VGPV_x86_linux_android) \
64       && !defined(VGPV_mips32_linux_android) \
65       && !defined(VGPV_arm64_linux_android) \
66 
67    /* g++ mangled __gnu_cxx::__freeres yields -> _ZN9__gnu_cxx9__freeresEv */
68    extern void _ZN9__gnu_cxx9__freeresEv(void) __attribute__((weak));
69    if (((to_run & VG_RUN__GNU_CXX__FREERES) != 0) &&
70        (_ZN9__gnu_cxx9__freeresEv != NULL)) {
71       _ZN9__gnu_cxx9__freeresEv();
72    }
73 
74 #  if defined(VGO_linux)
75    /* __libc_freeres() not yet available on Solaris. */
76    extern void __libc_freeres(void);
77    if ((to_run & VG_RUN__LIBC_FREERES) != 0) {
78       __libc_freeres();
79    }
80 #  endif
81 #  endif
82 
83    VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__FREERES_DONE, 0, 0, 0, 0, 0);
84    /*NOTREACHED*/
85    *(volatile int *)0 = 'x';
86 }
87 
88 #endif // VGO_linux || VGO_solaris
89 
90 #if defined(VGO_linux)
91 
92 /* ---------------------------------------------------------------------
93    Wrapper for indirect functions which need to be redirected.
94    ------------------------------------------------------------------ */
95 
96 void * VG_NOTIFY_ON_LOAD(ifunc_wrapper) (void);
VG_NOTIFY_ON_LOAD(ifunc_wrapper)97 void * VG_NOTIFY_ON_LOAD(ifunc_wrapper) (void)
98 {
99     OrigFn fn;
100     Addr result = 0;
101     Addr fnentry;
102 
103     /* Call the original indirect function and get it's result */
104     VALGRIND_GET_ORIG_FN(fn);
105     CALL_FN_W_v(result, fn);
106 
107 #if defined(VGP_ppc64be_linux)
108    /* ppc64be uses function descriptors, so get the actual function entry
109       address for the client request, but return the function descriptor
110       from this function.
111       result points to the function descriptor, which starts with the
112       function entry. */
113     fnentry = *(Addr*)result;
114 #else
115     fnentry = result;
116 #endif
117 
118     /* Ask the valgrind core running on the real CPU (as opposed to this
119        code which runs on the emulated CPU) to update the redirection that
120        led to this function. This client request eventually gives control to
121        the function VG_(redir_add_ifunc_target) in m_redir.c  */
122     VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__ADD_IFUNC_TARGET,
123                                     fn.nraddr, fnentry, 0, 0, 0);
124     return (void*)result;
125 }
126 
127 #elif defined(VGO_darwin)
128 
129 #include "config.h" /* VERSION */
130 
131 /* ---------------------------------------------------------------------
132    Darwin crash log hints
133    ------------------------------------------------------------------ */
134 
135 /* This string will be inserted into crash logs, so crashes while
136    running under Valgrind can be distinguished from other crashes. */
137 __private_extern__ const char *__crashreporter_info__ = "Instrumented by Valgrind " VERSION;
138 
139 /* ---------------------------------------------------------------------
140    Darwin environment cleanup
141    ------------------------------------------------------------------ */
142 
143 /* Scrubbing DYLD_INSERT_LIBRARIES from envp during exec is insufficient,
144    as there are other ways to launch a process with environment that
145    valgrind can't catch easily (i.e. launchd).
146    Instead, scrub DYLD_INSERT_LIBRARIES from the parent process once
147    dyld is done loading vg_preload.so.
148 */
149 #include <string.h>
150 #include <crt_externs.h>
151 
152 // GrP fixme copied from m_libcproc
env_unsetenv(HChar ** env,const HChar * varname)153 static void env_unsetenv ( HChar **env, const HChar *varname )
154 {
155    HChar **from;
156    HChar **to = NULL;
157    Int len = strlen(varname);
158 
159    for (from = to = env; from && *from; from++) {
160       if (!(strncmp(varname, *from, len) == 0 && (*from)[len] == '=')) {
161 	 *to = *from;
162 	 to++;
163       }
164    }
165    *(to++) = *(from++);
166    /* fix the 4th "char* apple" pointer (aka. executable path pointer) */
167    *(to++) = *(from++);
168    *to = NULL;
169 }
170 
171 static void vg_cleanup_env(void)  __attribute__((constructor));
vg_cleanup_env(void)172 static void vg_cleanup_env(void)
173 {
174     HChar **envp = (HChar**)*_NSGetEnviron();
175     env_unsetenv(envp, "VALGRIND_LAUNCHER");
176     env_unsetenv(envp, "DYLD_SHARED_REGION");
177     // GrP fixme should be more like mash_colon_env()
178     env_unsetenv(envp, "DYLD_INSERT_LIBRARIES");
179 }
180 
181 /* ---------------------------------------------------------------------
182    Darwin arc4random (rdar://6166275)
183    ------------------------------------------------------------------ */
184 
185 #include <fcntl.h>
186 #include <unistd.h>
187 
188 int VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib, arc4random)(void);
VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib,arc4random)189 int VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib, arc4random)(void)
190 {
191     static int rnd = -1;
192     int result;
193 
194     if (rnd < 0) rnd = open("/dev/random", O_RDONLY);
195 
196     read(rnd, &result, sizeof(result));
197     return result;
198 }
199 
200 void VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib, arc4random_stir)(void);
VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib,arc4random_stir)201 void VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib, arc4random_stir)(void)
202 {
203     // do nothing
204 }
205 
206 void VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib, arc4random_addrandom)(unsigned char *dat, int datlen);
VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib,arc4random_addrandom)207 void VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib, arc4random_addrandom)(unsigned char *dat, int datlen)
208 {
209     // do nothing
210     // GrP fixme ought to check [dat..dat+datlen) is defined
211     // but don't care if it's initialized
212 }
213 
214 #elif defined(VGO_solaris)
215 
216 /* Declare the errno and environ symbols weakly in case the client is not
217    linked against libc. In such a case it also cannot run replacement
218    functions for set_error() and spawnveg() where these two variables are
219    needed so this is ok. */
220 __attribute__((weak)) extern int errno;
221 __attribute__((weak)) extern char **environ;
222 
223 #include <assert.h>
224 #include <errno.h>
225 #include <spawn.h>
226 #include <sys/syscall.h>
227 #include <sys/signal.h>
228 #include <unistd.h>
229 
230 /* Replace function block_all_signals() from libc. When the client program is
231    not running under valgrind, the function blocks all signals by setting
232    sc_sigblock flag in the schedctl control block. When run under Valgrind
233    this would bypass Valgrind's syscall and signal machinery.
234    Valgrind's signal machinery needs to retain control over which signals are
235    blocked and which not (see m_signals.c and m_scheduler/scheduler.c for more
236    information - typically synchronous signals should not be blocked).
237    Therefore this function replacement emulates lwp_sigmask syscall.
238 */
239 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)240 void VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME, block_all_signals)(/*ulwp_t*/ void *self)
241 {
242    syscall(SYS_lwp_sigmask, SIG_SETMASK, ~0U, ~0U, ~0U, ~0U);
243 }
244 
245 /* Replace functions get_error() and set_error() in libc. These functions are
246    internal to the library and are used to work with an error value returned
247    by posix_spawn() (when it is implemented using vfork()). A child calls
248    set_error() to set an error code and the parent then calls get_error() to
249    read it. Accessor functions are used so these trivial store+load operations
250    are not changed by the compiler in any way.
251 
252    Since Valgrind translates vfork() to a normal fork(), calling set_error()
253    by the child would have no effect on the error value in the parent so
254    something must be done to fix this problem.
255 
256    A pipe is created between a child and its parent in the forksys pre-wrapper
257    when a vfork() is encountered. The child's end of the pipe is closed when
258    the child exits or execs (because close-on-exec is set on the file
259    descriptor). Valgrind (the parent) waits on the child's end of the pipe to
260    be closed which preserves the vfork() behaviour that the parent process is
261    suspended while the child is using its resources.
262 
263    The pipe is then used to send an eventual error code set by the child in
264    posix_spawn() to the parent. If there is any error Valgrind returns it as
265    an error from the vfork() syscall. This means the syscall can return errors
266    that it would normally never return but this is not a problem in practice
267    because any error is directly propagated as a return code from
268    posix_spawn().
269 
270    Address of vg_vfork_fildes is found by Valgrind when debug information for
271    vgpreload_core.so is being processed. A value of this variable is set in
272    the forksys pre-wrapper before a fork() call is made and set back to -1
273    before returning from the wrapper by the parent.
274 
275    Newer Solaris versions introduce the spawn syscall and posix_spawn() is
276    implemented using it. The redirect is not needed for these versions.
277 */
278 int vg_vfork_fildes = -1;
279 
280 int VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME, get_error)(int *errp);
VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME,get_error)281 int VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME, get_error)(int *errp)
282 {
283    /* Always return 0 when the parent tries to call get_error(). Any error
284       from the child is returned directly as an error from the vfork child.
285       Value pointed by errp is initialized only by the child so not
286       redirecting this function would mean that the parent gets an
287       uninitialized/garbage value when it calls this function. */
288    return 0;
289 }
290 
291 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)292 int VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME, set_error)(int *errp, int err)
293 {
294    *errp = err;
295 
296    /* Libc should always call set_error() only after doing a vfork() syscall
297       in posix_spawn(). The forksys pre-wrapper saves a descriptor of the
298       child's end of the pipe in vg_vfork_fildes so it is an error if it is
299       not a valid file descriptor at this point. */
300    assert(vg_vfork_fildes >= 0);
301    /* Current protocol between this function and the forksys pre-wrapper
302       allows to send only errors in range [0, 255] (one byte values). */
303    assert(err >= 0 && err <= 0xff);
304 
305    if (err != 0) {
306       unsigned char w = (unsigned char)(err & 0xff);
307       ssize_t res;
308       do {
309          res = write(vg_vfork_fildes, &w, 1);
310          assert(res == 1 || (errno == EINTR || errno == ERESTART));
311       } while (res != 1);
312    }
313 
314    return err;
315 }
316 
317 /* Replace spawnveg() in libast.so.1. This function is used by ksh to spawn
318    new processes. The library has a build time option to select between
319    several variants of this function based on behaviour of vfork() and
320    posix_spawn() on the system for which the library is being compiled.
321    Unfortunately, Solaris and illumos use the real vfork() variant which does
322    not work correctly with the vfork() -> fork() translation done by Valgrind
323    (see the forksys pre-wrapper for details). Therefore the function is
324    replaced here with an implementation that uses posix_spawn(). This
325    replacement can be removed when a configuration of libast in Solaris and
326    illumos is changed to use the posix_spawn() implementation.
327 */
328 pid_t VG_REPLACE_FUNCTION_ZU(libastZdsoZd1, spawnveg)(const char *command,
329                                                       char **argv,
330                                                       char **envv,
331                                                       pid_t pgid);
VG_REPLACE_FUNCTION_ZU(libastZdsoZd1,spawnveg)332 pid_t VG_REPLACE_FUNCTION_ZU(libastZdsoZd1, spawnveg)(const char *command,
333                                                       char **argv,
334                                                       char **envp,
335                                                       pid_t pgid)
336 {
337    int err = 0;
338    pid_t pid;
339    posix_spawnattr_t attr;
340    int attr_init_done = 0;
341 
342    err = posix_spawnattr_init(&attr);
343    if (err != 0)
344       goto out;
345    attr_init_done = 1;
346 
347    err = posix_spawnattr_init(&attr);
348    if (err != 0)
349       goto out;
350 
351    if (pgid != 0) {
352       if (pgid <= 1)
353          pgid = 0;
354       err = posix_spawnattr_setpgroup(&attr, pgid);
355       if (err != 0)
356          goto out;
357       err = posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETPGROUP);
358       if (err != 0)
359          goto out;
360    }
361 
362    err = posix_spawn(&pid, command, NULL, &attr, argv, envp ? envp : environ);
363 
364 out:
365    if (attr_init_done)
366       posix_spawnattr_destroy(&attr);
367    if (err != 0) {
368       errno = err;
369       return -1;
370    }
371    return pid;
372 }
373 
374 #else
375 #  error Unknown OS
376 #endif
377 
378 /*--------------------------------------------------------------------*/
379 /*--- end                                                          ---*/
380 /*--------------------------------------------------------------------*/
381