syswrap openat2 for all linux arches
[valgrind.git] / coregrind / vg_preloaded.c
blob7986eeec5275cb2e0aa2407f0f2bc6d42cda475c
2 /*--------------------------------------------------------------------*/
3 /*--- Client-space code for the core. vg_preloaded.c ---*/
4 /*--------------------------------------------------------------------*/
6 /*
7 This file is part of Valgrind, a dynamic binary instrumentation
8 framework.
10 Copyright (C) 2000-2017 Julian Seward
11 jseward@acm.org
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
49 #include <features.h>
50 #endif
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) \
57 asm("\
58 .pushsection \".debug_gdb_scripts\", \"MS\",@progbits,1\n\
59 .byte 1 /* Python */\n\
60 .asciz \"" script_name "\"\n\
61 .popsection \n\
62 ");
64 #ifdef VG_GDBSCRIPTS_DIR
65 DEFINE_GDB_PY_SCRIPT(VG_GDBSCRIPTS_DIR "/valgrind-monitor.py")
66 #endif
67 #endif
69 #if defined(VGO_linux) || defined(VGO_solaris) || defined(VGO_freebsd)
71 /* ---------------------------------------------------------------------
72 Hook for running __gnu_cxx::__freeres() and __libc_freeres() once
73 the program exits.
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();
92 # endif
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)) {
103 __libc_freeres();
106 # endif
108 VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__FREERES_DONE, 0, 0, 0, 0, 0);
109 /*NOTREACHED*/
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)
124 OrigFn fn;
125 Addr result = 0;
126 Addr fnentry;
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
135 from this function.
136 result points to the function descriptor, which starts with the
137 function entry. */
138 fnentry = *(Addr*)result;
139 #else
140 fnentry = result;
141 #endif
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.
174 #include <string.h>
175 #include <crt_externs.h>
177 // GrP fixme copied from m_libcproc
178 static void env_unsetenv ( HChar **env, const HChar *varname )
180 HChar **from;
181 HChar **to = NULL;
182 Int len = strlen(varname);
184 for (from = to = env; from && *from; from++) {
185 if (!(strncmp(varname, *from, len) == 0 && (*from)[len] == '=')) {
186 *to = *from;
187 to++;
190 *(to++) = *(from++);
191 /* fix the 4th "char* apple" pointer (aka. executable path pointer) */
192 *(to++) = *(from++);
193 *to = NULL;
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 ------------------------------------------------------------------ */
210 #include <fcntl.h>
211 #include <unistd.h>
213 int VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib, arc4random)(void);
214 int VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib, arc4random)(void)
216 static int rnd = -1;
217 int result;
219 if (rnd < 0) rnd = open("/dev/random", O_RDONLY);
221 read(rnd, &result, sizeof(result));
222 return result;
225 void VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib, arc4random_stir)(void);
226 void VG_REPLACE_FUNCTION_ZU(libSystemZdZaZddylib, arc4random_stir)(void)
228 // do nothing
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)
234 // do nothing
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 #if (FREEBSD_VERS >= FREEBSD_13)
243 void * VG_NOTIFY_ON_LOAD(ifunc_wrapper) (void);
244 void * VG_NOTIFY_ON_LOAD(ifunc_wrapper) (void)
246 OrigFn fn;
247 Addr result = 0;
248 Addr fnentry;
250 /* Call the original indirect function and get it's result */
251 VALGRIND_GET_ORIG_FN(fn);
252 CALL_FN_W_v(result, fn);
254 fnentry = result;
256 VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__ADD_IFUNC_TARGET,
257 fn.nraddr, fnentry, 0, 0, 0);
258 return (void*)result;
261 #endif
263 #elif defined(VGO_solaris)
265 /* Declare the errno and environ symbols weakly in case the client is not
266 linked against libc. In such a case it also cannot run replacement
267 functions for set_error() and spawnveg() where these two variables are
268 needed so this is ok. */
269 __attribute__((weak)) extern int errno;
270 __attribute__((weak)) extern char **environ;
272 #include <assert.h>
273 #include <errno.h>
274 #include <spawn.h>
275 #include <sys/syscall.h>
276 #include <sys/signal.h>
277 #include <unistd.h>
279 /* Replace function block_all_signals() from libc. When the client program is
280 not running under valgrind, the function blocks all signals by setting
281 sc_sigblock flag in the schedctl control block. When run under Valgrind
282 this would bypass Valgrind's syscall and signal machinery.
283 Valgrind's signal machinery needs to retain control over which signals are
284 blocked and which not (see m_signals.c and m_scheduler/scheduler.c for more
285 information - typically synchronous signals should not be blocked).
286 Therefore this function replacement emulates lwp_sigmask syscall.
288 void VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME, block_all_signals)(/*ulwp_t*/ void *self);
289 void VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME, block_all_signals)(/*ulwp_t*/ void *self)
291 syscall(SYS_lwp_sigmask, SIG_SETMASK, ~0U, ~0U, ~0U, ~0U);
294 /* Replace functions get_error() and set_error() in libc. These functions are
295 internal to the library and are used to work with an error value returned
296 by posix_spawn() (when it is implemented using vfork()). A child calls
297 set_error() to set an error code and the parent then calls get_error() to
298 read it. Accessor functions are used so these trivial store+load operations
299 are not changed by the compiler in any way.
301 Since Valgrind translates vfork() to a normal fork(), calling set_error()
302 by the child would have no effect on the error value in the parent so
303 something must be done to fix this problem.
305 A pipe is created between a child and its parent in the forksys pre-wrapper
306 when a vfork() is encountered. The child's end of the pipe is closed when
307 the child exits or execs (because close-on-exec is set on the file
308 descriptor). Valgrind (the parent) waits on the child's end of the pipe to
309 be closed which preserves the vfork() behaviour that the parent process is
310 suspended while the child is using its resources.
312 The pipe is then used to send an eventual error code set by the child in
313 posix_spawn() to the parent. If there is any error Valgrind returns it as
314 an error from the vfork() syscall. This means the syscall can return errors
315 that it would normally never return but this is not a problem in practice
316 because any error is directly propagated as a return code from
317 posix_spawn().
319 Address of vg_vfork_fildes is found by Valgrind when debug information for
320 vgpreload_core.so is being processed. A value of this variable is set in
321 the forksys pre-wrapper before a fork() call is made and set back to -1
322 before returning from the wrapper by the parent.
324 Newer Solaris versions introduce the spawn syscall and posix_spawn() is
325 implemented using it. The redirect is not needed for these versions.
327 int vg_vfork_fildes = -1;
329 int VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME, get_error)(int *errp);
330 int VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME, get_error)(int *errp)
332 /* Always return 0 when the parent tries to call get_error(). Any error
333 from the child is returned directly as an error from the vfork child.
334 Value pointed by errp is initialized only by the child so not
335 redirecting this function would mean that the parent gets an
336 uninitialized/garbage value when it calls this function. */
337 return 0;
340 int VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME, set_error)(int *errp, int err);
341 int VG_REPLACE_FUNCTION_ZU(VG_Z_LIBC_SONAME, set_error)(int *errp, int err)
343 *errp = err;
345 /* Libc should always call set_error() only after doing a vfork() syscall
346 in posix_spawn(). The forksys pre-wrapper saves a descriptor of the
347 child's end of the pipe in vg_vfork_fildes so it is an error if it is
348 not a valid file descriptor at this point. */
349 assert(vg_vfork_fildes >= 0);
350 /* Current protocol between this function and the forksys pre-wrapper
351 allows to send only errors in range [0, 255] (one byte values). */
352 assert(err >= 0 && err <= 0xff);
354 if (err != 0) {
355 unsigned char w = (unsigned char)(err & 0xff);
356 ssize_t res;
357 do {
358 res = write(vg_vfork_fildes, &w, 1);
359 assert(res == 1 || (errno == EINTR || errno == ERESTART));
360 } while (res != 1);
363 return err;
366 /* Replace spawnveg() in libast.so.1. This function is used by ksh to spawn
367 new processes. The library has a build time option to select between
368 several variants of this function based on behaviour of vfork() and
369 posix_spawn() on the system for which the library is being compiled.
370 Unfortunately, Solaris and illumos use the real vfork() variant which does
371 not work correctly with the vfork() -> fork() translation done by Valgrind
372 (see the forksys pre-wrapper for details). Therefore the function is
373 replaced here with an implementation that uses posix_spawn(). This
374 replacement can be removed when a configuration of libast in Solaris and
375 illumos is changed to use the posix_spawn() implementation.
377 pid_t VG_REPLACE_FUNCTION_ZU(libastZdsoZd1, spawnveg)(const char *command,
378 char **argv,
379 char **envv,
380 pid_t pgid);
381 pid_t VG_REPLACE_FUNCTION_ZU(libastZdsoZd1, spawnveg)(const char *command,
382 char **argv,
383 char **envp,
384 pid_t pgid)
386 int err = 0;
387 pid_t pid;
388 posix_spawnattr_t attr;
389 int attr_init_done = 0;
391 err = posix_spawnattr_init(&attr);
392 if (err != 0)
393 goto out;
394 attr_init_done = 1;
396 err = posix_spawnattr_init(&attr);
397 if (err != 0)
398 goto out;
400 if (pgid != 0) {
401 if (pgid <= 1)
402 pgid = 0;
403 err = posix_spawnattr_setpgroup(&attr, pgid);
404 if (err != 0)
405 goto out;
406 err = posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETPGROUP);
407 if (err != 0)
408 goto out;
411 err = posix_spawn(&pid, command, NULL, &attr, argv, envp ? envp : environ);
413 out:
414 if (attr_init_done)
415 posix_spawnattr_destroy(&attr);
416 if (err != 0) {
417 errno = err;
418 return -1;
420 return pid;
423 #else
424 # error Unknown OS
425 #endif
427 /*--------------------------------------------------------------------*/
428 /*--- end ---*/
429 /*--------------------------------------------------------------------*/