- // TODO, execute directly instead of relying on cp
- const char* command1 [] = {
- "cp", "--reflink=auto", "--", executable_copy.c_str(), target_executable.c_str(),
- nullptr
- };
- const char* command2 [] = {
- "cp", "--", executable_copy.c_str(), target_executable.c_str(),
- nullptr
- };
- if (execute_command(command1) != 0 && execute_command(command2) != 0)
- xbt_die("copy failed");
+
+ int fdin = open(executable_copy.c_str(), O_RDONLY);
+ xbt_assert(fdin >= 0, "Cannot read from %s", executable_copy.c_str());
+ int fdout = open(target_executable.c_str(), O_CREAT | O_RDWR, S_IRWXU);
+ xbt_assert(fdout >= 0, "Cannot write into %s", target_executable.c_str());
+
+#if HAVE_SENDFILE
+ ssize_t sent_size = sendfile(fdout, fdin, NULL, fdin_size);
+ xbt_assert(sent_size == fdin_size,
+ "Error while copying %s: only %zd bytes copied instead of %ld (errno: %d -- %s)",
+ target_executable.c_str(), sent_size, fdin_size, errno, strerror(errno));
+#else
+ XBT_VERB("Copy %d bytes into %s", static_cast<int>(fdin_size), target_executable.c_str());
+ const int bufsize = 1024 * 1024 * 4;
+ char buf[bufsize];
+ while (int got = read(fdin, buf, bufsize)) {
+ if (got == -1) {
+ xbt_assert(errno == EINTR, "Cannot read from %s", executable_copy.c_str());
+ } else {
+ char* p = buf;
+ int todo = got;
+ while (int done = write(fdout, p, todo)) {
+ if (done == -1) {
+ xbt_assert(errno == EINTR, "Cannot write into %s", target_executable.c_str());
+ } else {
+ p += done;
+ todo -= done;
+ }
+ }
+ }
+ }
+#endif
+ close(fdin);
+ close(fdout);