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 DEFINE_GDB_PY_SCRIPT(VG_LIBDIR
"/valgrind-monitor.py")
67 #if defined(VGO_linux) || defined(VGO_solaris) || defined(VGO_freebsd)
69 /* ---------------------------------------------------------------------
70 Hook for running __gnu_cxx::__freeres() and __libc_freeres() once
72 ------------------------------------------------------------------ */
74 void VG_NOTIFY_ON_LOAD(freeres
)(Vg_FreeresToRun to_run
);
75 void VG_NOTIFY_ON_LOAD(freeres
)(Vg_FreeresToRun to_run
)
77 # if !defined(__UCLIBC__) && !defined(MUSL_LIBC) \
78 && !defined(VGPV_arm_linux_android) \
79 && !defined(VGPV_x86_linux_android) \
80 && !defined(VGPV_mips32_linux_android) \
81 && !defined(VGPV_arm64_linux_android)
83 /* g++ mangled __gnu_cxx::__freeres yields -> _ZN9__gnu_cxx9__freeresEv */
84 extern void _ZN9__gnu_cxx9__freeresEv(void) __attribute__((weak
));
85 if (((to_run
& VG_RUN__GNU_CXX__FREERES
) != 0) &&
86 (_ZN9__gnu_cxx9__freeresEv
!= NULL
)) {
87 _ZN9__gnu_cxx9__freeresEv();
90 extern void __libc_freeres(void) __attribute__((weak
));
91 if (((to_run
& VG_RUN__LIBC_FREERES
) != 0) &&
92 (__libc_freeres
!= NULL
)) {
98 VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__FREERES_DONE
, 0, 0, 0, 0, 0);
100 *(volatile int *)0 = 'x';
103 #endif // VGO_linux || VGO_solaris
105 #if defined(VGO_linux)
107 /* ---------------------------------------------------------------------
108 Wrapper for indirect functions which need to be redirected.
109 ------------------------------------------------------------------ */
111 void * VG_NOTIFY_ON_LOAD(ifunc_wrapper
) (void);
112 void * VG_NOTIFY_ON_LOAD(ifunc_wrapper
) (void)
118 /* Call the original indirect function and get it's result */
119 VALGRIND_GET_ORIG_FN(fn
);
120 CALL_FN_W_v(result
, fn
);
122 #if defined(VGP_ppc64be_linux)
123 /* ppc64be uses function descriptors, so get the actual function entry
124 address for the client request, but return the function descriptor
126 result points to the function descriptor, which starts with the
128 fnentry
= *(Addr
*)result
;
133 /* Ask the valgrind core running on the real CPU (as opposed to this
134 code which runs on the emulated CPU) to update the redirection that
135 led to this function. This client request eventually gives control to
136 the function VG_(redir_add_ifunc_target) in m_redir.c */
137 VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__ADD_IFUNC_TARGET
,
138 fn
.nraddr
, fnentry
, 0, 0, 0);
139 return (void*)result
;
142 #elif defined(VGO_darwin)
144 #include "config.h" /* VERSION */
146 /* ---------------------------------------------------------------------
147 Darwin crash log hints
148 ------------------------------------------------------------------ */
150 /* This string will be inserted into crash logs, so crashes while
151 running under Valgrind can be distinguished from other crashes. */
152 __private_extern__
const char *__crashreporter_info__
= "Instrumented by Valgrind " VERSION
;
154 /* ---------------------------------------------------------------------
155 Darwin environment cleanup
156 ------------------------------------------------------------------ */
158 /* Scrubbing DYLD_INSERT_LIBRARIES from envp during exec is insufficient,
159 as there are other ways to launch a process with environment that
160 valgrind can't catch easily (i.e. launchd).
161 Instead, scrub DYLD_INSERT_LIBRARIES from the parent process once
162 dyld is done loading vg_preload.so.
165 #include <crt_externs.h>
167 // GrP fixme copied from m_libcproc
168 static void env_unsetenv ( HChar
**env
, const HChar
*varname
)
172 Int len
= strlen(varname
);
174 for (from
= to
= env
; from
&& *from
; from
++) {
175 if (!(strncmp(varname
, *from
, len
) == 0 && (*from
)[len
] == '=')) {
181 /* fix the 4th "char* apple" pointer (aka. executable path pointer) */
186 static void vg_cleanup_env(void) __attribute__((constructor
));
187 static void vg_cleanup_env(void)
189 HChar
**envp
= (HChar
**)*_NSGetEnviron();
190 env_unsetenv(envp
, "VALGRIND_LAUNCHER");
191 env_unsetenv(envp
, "DYLD_SHARED_REGION");
192 // GrP fixme should be more like mash_colon_env()
193 env_unsetenv(envp
, "DYLD_INSERT_LIBRARIES");
196 /* ---------------------------------------------------------------------
197 Darwin arc4random (rdar://6166275)
198 ------------------------------------------------------------------ */
203 int VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib
, arc4random
)(void);
204 int VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib
, arc4random
)(void)
209 if (rnd
< 0) rnd
= open("/dev/random", O_RDONLY
);
211 read(rnd
, &result
, sizeof(result
));
215 void VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib
, arc4random_stir
)(void);
216 void VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib
, arc4random_stir
)(void)
221 void VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib
, arc4random_addrandom
)(unsigned char *dat
, int datlen
);
222 void VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib
, arc4random_addrandom
)(unsigned char *dat
, int datlen
)
225 // GrP fixme ought to check [dat..dat+datlen) is defined
226 // but don't care if it's initialized
229 #elif defined(VGO_freebsd)
231 // nothing specific currently
233 #elif defined(VGO_solaris)
235 /* Declare the errno and environ symbols weakly in case the client is not
236 linked against libc. In such a case it also cannot run replacement
237 functions for set_error() and spawnveg() where these two variables are
238 needed so this is ok. */
239 __attribute__((weak
)) extern int errno
;
240 __attribute__((weak
)) extern char **environ
;
245 #include <sys/syscall.h>
246 #include <sys/signal.h>
249 /* Replace function block_all_signals() from libc. When the client program is
250 not running under valgrind, the function blocks all signals by setting
251 sc_sigblock flag in the schedctl control block. When run under Valgrind
252 this would bypass Valgrind's syscall and signal machinery.
253 Valgrind's signal machinery needs to retain control over which signals are
254 blocked and which not (see m_signals.c and m_scheduler/scheduler.c for more
255 information - typically synchronous signals should not be blocked).
256 Therefore this function replacement emulates lwp_sigmask syscall.
258 void VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME
, block_all_signals
)(/*ulwp_t*/ void *self
);
259 void VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME
, block_all_signals
)(/*ulwp_t*/ void *self
)
261 syscall(SYS_lwp_sigmask
, SIG_SETMASK
, ~0U, ~0U, ~0U, ~0U);
264 /* Replace functions get_error() and set_error() in libc. These functions are
265 internal to the library and are used to work with an error value returned
266 by posix_spawn() (when it is implemented using vfork()). A child calls
267 set_error() to set an error code and the parent then calls get_error() to
268 read it. Accessor functions are used so these trivial store+load operations
269 are not changed by the compiler in any way.
271 Since Valgrind translates vfork() to a normal fork(), calling set_error()
272 by the child would have no effect on the error value in the parent so
273 something must be done to fix this problem.
275 A pipe is created between a child and its parent in the forksys pre-wrapper
276 when a vfork() is encountered. The child's end of the pipe is closed when
277 the child exits or execs (because close-on-exec is set on the file
278 descriptor). Valgrind (the parent) waits on the child's end of the pipe to
279 be closed which preserves the vfork() behaviour that the parent process is
280 suspended while the child is using its resources.
282 The pipe is then used to send an eventual error code set by the child in
283 posix_spawn() to the parent. If there is any error Valgrind returns it as
284 an error from the vfork() syscall. This means the syscall can return errors
285 that it would normally never return but this is not a problem in practice
286 because any error is directly propagated as a return code from
289 Address of vg_vfork_fildes is found by Valgrind when debug information for
290 vgpreload_core.so is being processed. A value of this variable is set in
291 the forksys pre-wrapper before a fork() call is made and set back to -1
292 before returning from the wrapper by the parent.
294 Newer Solaris versions introduce the spawn syscall and posix_spawn() is
295 implemented using it. The redirect is not needed for these versions.
297 int vg_vfork_fildes
= -1;
299 int VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME
, get_error
)(int *errp
);
300 int VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME
, get_error
)(int *errp
)
302 /* Always return 0 when the parent tries to call get_error(). Any error
303 from the child is returned directly as an error from the vfork child.
304 Value pointed by errp is initialized only by the child so not
305 redirecting this function would mean that the parent gets an
306 uninitialized/garbage value when it calls this function. */
310 int VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME
, set_error
)(int *errp
, int err
);
311 int VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME
, set_error
)(int *errp
, int err
)
315 /* Libc should always call set_error() only after doing a vfork() syscall
316 in posix_spawn(). The forksys pre-wrapper saves a descriptor of the
317 child's end of the pipe in vg_vfork_fildes so it is an error if it is
318 not a valid file descriptor at this point. */
319 assert(vg_vfork_fildes
>= 0);
320 /* Current protocol between this function and the forksys pre-wrapper
321 allows to send only errors in range [0, 255] (one byte values). */
322 assert(err
>= 0 && err
<= 0xff);
325 unsigned char w
= (unsigned char)(err
& 0xff);
328 res
= write(vg_vfork_fildes
, &w
, 1);
329 assert(res
== 1 || (errno
== EINTR
|| errno
== ERESTART
));
336 /* Replace spawnveg() in libast.so.1. This function is used by ksh to spawn
337 new processes. The library has a build time option to select between
338 several variants of this function based on behaviour of vfork() and
339 posix_spawn() on the system for which the library is being compiled.
340 Unfortunately, Solaris and illumos use the real vfork() variant which does
341 not work correctly with the vfork() -> fork() translation done by Valgrind
342 (see the forksys pre-wrapper for details). Therefore the function is
343 replaced here with an implementation that uses posix_spawn(). This
344 replacement can be removed when a configuration of libast in Solaris and
345 illumos is changed to use the posix_spawn() implementation.
347 pid_t
VG_REPLACE_FUNCTION_ZU(libastZdsoZd1
, spawnveg
)(const char *command
,
351 pid_t
VG_REPLACE_FUNCTION_ZU(libastZdsoZd1
, spawnveg
)(const char *command
,
358 posix_spawnattr_t attr
;
359 int attr_init_done
= 0;
361 err
= posix_spawnattr_init(&attr
);
366 err
= posix_spawnattr_init(&attr
);
373 err
= posix_spawnattr_setpgroup(&attr
, pgid
);
376 err
= posix_spawnattr_setflags(&attr
, POSIX_SPAWN_SETPGROUP
);
381 err
= posix_spawn(&pid
, command
, NULL
, &attr
, argv
, envp
? envp
: environ
);
385 posix_spawnattr_destroy(&attr
);
397 /*--------------------------------------------------------------------*/
399 /*--------------------------------------------------------------------*/