main.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. #define WIN32_LEAN_AND_MEAN
  2. #define _WIN32_WINNT 0x0A00
  3. #include <windows.h>
  4. #include <cstdio>
  5. #include <cstring>
  6. #include <cwchar>
  7. #include <string>
  8. #include <vector>
  9. namespace {
  10. constexpr ULONGLONG kGraceMs = 1800;
  11. struct ExitDiagnostic {
  12. bool enabled = false, running = false, rootExited = false, forced = false, jobEmpty = false;
  13. DWORD hostPid = 0, runtimePid = 0, win32Error = 0;
  14. const char* reason = "none";
  15. const char* stage = "none";
  16. void failure(const char* value, DWORD code = GetLastError()) {
  17. if (std::strcmp(stage, "none") == 0) { stage = value; win32Error = code; }
  18. }
  19. ~ExitDiagnostic() {
  20. if (!enabled) return;
  21. // 管道断开与进程退出可能不同序;只输出首次决策和安全字段,不输出命令或任意正文。
  22. std::fprintf(stderr, "[windows-runtime-host:exit] {\"hostPid\":%lu,\"helperPid\":%lu,\"runtimePid\":%lu,\"reason\":\"%s\",\"stage\":\"%s\",\"win32Error\":%lu,\"running\":%s,\"rootExited\":%s,\"forced\":%s,\"jobEmpty\":%s}\n",
  23. hostPid, GetCurrentProcessId(), runtimePid, reason, stage, win32Error,
  24. running ? "true" : "false", rootExited ? "true" : "false", forced ? "true" : "false", jobEmpty ? "true" : "false");
  25. }
  26. } diagnostic;
  27. struct Handle {
  28. HANDLE value = nullptr;
  29. ~Handle() { if (value && value != INVALID_HANDLE_VALUE) CloseHandle(value); }
  30. };
  31. bool send(HANDLE pipe, const std::string& message) {
  32. const auto frame = message + "\n";
  33. DWORD count;
  34. const BOOL written = WriteFile(pipe, frame.data(), static_cast<DWORD>(frame.size()), &count, nullptr);
  35. if (!written || count != frame.size()) diagnostic.failure("control_write", written ? ERROR_WRITE_FAULT : GetLastError());
  36. return written && count == frame.size();
  37. }
  38. std::wstring quote(const std::wstring& arg) {
  39. std::wstring result = L"\"";
  40. size_t slashes = 0;
  41. for (const auto c : arg) {
  42. if (c == L'\\') { ++slashes; continue; }
  43. result.append(slashes * (c == L'"' ? 2 : 1), L'\\');
  44. slashes = 0;
  45. if (c == L'"') result += L'\\';
  46. result += c;
  47. }
  48. result.append(slashes * 2, L'\\');
  49. return result + L'"';
  50. }
  51. int fail(const char* stage) {
  52. diagnostic.enabled = true;
  53. diagnostic.failure(stage);
  54. return 1;
  55. }
  56. }
  57. int wmain(int argc, wchar_t** argv) {
  58. if (argc == 2 && std::wstring(argv[1]) == L"--version") {
  59. std::puts("zcode-runtime-host 1"); return 0;
  60. }
  61. if (argc == 3 && std::wstring(argv[1]) == L"--check-empty") {
  62. Handle previous{OpenJobObjectW(JOB_OBJECT_QUERY, FALSE, argv[2])};
  63. // 内核在最后一个句柄关闭且全部成员退出后销毁 Job;不存在是原 Job 已消失的事实。
  64. if (!previous.value) return GetLastError() == ERROR_FILE_NOT_FOUND ? 0 : fail("open_previous_job");
  65. JOBOBJECT_BASIC_ACCOUNTING_INFORMATION accounting{};
  66. if (!QueryInformationJobObject(previous.value, JobObjectBasicAccountingInformation, &accounting, sizeof(accounting), nullptr)) return fail("previous_job_membership");
  67. return accounting.ActiveProcesses == 0 ? 0 : 2;
  68. }
  69. if (argc < 5) return fail("arguments");
  70. diagnostic.enabled = true;
  71. const DWORD parentPid = wcstoul(argv[2], nullptr, 10);
  72. diagnostic.hostPid = parentPid;
  73. Handle parent{OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE, parentPid)};
  74. if (!parent.value) return fail("parent_handle");
  75. Handle control{CreateFileW(argv[1], GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr)};
  76. if (control.value == INVALID_HANDLE_VALUE) return fail("control_pipe");
  77. ULONG serverPid = 0;
  78. if (!GetNamedPipeServerProcessId(control.value, &serverPid) || serverPid != parentPid ||
  79. WaitForSingleObject(parent.value, 0) != WAIT_TIMEOUT) return fail("control_owner");
  80. Handle job{CreateJobObjectW(nullptr, argv[3])};
  81. if (!job.value || GetLastError() == ERROR_ALREADY_EXISTS) return fail("create_job");
  82. JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{};
  83. limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
  84. if (!SetInformationJobObject(job.value, JobObjectExtendedLimitInformation, &limits, sizeof(limits))) return fail("configure_job");
  85. // 原因:spawn 后再 attach 有派生窗口,退出后按 PPID 补查又可能误认复用的 PID。
  86. // 只传递三条 stdio,并通过创建属性加入 Job,避免 helper 在 create/assign 之间崩溃。
  87. // CLI 在 Host 接管前始终保持 suspended;不支持 Job 属性时明确拒绝启动。
  88. Handle input, output, error;
  89. HANDLE inherited[3];
  90. Handle* copies[] = {&input, &output, &error};
  91. const DWORD ids[] = {STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE};
  92. for (int i = 0; i < 3; ++i) {
  93. if (!DuplicateHandle(GetCurrentProcess(), GetStdHandle(ids[i]), GetCurrentProcess(),
  94. &copies[i]->value, 0, TRUE, DUPLICATE_SAME_ACCESS)) return fail("stdio_handles");
  95. inherited[i] = copies[i]->value;
  96. }
  97. SIZE_T size = 0;
  98. InitializeProcThreadAttributeList(nullptr, 2, 0, &size);
  99. std::vector<unsigned char> storage(size);
  100. auto attributes = reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
  101. if (!InitializeProcThreadAttributeList(attributes, 2, 0, &size)) return fail("handle_list");
  102. if (!UpdateProcThreadAttribute(attributes, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
  103. inherited, sizeof(inherited), nullptr, nullptr)) {
  104. diagnostic.failure("inherit_list");
  105. DeleteProcThreadAttributeList(attributes); return fail("inherit_list");
  106. }
  107. if (!UpdateProcThreadAttribute(attributes, 0, PROC_THREAD_ATTRIBUTE_JOB_LIST,
  108. &job.value, sizeof(job.value), nullptr, nullptr)) {
  109. diagnostic.failure("job_attribute");
  110. DeleteProcThreadAttributeList(attributes); return fail("job_attribute");
  111. }
  112. STARTUPINFOEXW si{};
  113. si.StartupInfo.cb = sizeof(si);
  114. si.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
  115. si.StartupInfo.hStdInput = input.value;
  116. si.StartupInfo.hStdOutput = output.value;
  117. si.StartupInfo.hStdError = error.value;
  118. si.lpAttributeList = attributes;
  119. std::wstring command;
  120. for (int i = 4; i < argc; ++i) {
  121. if (i > 4) command += L' ';
  122. command += quote(argv[i]);
  123. }
  124. PROCESS_INFORMATION pi{};
  125. const BOOL created = CreateProcessW(nullptr, command.data(), nullptr, nullptr, TRUE,
  126. CREATE_SUSPENDED | EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW,
  127. nullptr, nullptr, &si.StartupInfo, &pi);
  128. const DWORD createError = GetLastError();
  129. DeleteProcThreadAttributeList(attributes);
  130. if (!created) { SetLastError(createError); return fail("create_cli"); }
  131. Handle root{pi.hProcess}, primaryThread{pi.hThread};
  132. diagnostic.runtimePid = pi.dwProcessId;
  133. BOOL assigned = FALSE;
  134. if (!IsProcessInJob(root.value, job.value, &assigned) || !assigned) {
  135. diagnostic.failure("verify_job");
  136. TerminateProcess(root.value, 1);
  137. return fail("verify_job");
  138. }
  139. bool start = false, close = false, lost = false;
  140. std::string controlLine;
  141. bool& running = diagnostic.running;
  142. bool& rootExited = diagnostic.rootExited;
  143. bool& forced = diagnostic.forced;
  144. ULONGLONG closeAt = 0;
  145. const auto startupDeadline = GetTickCount64() + 10000;
  146. if (!send(control.value, "ready " + std::to_string(pi.dwProcessId))) lost = true;
  147. int result = 0;
  148. for (;;) {
  149. DWORD available = 0;
  150. if (!lost && !PeekNamedPipe(control.value, nullptr, 0, nullptr, &available, nullptr)) {
  151. diagnostic.failure("control_peek"); lost = true;
  152. }
  153. while (!lost && available-- > 0) {
  154. char c; DWORD count;
  155. const BOOL read = ReadFile(control.value, &c, 1, &count, nullptr);
  156. if (!read || count != 1) {
  157. diagnostic.failure("control_read", read ? ERROR_BROKEN_PIPE : GetLastError()); lost = true; break;
  158. }
  159. if (c == '\n') {
  160. if (controlLine == "start") start = true;
  161. else if (controlLine == "close") close = true;
  162. else { diagnostic.failure("control_frame", ERROR_INVALID_DATA); lost = true; }
  163. controlLine.clear();
  164. } else if (controlLine.size() < 32) controlLine += c;
  165. else { diagnostic.failure("control_frame", ERROR_INVALID_DATA); lost = true; }
  166. }
  167. const auto now = GetTickCount64();
  168. const bool abandoned = lost || WaitForSingleObject(parent.value, 0) == WAIT_OBJECT_0;
  169. if (!running && start && !close && !abandoned) {
  170. if (ResumeThread(primaryThread.value) == static_cast<DWORD>(-1)) { result = fail("resume_cli"); break; }
  171. running = true;
  172. if (!send(control.value, "started")) lost = true;
  173. }
  174. if (!rootExited && WaitForSingleObject(root.value, 0) == WAIT_OBJECT_0) {
  175. rootExited = true;
  176. DWORD code;
  177. if (!GetExitCodeProcess(root.value, &code)) { result = fail("root_exit_status"); break; }
  178. if (!lost && !send(control.value, "root " + std::to_string(code))) lost = true;
  179. }
  180. if (close && closeAt == 0) closeAt = now;
  181. // 根退出表示它已完成自身收尾;残余成员仍归 Job,不能因根 PID 消失释放所有权。
  182. const bool mustTerminate = abandoned || rootExited || (!running && (close || now >= startupDeadline)) ||
  183. (closeAt != 0 && now - closeAt >= kGraceMs);
  184. if (mustTerminate && !forced) {
  185. // 只在原有终止决策处固定首次原因,后续 root/管道事件不得覆盖它。
  186. diagnostic.reason = abandoned ? (lost ? "control_lost" : "parent_exited") :
  187. rootExited ? "root_exited" : !running ? (close ? "start_cancelled" : "start_timeout") : "close_grace_elapsed";
  188. if (!TerminateJobObject(job.value, 1)) { result = fail("terminate_job"); break; }
  189. forced = true;
  190. }
  191. if (rootExited) {
  192. JOBOBJECT_BASIC_ACCOUNTING_INFORMATION accounting{};
  193. if (!QueryInformationJobObject(job.value, JobObjectBasicAccountingInformation, &accounting, sizeof(accounting), nullptr)) {
  194. result = fail("query_job"); break;
  195. }
  196. if (accounting.ActiveProcesses == 0 && rootExited) {
  197. diagnostic.jobEmpty = true;
  198. if (!lost) send(control.value, "empty");
  199. break;
  200. }
  201. }
  202. // 等待句柄事件;短轮询只复核内核 Job 计数,不枚举系统进程,也不把超时当清空。
  203. HANDLE waits[] = {parent.value, root.value};
  204. if (abandoned) Sleep(50);
  205. else WaitForMultipleObjects(rootExited ? 1 : 2, waits, FALSE, 50);
  206. }
  207. // 异常退出仍由最后一个 Job 句柄负责强制回收。
  208. return result;
  209. }