/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8                                :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2020 Justine Alexandra Roberts Tunney                              │
│                                                                              │
│ Permission to use, copy, modify, and/or distribute this software for         │
│ any purpose with or without fee is hereby granted, provided that the         │
│ above copyright notice and this permission notice appear in all copies.      │
│                                                                              │
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL                │
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED                │
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE             │
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL         │
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR        │
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER               │
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR             │
│ PERFORMANCE OF THIS SOFTWARE.                                                │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/assert.h"
#include "libc/calls/internal.h"
#include "libc/calls/struct/fd.internal.h"
#include "libc/calls/struct/sigset.internal.h"
#include "libc/calls/syscall-nt.internal.h"
#include "libc/errno.h"
#include "libc/intrin/kprintf.h"
#include "libc/mem/mem.h"
#include "libc/nt/enum/processaccess.h"
#include "libc/nt/enum/startf.h"
#include "libc/nt/errors.h"
#include "libc/nt/files.h"
#include "libc/nt/process.h"
#include "libc/nt/runtime.h"
#include "libc/nt/struct/processinformation.h"
#include "libc/nt/struct/startupinfo.h"
#include "libc/proc/describefds.internal.h"
#include "libc/proc/ntspawn.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/at.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/errfuns.h"
#include "libc/thread/posixthread.internal.h"
#include "libc/thread/thread.h"
#ifdef __x86_64__

textwindows int sys_execve_nt(const char *program, char *const argv[],
                              char *const envp[]) {

  // execve() needs to be @asyncsignalsafe
  sigset_t m = __sig_block();
  _pthread_lock();

  // new process should be a child of our parent
  int64_t hParentProcess;
  int ppid = sys_getppid_nt();
  if (!(hParentProcess = OpenProcess(
            kNtProcessDupHandle | kNtProcessCreateProcess, false, ppid))) {
    _pthread_unlock();
    __sig_unblock(m);
    return -1;
  }

  // define stdio handles for the spawned subprocess
  struct NtStartupInfo si = {
      .cb = sizeof(struct NtStartupInfo),
      .dwFlags = kNtStartfUsestdhandles,
  };
  for (int fd = 0; fd < 3; ++fd) {
    if (!__is_cloexec(g_fds.p + fd)) {
      si.stdiofds[fd] = g_fds.p[fd].handle;
    } else {
      si.stdiofds[fd] = -1;
    }
  }

  // pass serialized file descriptor table in environment
  char *fdspec;
  int64_t *lpExplicitHandles;
  uint32_t dwExplicitHandleCount;
  if (!(fdspec = __describe_fds(g_fds.p, g_fds.n, &si, hParentProcess,
                                &lpExplicitHandles, &dwExplicitHandleCount))) {
    CloseHandle(hParentProcess);
    _pthread_unlock();
    __sig_unblock(m);
    return -1;
  }

  // launch the process
  struct NtProcessInformation pi;
  int rc = ntspawn(AT_FDCWD, program, argv, envp, (char *[]){fdspec, 0}, 0, 0,
                   hParentProcess, lpExplicitHandles, dwExplicitHandleCount,
                   &si, &pi);
  __undescribe_fds(hParentProcess, lpExplicitHandles, dwExplicitHandleCount);
  if (rc == -1) {
    free(fdspec);
    CloseHandle(hParentProcess);
    _pthread_unlock();
    __sig_unblock(m);
    if (GetLastError() == kNtErrorSharingViolation) {
      return etxtbsy();
    } else {
      return -1;
    }
  }

  // give child to libc/proc/proc.c worker thread in parent
  int64_t handle;
  unassert(DuplicateHandle(GetCurrentProcess(), pi.hProcess, hParentProcess,
                           &handle, 0, false, kNtDuplicateSameAccess));
  unassert(!(handle & 0xFFFFFFFFFF000000));
  TerminateThisProcess(0x23000000u | handle);
}

#endif /* __x86_64__ */