File: execwrappers.cpp

package info (click to toggle)
dmtcp 2.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 6,496 kB
  • sloc: cpp: 33,592; ansic: 28,099; sh: 6,735; makefile: 1,950; perl: 1,690; python: 1,241; asm: 138; java: 13
file content (799 lines) | stat: -rw-r--r-- 26,071 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
/****************************************************************************
 *   Copyright (C) 2006-2013 by Jason Ansel, Kapil Arya, and Gene Cooperman *
 *   jansel@csail.mit.edu, kapil@ccs.neu.edu, gene@ccs.neu.edu              *
 *                                                                          *
 *  This file is part of DMTCP.                                             *
 *                                                                          *
 *  DMTCP is free software: you can redistribute it and/or                  *
 *  modify it under the terms of the GNU Lesser General Public License as   *
 *  published by the Free Software Foundation, either version 3 of the      *
 *  License, or (at your option) any later version.                         *
 *                                                                          *
 *  DMTCP is distributed in the hope that it will be useful,                *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of          *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           *
 *  GNU Lesser General Public License for more details.                     *
 *                                                                          *
 *  You should have received a copy of the GNU Lesser General Public        *
 *  License along with DMTCP:dmtcp/src.  If not, see                        *
 *  <http://www.gnu.org/licenses/>.                                         *
 ****************************************************************************/

#include <sys/syscall.h>
#ifdef __aarch64__
# define __ARCH_WANT_SYSCALL_DEPRECATED
// SYS_fork is a deprecated kernel call in aarch64; in favor of SYS_clone?
# include <asm-generic/unistd.h>
// SYS_fork undefined in aarch64, but add extra insurance
# undef SYS_fork
# define SYS_fork __NR_fork
#endif
#include "constants.h"
#include "uniquepid.h"
#include "dmtcpworker.h"
#include "processinfo.h"
#include "syscallwrappers.h"
#include "syslogwrappers.h"
#include "threadlist.h"
#include "util.h"
#include "coordinatorapi.h"
#include "mtcpinterface.h"
#include "shareddata.h"
#include "threadsync.h"
#include  "../jalib/jconvert.h"
#include  "../jalib/jassert.h"
#include  "../jalib/jfilesystem.h"

#define INITIAL_ARGV_MAX 32

using namespace dmtcp;

#ifdef LOGGING
const static bool dbg = true;
#else // ifdef LOGGING
const static bool dbg = false;
#endif // ifdef LOGGING

static bool pthread_atfork_enabled = false;
static uint64_t child_time;
static CoordinatorAPI coordinatorAPI;

// Allow plugins to call fork/exec/system to perform specific tasks during
// preCKpt/postCkpt/PostRestart etc. event.
static bool isPerformingCkptRestart()
{
  if (WorkerState::currentState() != WorkerState::UNKNOWN &&
      WorkerState::currentState() != WorkerState::RUNNING) {
    return true;
  }
  return false;
}

static bool isBlacklistedProgram(const char *path)
{
  string programName = jalib::Filesystem::BaseName(path);

  JASSERT(programName != "dmtcp_coordinator" &&
          programName != "dmtcp_launch"  &&
          programName != "dmtcp_restart"     &&
          programName != "mtcp_restart")
    (programName) .Text("This program should not be run under ckpt control");

  /*
   * When running gdb or any shell which does a waitpid() on the child
   * processes, executing dmtcp_command from within gdb session / shell results
   * in process getting hung up because:
   *   gdb shell dmtcp_command -c => hangs because gdb forks off a new process
   *   and it does a waitpid  (in which we block signals) ...
   */
  if (programName == "dmtcp_command") {
    //make sure coordinator connection is closed
    _real_close (PROTECTED_COORD_FD);

    pid_t cpid = _real_fork();
    JASSERT(cpid != -1);
    if (cpid != 0) {
      _real_exit(0);
    }
  }

  if (programName == "dmtcp_nocheckpoint" || programName == "dmtcp_command" ||
      programName == "ssh" || programName == "rsh" ) {
    return true;
  }
  return false;
}

LIB_PRIVATE void pthread_atfork_prepare()
{
  /* FIXME: The user process might register a fork prepare handler with
   * pthread_atfork. That handler will be called _after_ we have acquired the
   * wrapper-exec lock in exclusive mode. This can lead to a deadlock situation
   * if the user process decides to do some operations that require calling a
   * dmtcp wrapper that require the wrapper-exec lock.
   *
   * Also, the preparation that dmtcp needs to do for fork() should be done
   * right before the child process is created, i.e. after all the user
   * handlers have been invoked. Fortunately, pthread_atfork prepare handlers
   * are called in reverse order or registration (as opposed to parent and
   * child handlers which are called in the order of registration), thus our
   * prepare handle will be called at the very last.
   *
   * FIXME: PID-conflict detection poses yet another serious problem. On a
   * pid-conflict, _real_fork() will be called more than once, resulting in
   * multiple calls of user-defined prepare handlers. This is undesired and can
   * cause several issues. One solution to this problem is to call the fork
   * system call directly whenever a tid-conflict is detected, however, it
   * might have some other side-effects.  Another possible solution would be to
   * have pid-virtualization plugin, which always assigns virtual pids, to the
   * newly created processes, and thus avoiding the pid-conflict totally.
   */
  return;
}

LIB_PRIVATE void pthread_atfork_parent()
{
  return;
}

LIB_PRIVATE void pthread_atfork_child()
{
  if (!pthread_atfork_enabled) {
    return;
  }
  pthread_atfork_enabled = false;

  uint64_t host = UniquePid::ThisProcess().hostid();
  UniquePid parent = UniquePid::ThisProcess();
  UniquePid child = UniquePid(host, getpid(), child_time);
  string child_name = jalib::Filesystem::GetProgramName() + "_(forked)";
  _dmtcp_remutex_on_fork();
  ThreadSync::resetLocks();

  UniquePid::resetOnFork(child);
  Util::initializeLogFile(child_name);

  ProcessInfo::instance().resetOnFork();

  JLOG(DMTCP)("fork()ed [CHILD]") (child) (parent);
  CoordinatorAPI::resetOnFork(coordinatorAPI);
  DmtcpWorker::resetOnFork();
}

extern "C" pid_t fork()
{
  if (isPerformingCkptRestart() ||
      /*
       * We don't want any user program between post checkpointing and before
       * resuming to run under dmtcp
       */
      (dmtcp_delay_resume_blocked != NULL && dmtcp_delay_resume_blocked())) {
    return _real_syscall(SYS_fork);
  }

  /* Acquire the wrapperExeution lock to prevent checkpoint to happen while
   * processing this system call.
   */
  WRAPPER_EXECUTION_GET_EXCL_LOCK();
  DmtcpWorker::eventHook(DMTCP_EVENT_ATFORK_PREPARE, NULL);

  /* Little bit cheating here: child_time should be same for both parent and
   * child, thus we compute it before forking the child. */
  child_time = time(NULL);
  uint64_t host = UniquePid::ThisProcess().hostid();
  UniquePid parent = UniquePid::ThisProcess();
  string child_name = jalib::Filesystem::GetProgramName() + "_(forked)";

  coordinatorAPI.createNewConnectionBeforeFork(child_name);

  //Enable the pthread_atfork child call
  pthread_atfork_enabled = true;
  pid_t childPid = _real_fork();

  if (childPid == -1) {
  } else if (childPid == 0) { /* child process */
    // ThreadList::resetOnFork calls pthread_create which in turn calls
    // malloc/calloc, etc. This can result in a deadlock if the parent process
    // was holding malloc-lock while forking and might reset the lock only
    // during atfork_child handler. Because our own atfork_child handler is
    // called at the very beginning, the parent process won't have a chance to
    // reset the lock. Calling ThreadList::resetOnFork here ensures that any
    // such locks would have been reset by the caller and hence it's safe to
    // call pthread_creat at this point.
    ThreadList::resetOnFork();

    /* NOTE: Any work that needs to be done for the newly created child
     * should be put into pthread_atfork_child() function. That function is
     * hooked to the libc:fork() and will be called right after the new
     * process is created and before the fork() returns.
     *
     * pthread_atfork_child is registered by calling pthread_atfork() from
     * within the DmtcpWorker constructor to make sure that this is the first
     * registered handle.
     */
    UniquePid child = UniquePid(host, getpid(), child_time);
    JLOG(DMTCP)("fork() done [CHILD]") (child) (parent);

    initializeMtcpEngine();
  } else if (childPid > 0) { /* Parent Process */
    UniquePid child = UniquePid(host, childPid, child_time);
    ProcessInfo::instance().insertChild(childPid, child);
    JLOG(DMTCP)("fork()ed [PARENT] done") (child);;
  }

  pthread_atfork_enabled = false;

  if (childPid != 0) {
    coordinatorAPI.closeConnection();
    DmtcpWorker::eventHook(DMTCP_EVENT_ATFORK_PARENT, NULL);
    WRAPPER_EXECUTION_RELEASE_EXCL_LOCK();
  }
  return childPid;
}

extern "C" pid_t vfork()
{
  JLOG(DMTCP)("vfork wrapper calling fork");
  // This might not preserve the full semantics of vfork.
  // Used for checkpointing gdb.
  return fork();
}

// Special short-lived processes from executables like /lib/libc.so.6
//   and man setuid/setgid executables cannot be loaded with LD_PRELOAD.
// Since they're short-lived, we execute them while holding a lock
//   delaying checkpointing.
static void execShortLivedProcessAndExit(const char *path, char *const argv[])
{
  unsetenv("LD_PRELOAD"); // /lib/ld.so won't let us preload if exec'ing lib
  const unsigned int bufSize = 100000;
  char *buf = (char*)JALLOC_HELPER_MALLOC(bufSize);
  memset(buf, 0, bufSize);
  FILE *output;
  if (argv[0] == NULL) {
    output = _real_popen(path, "r");
  } else {
    string command = path;
    for (int i = 1; argv[i] != NULL; i++)
      command = command + " " + argv[i];
    output = _real_popen(command.c_str(), "r");
  }
  int numRead = fread(buf, 1, bufSize - 1, output);
  numRead++, numRead--; // suppress unused-var warning
  buf[bufSize - 1] = '\0'; // NULL terminate in case the last char is not null

  pclose(output); // /lib/libXXX process is now done; can checkpoint now
  // FIXME:  code currently allows wrapper to proceed without lock if
  //   it was busy because of a writer.  The unlock will then fail below.
  bool __wrapperExecutionLockAcquired = true; // needed for LOCK_UNLOCK macro
  WRAPPER_EXECUTION_RELEASE_EXCL_LOCK();
  // We  are now the new /lib/libXXX process, and it's safe for DMTCP to ckpt us.
  printf("%s", buf); // print buf, which is what /lib/libXXX would print
  JALLOC_HELPER_FREE(buf);
  // Avoid running exit handlers of the parent process by calling _exit.
  _exit(0);
}

// FIXME:  Unify this code with code prior to execvp in dmtcp_launch.cpp
//   Can use argument to dmtcpPrepareForExec() or getenv("DMTCP_...")
//   from DmtcpWorker constructor, to distinguish the two cases.
static void dmtcpPrepareForExec(const char *path, char *const argv[],
                                char **filename, char ***newArgv)
{
  JLOG(DMTCP)("Preparing for Exec") (path);

  const char * libPrefix = "/lib/lib";
  const char * lib64Prefix = "/lib64/lib";
  if (path != NULL && Util::strStartsWith(path, libPrefix))
    execShortLivedProcessAndExit(path, argv);
  if (path != NULL && Util::strStartsWith(path, lib64Prefix))
    execShortLivedProcessAndExit(path, argv);
  // Needed for /usr/libexec/utempter/utempter and other short-lived
  //  setuid/setgid processes.
  // FIXME:  USE THIS FOR ALL setuid/setgid PROCESSES EXCEPT ONES THAT
  //         WE DIRECTLY HANDLE, LIKE 'screen'.  (Need to name special routine,
  //         execScreenProcess() ??)
  if (path != NULL && Util::strEndsWith(path, "/utempter")) {
    JLOG(DMTCP)("Trying to exec: utempter")(path)(argv[0])(argv[1]);
    int oldIdx = -1;
    char *oldStr = NULL;
    string realPtsNameStr;
    // utempter takes a pts slave name as an argument. Since we virtualize
    // ptys, the slave name points to a virtual slave name, thus we need to
    // replace it with the real one.
    for (size_t i = 0; argv[i] != NULL; i++) {
      if (Util::strStartsWith(argv[i], VIRT_PTS_PREFIX_STR)) {
        // FIXME: Potential memory leak if exec() fails.
        char *realPtsNameStr = (char*)JALLOC_HELPER_MALLOC(PTS_PATH_MAX);
        oldStr = argv[i];
        oldIdx = i;
        SharedData::getRealPtyName(argv[i], realPtsNameStr,
                                          PTS_PATH_MAX);
        // Override const restriction
        *(const char**)&argv[i] = realPtsNameStr;
      }
    }
    execShortLivedProcessAndExit(path, argv);
    if (oldIdx != -1) {
      // Restore original argv[] if exec failed.
      *(const char**)&argv[oldIdx] = oldStr;
    }
  }

  // FIXME:  SEE COMMENTS IN dmtcp_launch.cpp, rev. 1087; AND CHANGE THIS.
  if (path != NULL && Util::isSetuid(path)) {
    if (Util::isScreen(path)) {
      Util::setScreenDir();
    }
    // THIS NEXT LINE IS DANGEROUS.  MOST setuid PROGRAMS CAN'T RUN UNPRIVILEGED
    Util::patchArgvIfSetuid(path, argv, newArgv);
    // BUG:  Util::patchArgvIfSetuid() DOES NOT SET newArgv WHEN COPYING
    //   BINARY IN CODE RE-FACTORING FROM REVISION 911.
    *filename = (*newArgv)[0];
  } else {
    *filename = (char*)path;
    *newArgv = (char**)argv;
  }

  ostringstream os;
  os << dmtcp_get_tmpdir() << "/dmtcpLifeBoat." << UniquePid::ThisProcess()
     << "-XXXXXX";
  char *buf = (char*) JALLOC_HELPER_MALLOC(os.str().length()+1);
  strcpy(buf, os.str().c_str());
  int fd = _real_mkstemp(buf);
  JASSERT(fd != -1) (JASSERT_ERRNO);
  JASSERT(unlink(buf) == 0) (JASSERT_ERRNO);
  Util::changeFd(fd, PROTECTED_LIFEBOAT_FD);
  jalib::JBinarySerializeWriterRaw wr ("", PROTECTED_LIFEBOAT_FD);
  UniquePid::serialize (wr);
  DmtcpEventData_t edata;
  edata.serializerInfo.fd = PROTECTED_LIFEBOAT_FD;
  DmtcpWorker::eventHook(DMTCP_EVENT_PRE_EXEC, &edata);

  JLOG(DMTCP)("Will exec filename instead of path") (path) (*filename);

  Util::adjustRlimitStack();
  Util::prepareDlsymWrapper();
  Util::setProtectedFdBase();

  // Remove FD_CLOEXEC flag from protected file descriptors.
  for (int i  = PROTECTED_FD_START; i < PROTECTED_FD_END; i++) {
    int flags = fcntl(i, F_GETFD, NULL);
    if (flags != -1) {
      fcntl(i, F_SETFD, flags & ~FD_CLOEXEC);
    }
  }
  JLOG(DMTCP)("Prepared for Exec") (getenv("LD_PRELOAD"));
}

static void dmtcpProcessFailedExec(const char *path, char *newArgv[])
{
  int saved_errno = errno;

  if (Util::isSetuid(path)) {
    Util::freePatchedArgv(newArgv);
  }

  restoreUserLDPRELOAD();

  unsetenv(ENV_VAR_DLSYM_OFFSET);
  unsetenv(ENV_VAR_DLSYM_OFFSET_M32);

  JLOG(DMTCP)("Processed failed Exec Attempt") (path) (getenv("LD_PRELOAD"));
  errno = saved_errno;
  JASSERT(_real_close(PROTECTED_LIFEBOAT_FD) == 0) (JASSERT_ERRNO);
}

static string getUpdatedLdPreload(const char* filename,
                                  const char* currLdPreload)
{
  string preload = getenv(ENV_VAR_HIJACK_LIBS);

  bool isElf = false;
  bool is32bitElf = false;
  if (getenv(ENV_VAR_HIJACK_LIBS_M32) != NULL &&
      Util::elfType(filename, &isElf, &is32bitElf) != -1 &&
      isElf &&
      is32bitElf) {
    preload = getenv(ENV_VAR_HIJACK_LIBS_M32);
  }

  vector<string> pluginLibraries = Util::tokenizeString(preload, ":");
  for (size_t i = 0; i < pluginLibraries.size(); i++) {
    // If the plugin doesn't exist, try to search it in the current install
    // directory.
    if (!jalib::Filesystem::FileExists(pluginLibraries[i])) {
      pluginLibraries[i] =
        Util::getPath(jalib::Filesystem::BaseName(pluginLibraries[i]),
                                                  is32bitElf);
    }
  }

  const char *preloadEnv = getenv("LD_PRELOAD");
  if (currLdPreload != NULL && strlen(currLdPreload) > 0) {
    pluginLibraries.push_back(currLdPreload);
    setenv(ENV_VAR_ORIG_LD_PRELOAD, currLdPreload, 1);
  } else if (preloadEnv != NULL && strlen(preloadEnv) > 0) {
    pluginLibraries.push_back(preloadEnv);
    setenv(ENV_VAR_ORIG_LD_PRELOAD, preloadEnv, 1);
  }

  string newPreload = Util::joinStrings(pluginLibraries, ":");
  return newPreload;
}

static vector<string> copyEnv(char *const envp[])
{
  vector<string> result;
  if (envp) {
    for (size_t i = 0; envp[i] != NULL; i++) {
      result.push_back(envp[i]);
    }
  }
  return result;
}

static vector<const char*> stringVectorToPointerArray(const vector<string>& s)
{
  vector<const char*> result;
  // Now get the pointers.
  for (size_t i = 0; i < s.size(); i++) {
    result.push_back(s[i].c_str());
  }
  result.push_back(NULL);
  return result;
}

static const char* ourImportantEnvs[] =
{
  ENV_VARS_ALL //expands to a long list
};
#define ourImportantEnvsCnt ((sizeof(ourImportantEnvs))/(sizeof(const char*)))

static bool isImportantEnv (string str)
{
  str = str.substr(0, str.find("="));

  for (size_t i=0; i<ourImportantEnvsCnt; ++i) {
    if (str == ourImportantEnvs[i])
      return true;
  }
  return false;
}

static vector<string> patchUserEnv (vector<string> env, const char* filename)
{
  vector<string> result;
  string userPreloadStr;

  ostringstream out;
  out << "non-DMTCP env vars:\n";

  for (size_t i = 0; i < env.size(); i++) {
    if (isImportantEnv (env[i])) {
      if (dbg) {
        out << "     skipping: " << env[i] << '\n';
      }
      continue;
    }
    if (Util::strStartsWith(env[i], "LD_PRELOAD=")) {
      userPreloadStr = env[i].substr(strlen("LD_PRELOAD="));
      continue;
    }

    result.push_back(env[i]);
    if (dbg) {
      out << "     addenv[user]:" << result.back() << '\n';
    }
  }
  JLOG(DMTCP)("Creating a copy of (non-DMTCP) user env vars...") (out.str());

  //pack up our ENV into the new ENV
  out.str("DMTCP env vars:\n");
  for (size_t i=0; i<ourImportantEnvsCnt; ++i) {
    const char* v = getenv(ourImportantEnvs[i]);
    const string e = ourImportantEnvs[i];
    if (e == ENV_VAR_ORIG_LD_PRELOAD && !userPreloadStr.empty()) {
      result.push_back(e + "=" + userPreloadStr);
    } else if (v != NULL) {
      result.push_back (e + '=' + v);
      if (dbg) {
        out << "     addenv[dmtcp]:" << result.back() << '\n';
      }
    }
  }

  string ldPreloadStr = "LD_PRELOAD=";
  ldPreloadStr += getUpdatedLdPreload(filename, userPreloadStr.c_str());

  result.push_back(ldPreloadStr);

  /*
   * The path virtualization plugin tries to set the new prefix env var on
   * restart. However, for some applications (e.g. bash), setenv() won't affect
   * the envp area, possibly because the application has its private copy of
   * the env vars. We need to patch the right env vars before calling execve().
   * */
  if (getenv("DMTCP_NEW_PATH_PREFIX")) {
    string pathVirt = "DMTCP_NEW_PATH_PREFIX=";
    pathVirt += getenv("DMTCP_NEW_PATH_PREFIX");
    result.push_back(pathVirt);
  }

  if (dbg) {
    out << "     addenv[dmtcp]:" << result.back() << '\n';
  }

  JLOG(DMTCP)("Patched user envp...")  (out.str());

  return result;
}

extern "C" int execve (const char *filename, char *const argv[],
                        char *const envp[])
{

  if (isPerformingCkptRestart() || isBlacklistedProgram(filename) ) {
    return _real_execve(filename, argv, envp);
  }
  JLOG(DMTCP)("execve() wrapper") (filename);

  /* Acquire the wrapperExeution lock to prevent checkpoint to happen while
   * processing this system call.
   */
  WRAPPER_EXECUTION_GET_EXCL_LOCK();

  const vector<string> env = copyEnv(envp);

  char *newFilename;
  char **newArgv;
  dmtcpPrepareForExec(filename, argv, &newFilename, &newArgv);

  const vector<string> envStrings = patchUserEnv(env, filename);
  const vector<const char*> newEnv = stringVectorToPointerArray(envStrings);

  int retVal = _real_execve (newFilename, newArgv, (char* const*)&newEnv[0]);

  dmtcpProcessFailedExec(filename, newArgv);

  WRAPPER_EXECUTION_RELEASE_EXCL_LOCK();

  return retVal;
}

extern "C" int execv (const char *path, char *const argv[])
{
  JLOG(DMTCP)("execv() wrapper, calling execve with environ") (path);

  // Make a copy of the environ coz it might change after a setenv().
  const vector<string> envStrings = copyEnv(environ);
  // Now get the pointers.
  const vector<const char*> env = stringVectorToPointerArray(envStrings);

  return execve(path, argv, (char* const*) &env[0]);
}

extern "C" int execvp (const char *filename, char *const argv[])
{
  if (isPerformingCkptRestart() || isBlacklistedProgram(filename) ) {
    return _real_execvp(filename, argv);
  }
  JLOG(DMTCP)("execvp() wrapper") (filename);
  /* Acquire the wrapperExeution lock to prevent checkpoint to happen while
   * processing this system call.
   */
  WRAPPER_EXECUTION_GET_EXCL_LOCK();

  char *newFilename;
  char **newArgv;
  dmtcpPrepareForExec(filename, argv, &newFilename, &newArgv);
  setenv("LD_PRELOAD", getUpdatedLdPreload(filename, NULL).c_str(), 1);

  int retVal = _real_execvp (newFilename, newArgv);

  dmtcpProcessFailedExec(filename, newArgv);

  WRAPPER_EXECUTION_RELEASE_EXCL_LOCK();

  return retVal;
}

// This function first appeared in glibc 2.11
extern "C" int execvpe (const char *filename, char *const argv[],
                         char *const envp[])
{
  if (isPerformingCkptRestart() || isBlacklistedProgram(filename)) {
    return _real_execvpe(filename, argv, envp);
  }
  JLOG(DMTCP)("execvpe() wrapper") (filename);
  /* Acquire the wrapperExeution lock to prevent checkpoint to happen while
   * processing this system call.
   */
  WRAPPER_EXECUTION_GET_EXCL_LOCK();

  // Make a copy of the environ coz it might change after a setenv().
  const vector<string> env = copyEnv(envp);

  char *newFilename;
  char **newArgv;
  dmtcpPrepareForExec(filename, argv, &newFilename, &newArgv);

  const vector<string> newEnvStrings = patchUserEnv(env, filename);
  const vector<const char*> newEnv = stringVectorToPointerArray(newEnvStrings);

  int retVal = _real_execvpe(newFilename, newArgv, (char* const*)&newEnv[0]);

  dmtcpProcessFailedExec(filename, newArgv);

  WRAPPER_EXECUTION_RELEASE_EXCL_LOCK();

  return retVal;
}

extern "C" int fexecve (int fd, char *const argv[], char *const envp[])
{
  char buf[sizeof "/proc/self/fd/" + sizeof (int) * 3];
  snprintf (buf, sizeof (buf), "/proc/self/fd/%d", fd);

  JLOG(DMTCP)("fexecve() wrapper calling execve()") (fd) (buf);
  return execve(buf, argv, envp);
}


extern "C" int execl (const char *path, const char *arg, ...)
{
  JLOG(DMTCP)("execl() wrapper") (path);

  size_t argv_max = INITIAL_ARGV_MAX;
  const char *initial_argv[INITIAL_ARGV_MAX];
  const char **argv = initial_argv;
  va_list args;

  argv[0] = arg;

  va_start (args, arg);
  unsigned int i = 0;
  while (argv[i++] != NULL)
  {
    if (i == argv_max)
    {
      argv_max *= 2;
      const char **nptr = (const char**) realloc (argv == initial_argv ? NULL : argv,
          argv_max * sizeof (const char *));
      if (nptr == NULL)
      {
        if (argv != initial_argv)
          free (argv);
        va_end (args);
        return -1;
      }
      if (argv == initial_argv)
        /* We have to copy the already filled-in data ourselves.  */
        memcpy (nptr, argv, i * sizeof (const char *));

      argv = nptr;
    }

    argv[i] = va_arg (args, const char *);
  }
  va_end (args);

  int ret = execv (path, (char *const *) argv);
  if (argv != initial_argv)
    free (argv);

  return ret;
}


extern "C" int execlp (const char *file, const char *arg, ...)
{
  JLOG(DMTCP)("execlp() wrapper") (file);

  size_t argv_max = INITIAL_ARGV_MAX;
  const char *initial_argv[INITIAL_ARGV_MAX];
  const char **argv = initial_argv;
  va_list args;

  argv[0] = arg;

  va_start (args, arg);
  unsigned int i = 0;
  while (argv[i++] != NULL)
  {
    if (i == argv_max)
    {
      argv_max *= 2;
      const char **nptr = (const char**) realloc (argv == initial_argv ? NULL : argv,
          argv_max * sizeof (const char *));
      if (nptr == NULL)
      {
        if (argv != initial_argv)
          free (argv);
        va_end (args);
        return -1;
      }
      if (argv == initial_argv)
        /* We have to copy the already filled-in data ourselves.  */
        memcpy (nptr, argv, i * sizeof (const char *));

      argv = nptr;
    }

    argv[i] = va_arg (args, const char *);
  }
  va_end (args);

  int ret = execvp (file, (char *const *) argv);
  if (argv != initial_argv)
    free (argv);

  return ret;
}


extern "C" int execle(const char *path, const char *arg, ...)
{
  JLOG(DMTCP)("execle() wrapper") (path);

  size_t argv_max = INITIAL_ARGV_MAX;
  const char *initial_argv[INITIAL_ARGV_MAX];
  const char **argv = initial_argv;
  va_list args;
  argv[0] = arg;

  va_start (args, arg);
  unsigned int i = 0;
  while (argv[i++] != NULL)
  {
    if (i == argv_max)
    {
      argv_max *= 2;
      const char **nptr = (const char**) realloc (argv == initial_argv ? NULL : argv,
          argv_max * sizeof (const char *));
      if (nptr == NULL)
      {
        if (argv != initial_argv)
          free (argv);
        va_end (args);
        return -1;
      }
      if (argv == initial_argv)
        /* We have to copy the already filled-in data ourselves.  */
        memcpy (nptr, argv, i * sizeof (const char *));

      argv = nptr;
    }

    argv[i] = va_arg (args, const char *);
  }

  const char *const *envp = va_arg (args, const char *const *);
  va_end (args);

  int ret = execve (path, (char *const *) argv, (char *const *) envp);
  if (argv != initial_argv)
    free (argv);

  return ret;
}

// See comment in glibcsystem.cpp for why this exists and how it works.
extern int do_system (const char *line);

extern "C" int system (const char *line)
{
  JLOG(DMTCP)("before system(), checkpointing may not work")
    (line) (getenv (ENV_VAR_HIJACK_LIBS)) (getenv ("LD_PRELOAD"));

  if (line == NULL)
    /* Check that we have a command processor available.  It might
       not be available after a chroot(), for example.  */
    return do_system ("exit 0") == 0;

  int result = do_system (line);

  JLOG(DMTCP)("after system()");

  return result;
}