/*-*- 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                              │
│                                                                              │
│ This program is free software; you can redistribute it and/or modify         │
│ it under the terms of the GNU General Public License as published by         │
│ the Free Software Foundation; version 2 of the License.                      │
│                                                                              │
│ This program 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             │
│ General Public License for more details.                                     │
│                                                                              │
│ You should have received a copy of the GNU General Public License            │
│ along with this program; if not, write to the Free Software                  │
│ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA                │
│ 02110-1301 USA                                                               │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/calls/hefty/internal.h"
#include "libc/calls/hefty/ntspawn.h"
#include "libc/calls/internal.h"
#include "libc/nt/enum/startf.h"
#include "libc/nt/runtime.h"
#include "libc/nt/struct/startupinfo.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/fileno.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/sock.h"

static textwindows int64_t passstdhand$nt(int fd) {
  if (g_fds.p[fd].kind != kFdEmpty &&
      !(g_fds.p[fd].flags &
        (g_fds.p[fd].kind == kFdSocket ? SOCK_CLOEXEC : O_CLOEXEC))) {
    return g_fds.p[fd].handle;
  } else {
    return -1;
  }
}

textwindows int execve$nt(const char *program, char *const argv[],
                          char *const envp[]) {
  struct NtStartupInfo startinfo;
  memset(&startinfo, 0, sizeof(startinfo));
  startinfo.cb = sizeof(struct NtStartupInfo);
  startinfo.dwFlags = kNtStartfUsestdhandles;
  startinfo.hStdInput = passstdhand$nt(STDIN_FILENO);
  startinfo.hStdOutput = passstdhand$nt(STDOUT_FILENO);
  startinfo.hStdError = passstdhand$nt(STDERR_FILENO);
  if (ntspawn(program, argv, envp, NULL, NULL, true, 0, NULL, &startinfo,
              NULL) != -1) {
    for (;;) TerminateProcess(GetCurrentProcess(), 0);
  }
  return -1;
}
