2 /*--------------------------------------------------------------------*/
3 /*--- Client-space code for the core. vg_preloaded.c ---*/
4 /*--------------------------------------------------------------------*/
7 This file is part of Valgrind, a dynamic binary instrumentation
10 Copyright (C) 2000-2017 Julian Seward
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.
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.
23 You should have received a copy of the GNU General Public License
24 along with this program; if not, see <http://www.gnu.org/licenses/>.
26 The GNU General Public License is contained in the file COPYING.
30 /* ---------------------------------------------------------------------
31 ALL THE CODE IN THIS FILE RUNS ON THE SIMULATED CPU.
33 These functions are not called directly - they're the targets of code
34 redirection or load notifications (see pub_core_redir.h for info).
35 They're named weirdly so that the intercept code can find them when the
36 shared object is initially loaded.
38 Note that this filename has the "vg_" prefix because it can appear
39 in stack traces, and the "vg_" makes it a little clearer that it
40 originates from Valgrind.
41 ------------------------------------------------------------------ */
43 #include "pub_core_basics.h"
44 #include "pub_core_clreq.h"
45 #include "pub_core_debuginfo.h" // Needed for pub_core_redir.h
46 #include "pub_core_redir.h" // For VG_NOTIFY_ON_LOAD
48 #ifdef HAVE_HEADER_FEATURES_H
52 #if !defined(VGO_darwin)
53 /* Instruct GDB via a .debug_gdb_scripts section to load the valgrind and tool
54 front-end commands. */
55 /* Note: The "MS" section flags are to remove duplicates. */
56 #define DEFINE_GDB_PY_SCRIPT(script_name) \
58 .pushsection \".debug_gdb_scripts\", \"MS\",@progbits,1\n\
59 .byte 1 /* Python */\n\
60 .asciz \"" script_name "\"\n\
64 #ifdef VG_GDBSCRIPTS_DIR
65 DEFINE_GDB_PY_SCRIPT(VG_GDBSCRIPTS_DIR
"/valgrind-monitor.py")
69 #if defined(VGO_linux) || defined(VGO_solaris) || defined(VGO_freebsd)
71 /* ---------------------------------------------------------------------
72 Hook for running __gnu_cxx::__freeres() and __libc_freeres() once
74 ------------------------------------------------------------------ */
76 void VG_NOTIFY_ON_LOAD(freeres
)(Vg_FreeresToRun to_run
);
77 void VG_NOTIFY_ON_LOAD(freeres
)(Vg_FreeresToRun to_run
)
79 # if !defined(__UCLIBC__) \
80 && !defined(VGPV_arm_linux_android) \
81 && !defined(VGPV_x86_linux_android) \
82 && !defined(VGPV_mips32_linux_android) \
83 && !defined(VGPV_arm64_linux_android)
85 /* g++ mangled __gnu_cxx::__freeres yields -> _ZN9__gnu_cxx9__freeresEv */
86 extern void _ZN9__gnu_cxx9__freeresEv(void) __attribute__((weak
));
87 if (((to_run
& VG_RUN__GNU_CXX__FREERES
) != 0) &&
88 (_ZN9__gnu_cxx9__freeresEv
!= NULL
)) {
89 _ZN9__gnu_cxx9__freeresEv();
94 # if !defined(__UCLIBC__) && !defined(MUSL_LIBC) \
95 && !defined(VGPV_arm_linux_android) \
96 && !defined(VGPV_x86_linux_android) \
97 && !defined(VGPV_mips32_linux_android) \
98 && !defined(VGPV_arm64_linux_android)
100 extern void __libc_freeres(void) __attribute__((weak
));
101 if (((to_run
& VG_RUN__LIBC_FREERES
) != 0) &&
102 (__libc_freeres
!= NULL
)) {
108 VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__FREERES_DONE
, 0, 0, 0, 0, 0);
110 *(volatile int *)0 = 'x';
113 #endif // VGO_linux || VGO_solaris
115 #if defined(VGO_linux)
117 /* ---------------------------------------------------------------------
118 Wrapper for indirect functions which need to be redirected.
119 ------------------------------------------------------------------ */
121 void * VG_NOTIFY_ON_LOAD(ifunc_wrapper
) (void);
122 void * VG_NOTIFY_ON_LOAD(ifunc_wrapper
) (void)
128 /* Call the original indirect function and get it's result */
129 VALGRIND_GET_ORIG_FN(fn
);
130 CALL_FN_W_v(result
, fn
);
132 #if defined(VGP_ppc64be_linux)
133 /* ppc64be uses function descriptors, so get the actual function entry
134 address for the client request, but return the function descriptor
136 result points to the function descriptor, which starts with the
138 fnentry
= *(Addr
*)result
;
143 /* Ask the valgrind core running on the real CPU (as opposed to this
144 code which runs on the emulated CPU) to update the redirection that
145 led to this function. This client request eventually gives control to
146 the function VG_(redir_add_ifunc_target) in m_redir.c */
147 VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__ADD_IFUNC_TARGET
,
148 fn
.nraddr
, fnentry
, 0, 0, 0);
149 return (void*)result
;
152 #elif defined(VGO_darwin)
154 #include "config.h" /* VERSION */
156 /* ---------------------------------------------------------------------
157 Darwin crash log hints
158 ------------------------------------------------------------------ */
160 /* This string will be inserted into crash logs, so crashes while
161 running under Valgrind can be distinguished from other crashes. */
162 __private_extern__
const char *__crashreporter_info__
= "Instrumented by Valgrind " VERSION
;
164 /* ---------------------------------------------------------------------
165 Darwin environment cleanup
166 ------------------------------------------------------------------ */
168 /* Scrubbing DYLD_INSERT_LIBRARIES from envp during exec is insufficient,
169 as there are other ways to launch a process with environment that
170 valgrind can't catch easily (i.e. launchd).
171 Instead, scrub DYLD_INSERT_LIBRARIES from the parent process once
172 dyld is done loading vg_preload.so.
175 #include <crt_externs.h>
177 // GrP fixme copied from m_libcproc
178 static void env_unsetenv ( HChar
**env
, const HChar
*varname
)
182 Int len
= strlen(varname
);
184 for (from
= to
= env
; from
&& *from
; from
++) {
185 if (!(strncmp(varname
, *from
, len
) == 0 && (*from
)[len
] == '=')) {
191 /* fix the 4th "char* apple" pointer (aka. executable path pointer) */
196 static void vg_cleanup_env(void) __attribute__((constructor
));
197 static void vg_cleanup_env(void)
199 HChar
**envp
= (HChar
**)*_NSGetEnviron();
200 env_unsetenv(envp
, "VALGRIND_LAUNCHER");
201 env_unsetenv(envp
, "DYLD_SHARED_REGION");
202 // GrP fixme should be more like mash_colon_env()
203 env_unsetenv(envp
, "DYLD_INSERT_LIBRARIES");
206 /* ---------------------------------------------------------------------
207 Darwin arc4random (rdar://6166275)
208 ------------------------------------------------------------------ */
213 int VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib
, arc4random
)(void);
214 int VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib
, arc4random
)(void)
219 if (rnd
< 0) rnd
= open("/dev/random", O_RDONLY
);
221 read(rnd
, &result
, sizeof(result
));
225 void VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib
, arc4random_stir
)(void);
226 void VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib
, arc4random_stir
)(void)
231 void VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib
, arc4random_addrandom
)(unsigned char *dat
, int datlen
);
232 void VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib
, arc4random_addrandom
)(unsigned char *dat
, int datlen
)
235 // GrP fixme ought to check [dat..dat+datlen) is defined
236 // but don't care if it's initialized
239 #elif defined(VGO_freebsd)
241 void * VG_NOTIFY_ON_LOAD(ifunc_wrapper
) (void);
242 void * VG_NOTIFY_ON_LOAD(ifunc_wrapper
) (void)
248 /* Call the original indirect function and get it's result */
249 VALGRIND_GET_ORIG_FN(fn
);
250 CALL_FN_W_v(result
, fn
);
254 VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__ADD_IFUNC_TARGET
,
255 fn
.nraddr
, fnentry
, 0, 0, 0);
256 return (void*)result
;
259 #elif defined(VGO_solaris)
261 /* Declare the errno and environ symbols weakly in case the client is not
262 linked against libc. In such a case it also cannot run replacement
263 functions for set_error() and spawnveg() where these two variables are
264 needed so this is ok. */
265 __attribute__((weak
)) extern int errno
;
266 __attribute__((weak
)) extern char **environ
;
271 #include <sys/syscall.h>
272 #include <sys/signal.h>
275 /* Replace function block_all_signals() from libc. When the client program is
276 not running under valgrind, the function blocks all signals by setting
277 sc_sigblock flag in the schedctl control block. When run under Valgrind
278 this would bypass Valgrind's syscall and signal machinery.
279 Valgrind's signal machinery needs to retain control over which signals are
280 blocked and which not (see m_signals.c and m_scheduler/scheduler.c for more
281 information - typically synchronous signals should not be blocked).
282 Therefore this function replacement emulates lwp_sigmask syscall.
284 void VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME
, block_all_signals
)(/*ulwp_t*/ void *self
);
285 void VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME
, block_all_signals
)(/*ulwp_t*/ void *self
)
287 syscall(SYS_lwp_sigmask
, SIG_SETMASK
, ~0U, ~0U, ~0U, ~0U);
290 /* Replace functions get_error() and set_error() in libc. These functions are
291 internal to the library and are used to work with an error value returned
292 by posix_spawn() (when it is implemented using vfork()). A child calls
293 set_error() to set an error code and the parent then calls get_error() to
294 read it. Accessor functions are used so these trivial store+load operations
295 are not changed by the compiler in any way.
297 Since Valgrind translates vfork() to a normal fork(), calling set_error()
298 by the child would have no effect on the error value in the parent so
299 something must be done to fix this problem.
301 A pipe is created between a child and its parent in the forksys pre-wrapper
302 when a vfork() is encountered. The child's end of the pipe is closed when
303 the child exits or execs (because close-on-exec is set on the file
304 descriptor). Valgrind (the parent) waits on the child's end of the pipe to
305 be closed which preserves the vfork() behaviour that the parent process is
306 suspended while the child is using its resources.
308 The pipe is then used to send an eventual error code set by the child in
309 posix_spawn() to the parent. If there is any error Valgrind returns it as
310 an error from the vfork() syscall. This means the syscall can return errors
311 that it would normally never return but this is not a problem in practice
312 because any error is directly propagated as a return code from
315 Address of vg_vfork_fildes is found by Valgrind when debug information for
316 vgpreload_core.so is being processed. A value of this variable is set in
317 the forksys pre-wrapper before a fork() call is made and set back to -1
318 before returning from the wrapper by the parent.
320 Newer Solaris versions introduce the spawn syscall and posix_spawn() is
321 implemented using it. The redirect is not needed for these versions.
323 int vg_vfork_fildes
= -1;
325 int VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME
, get_error
)(int *errp
);
326 int VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME
, get_error
)(int *errp
)
328 /* Always return 0 when the parent tries to call get_error(). Any error
329 from the child is returned directly as an error from the vfork child.
330 Value pointed by errp is initialized only by the child so not
331 redirecting this function would mean that the parent gets an
332 uninitialized/garbage value when it calls this function. */
336 int VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME
, set_error
)(int *errp
, int err
);
337 int VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME
, set_error
)(int *errp
, int err
)
341 /* Libc should always call set_error() only after doing a vfork() syscall
342 in posix_spawn(). The forksys pre-wrapper saves a descriptor of the
343 child's end of the pipe in vg_vfork_fildes so it is an error if it is
344 not a valid file descriptor at this point. */
345 assert(vg_vfork_fildes
>= 0);
346 /* Current protocol between this function and the forksys pre-wrapper
347 allows to send only errors in range [0, 255] (one byte values). */
348 assert(err
>= 0 && err
<= 0xff);
351 unsigned char w
= (unsigned char)(err
& 0xff);
354 res
= write(vg_vfork_fildes
, &w
, 1);
355 assert(res
== 1 || (errno
== EINTR
|| errno
== ERESTART
));
362 /* Replace spawnveg() in libast.so.1. This function is used by ksh to spawn
363 new processes. The library has a build time option to select between
364 several variants of this function based on behaviour of vfork() and
365 posix_spawn() on the system for which the library is being compiled.
366 Unfortunately, Solaris and illumos use the real vfork() variant which does
367 not work correctly with the vfork() -> fork() translation done by Valgrind
368 (see the forksys pre-wrapper for details). Therefore the function is
369 replaced here with an implementation that uses posix_spawn(). This
370 replacement can be removed when a configuration of libast in Solaris and
371 illumos is changed to use the posix_spawn() implementation.
373 pid_t
VG_REPLACE_FUNCTION_ZU(libastZdsoZd1
, spawnveg
)(const char *command
,
377 pid_t
VG_REPLACE_FUNCTION_ZU(libastZdsoZd1
, spawnveg
)(const char *command
,
384 posix_spawnattr_t attr
;
385 int attr_init_done
= 0;
387 err
= posix_spawnattr_init(&attr
);
392 err
= posix_spawnattr_init(&attr
);
399 err
= posix_spawnattr_setpgroup(&attr
, pgid
);
402 err
= posix_spawnattr_setflags(&attr
, POSIX_SPAWN_SETPGROUP
);
407 err
= posix_spawn(&pid
, command
, NULL
, &attr
, argv
, envp
? envp
: environ
);
411 posix_spawnattr_destroy(&attr
);
423 /*--------------------------------------------------------------------*/
425 /*--------------------------------------------------------------------*/