LCOV - code coverage report
Current view: top level - ext - lsp_server_process.c (source / functions) Coverage Total Hit
Test: Extension code coverage Lines: 66.0 % 282 186
Test Date: 2026-07-13 00:58:38 Functions: 88.5 % 26 23

            Line data    Source code
       1              : /*
       2              :   +----------------------------------------------------------------------+
       3              :   | LSParrot PHP LSP Extension                                           |
       4              :   +----------------------------------------------------------------------+
       5              :   | Copyright (c) LSParrot GitHub Organization                           |
       6              :   +----------------------------------------------------------------------+
       7              :   | This source file is subject to the 0BSD license that is              |
       8              :   | bundled with this package in the file LICENSE.                       |
       9              :   +----------------------------------------------------------------------+
      10              :   | Author: Go Kudo <zeriyoshi@gmail.com>                                |
      11              :   +----------------------------------------------------------------------+
      12              : */
      13              : 
      14              : #include "lsp_internal.h"
      15              : 
      16              : #if defined(_WIN32)
      17              : static LONG lsp_process_windows_pipe_counter = 0;
      18              : 
      19              : static inline void lsp_process_append_windows_quoted_arg(smart_str *line, const char *value)
      20              : {
      21              :         const char *p;
      22              :         size_t backslashes;
      23              : 
      24              :         smart_str_appendc(line, '"');
      25              :         backslashes = 0;
      26              :         for (p = value; *p; p++) {
      27              :                 if (*p == '\\') {
      28              :                         backslashes++;
      29              :                         continue;
      30              :                 }
      31              :                 if (*p == '"') {
      32              :                         while (backslashes > 0) {
      33              :                                 smart_str_appendl(line, "\\\\", sizeof("\\\\") - 1);
      34              :                                 backslashes--;
      35              :                         }
      36              :                         smart_str_appendl(line, "\\\"", sizeof("\\\"") - 1);
      37              :                         continue;
      38              :                 }
      39              :                 while (backslashes > 0) {
      40              :                         smart_str_appendc(line, '\\');
      41              :                         backslashes--;
      42              :                 }
      43              :                 smart_str_appendc(line, *p);
      44              :         }
      45              :         while (backslashes > 0) {
      46              :                 smart_str_appendl(line, "\\\\", sizeof("\\\\") - 1);
      47              :                 backslashes--;
      48              :         }
      49              :         smart_str_appendc(line, '"');
      50              : }
      51              : 
      52              : static inline zend_string *lsp_process_command_line(lsp_command *command)
      53              : {
      54              :         smart_str line = {0};
      55              :         uint32_t i;
      56              : 
      57              :         for (i = 0; i < command->count; i++) {
      58              :                 if (i > 0) {
      59              :                         smart_str_appendc(&line, ' ');
      60              :                 }
      61              : 
      62              :                 lsp_process_append_windows_quoted_arg(&line, command->argv[i]);
      63              :         }
      64              : 
      65              :         smart_str_0(&line);
      66              : 
      67              :         return line.s ? line.s : zend_empty_string;
      68              : }
      69              : #endif
      70              : 
      71              : #if !defined(_WIN32)
      72          180 : static inline bool lsp_process_pipe_pair(lsp_pipe_handle *read_pipe, lsp_pipe_handle *write_pipe)
      73              : {
      74              :         int fds[2];
      75              : 
      76          180 :         if (pipe(fds) != 0) {
      77            0 :                 *read_pipe = LSP_INVALID_PIPE_HANDLE;
      78            0 :                 *write_pipe = LSP_INVALID_PIPE_HANDLE;
      79              : 
      80            0 :                 return false;
      81              :         }
      82              : 
      83          180 :         *read_pipe = (lsp_pipe_handle) fds[0];
      84          180 :         *write_pipe = (lsp_pipe_handle) fds[1];
      85              : 
      86          180 :         return true;
      87              : }
      88              : 
      89          180 : static inline bool lsp_process_set_nonblock(lsp_pipe_handle pipe)
      90              : {
      91              :         int flags;
      92              : 
      93          180 :         if (!lsp_pipe_handle_valid(pipe)) {
      94            0 :                 return false;
      95              :         }
      96              : 
      97          180 :         flags = fcntl((int) pipe, F_GETFL, 0);
      98          180 :         if (flags < 0) {
      99            0 :                 return false;
     100              :         }
     101              : 
     102          180 :         return fcntl((int) pipe, F_SETFL, flags | O_NONBLOCK) == 0;
     103              : }
     104              : 
     105              : /* Parent-side pipe ends must not leak into later fork+exec children: an
     106              :  * unrelated child holding a stray write end delays EOF detection (a capture
     107              :  * then spins until its deadline), and a stray read end keeps buffers alive. */
     108          180 : static inline void lsp_process_set_cloexec(lsp_pipe_handle pipe)
     109              : {
     110              :         int flags;
     111              : 
     112          180 :         if (!lsp_pipe_handle_valid(pipe)) {
     113            0 :                 return;
     114              :         }
     115              : 
     116          180 :         flags = fcntl((int) pipe, F_GETFD, 0);
     117          180 :         if (flags >= 0) {
     118          180 :                 (void) fcntl((int) pipe, F_SETFD, flags | FD_CLOEXEC);
     119              :         }
     120              : }
     121              : 
     122          468 : static inline void lsp_process_child_dup2_or_exit(int source, int target)
     123              : {
     124          468 :         if (source == target) {
     125            0 :                 return;
     126              :         }
     127              : 
     128          468 :         if (dup2(source, target) < 0) {
     129            0 :                 _exit(127);
     130              :         }
     131              : }
     132              : 
     133          552 : static inline void lsp_process_child_close_fd(int fd)
     134              : {
     135          552 :         if (fd > STDERR_FILENO) {
     136          552 :                 close(fd);
     137              :         }
     138          552 : }
     139              : 
     140          156 : static inline void lsp_process_child_chdir_or_exit(zend_string *cwd)
     141              : {
     142          156 :         if (cwd && ZSTR_LEN(cwd) > 0 && chdir(ZSTR_VAL(cwd)) != 0) {
     143            0 :                 _exit(127);
     144              :         }
     145          156 : }
     146              : 
     147           60 : static inline bool lsp_process_fork_exec_piped(
     148              :         lsp_command *command,
     149              :         zend_string *cwd,
     150              :         lsp_pipe_handle input_read,
     151              :         lsp_pipe_handle input_write,
     152              :         lsp_pipe_handle output_read,
     153              :         lsp_pipe_handle output_write,
     154              :         lsp_pipe_handle error_read,
     155              :         lsp_pipe_handle error_write,
     156              :         lsp_process_id *process
     157              : )
     158              : {
     159              :         pid_t pid;
     160              : 
     161           60 :         pid = fork();
     162          120 :         if (pid < 0) {
     163            0 :                 return false;
     164              :         }
     165              : 
     166          120 :         if (pid == 0) {
     167           60 :                 lsp_process_child_dup2_or_exit((int) input_read, STDIN_FILENO);
     168           60 :                 lsp_process_child_dup2_or_exit((int) output_write, STDOUT_FILENO);
     169           60 :                 lsp_process_child_dup2_or_exit((int) error_write, STDERR_FILENO);
     170           60 :                 lsp_process_child_close_fd((int) input_read);
     171           60 :                 lsp_process_child_close_fd((int) input_write);
     172           60 :                 lsp_process_child_close_fd((int) output_read);
     173           60 :                 lsp_process_child_close_fd((int) output_write);
     174           60 :                 lsp_process_child_close_fd((int) error_read);
     175           60 :                 lsp_process_child_close_fd((int) error_write);
     176           60 :                 lsp_process_child_chdir_or_exit(cwd);
     177           60 :                 execvp(command->argv[0], command->argv);
     178           60 :                 _exit(127);
     179              :         }
     180              : 
     181           60 :         *process = pid;
     182              : 
     183           60 :         return true;
     184              : }
     185              : 
     186           96 : static inline bool lsp_process_fork_exec_to_file(lsp_command *command, zend_string *cwd, int input, int output, lsp_process_id *process)
     187              : {
     188              :         pid_t pid;
     189              : 
     190           96 :         pid = fork();
     191          192 :         if (pid < 0) {
     192            0 :                 return false;
     193              :         }
     194              : 
     195          192 :         if (pid == 0) {
     196           96 :                 lsp_process_child_dup2_or_exit(input, STDIN_FILENO);
     197           96 :                 lsp_process_child_dup2_or_exit(output, STDOUT_FILENO);
     198           96 :                 lsp_process_child_dup2_or_exit(output, STDERR_FILENO);
     199           96 :                 lsp_process_child_close_fd(input);
     200           96 :                 lsp_process_child_close_fd(output);
     201           96 :                 lsp_process_child_chdir_or_exit(cwd);
     202           96 :                 execvp(command->argv[0], command->argv);
     203           96 :                 _exit(127);
     204              :         }
     205              : 
     206           96 :         *process = pid;
     207              : 
     208           96 :         return true;
     209              : }
     210              : #endif
     211              : 
     212              : #if defined(_WIN32)
     213              : static inline void lsp_process_windows_add_handle(HANDLE *handles, DWORD *handle_count, HANDLE handle)
     214              : {
     215              :         DWORD i;
     216              : 
     217              :         if (!handle || handle == INVALID_HANDLE_VALUE) {
     218              :                 return;
     219              :         }
     220              : 
     221              :         for (i = 0; i < *handle_count; i++) {
     222              :                 if (handles[i] == handle) {
     223              :                         return;
     224              :                 }
     225              :         }
     226              : 
     227              :         handles[*handle_count] = handle;
     228              :         (*handle_count)++;
     229              : }
     230              : 
     231              : static inline bool lsp_process_windows_start(lsp_command *command, zend_string *cwd, HANDLE input, HANDLE output, HANDLE error, lsp_process_id *process)
     232              : {
     233              :         STARTUPINFOEXA startup;
     234              :         PROCESS_INFORMATION info;
     235              :         zend_string *line;
     236              :         char *command_line;
     237              :         HANDLE handles[3], stdin_handle, stdout_handle, stderr_handle;
     238              :         SIZE_T attribute_size;
     239              :         DWORD creation_flags, handle_count;
     240              :         BOOL attributes_initialized, ok;
     241              : 
     242              :         line = lsp_process_command_line(command);
     243              :         if (line == zend_empty_string) {
     244              :                 return false;
     245              :         }
     246              : 
     247              :         command_line = estrndup(ZSTR_VAL(line), ZSTR_LEN(line));
     248              :         memset(&startup, 0, sizeof(startup));
     249              :         memset(&info, 0, sizeof(info));
     250              :         startup.StartupInfo.cb = sizeof(startup);
     251              :         startup.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
     252              :         stdin_handle = input ? input : GetStdHandle(STD_INPUT_HANDLE);
     253              :         stdout_handle = output ? output : GetStdHandle(STD_OUTPUT_HANDLE);
     254              :         stderr_handle = error ? error : GetStdHandle(STD_ERROR_HANDLE);
     255              :         startup.StartupInfo.hStdInput = stdin_handle;
     256              :         startup.StartupInfo.hStdOutput = stdout_handle;
     257              :         startup.StartupInfo.hStdError = stderr_handle;
     258              :         handles[0] = NULL;
     259              :         handles[1] = NULL;
     260              :         handles[2] = NULL;
     261              :         handle_count = 0;
     262              :         lsp_process_windows_add_handle(handles, &handle_count, stdin_handle);
     263              :         lsp_process_windows_add_handle(handles, &handle_count, stdout_handle);
     264              :         lsp_process_windows_add_handle(handles, &handle_count, stderr_handle);
     265              :         creation_flags = CREATE_NO_WINDOW;
     266              :         attribute_size = 0;
     267              :         InitializeProcThreadAttributeList(NULL, 1, 0, &attribute_size);
     268              :         attributes_initialized = FALSE;
     269              :         if (attribute_size > 0 && handle_count > 0) {
     270              :                 startup.lpAttributeList = emalloc(attribute_size);
     271              :                 attributes_initialized = InitializeProcThreadAttributeList(startup.lpAttributeList, 1, 0, &attribute_size);
     272              :                 if (attributes_initialized &&
     273              :                         UpdateProcThreadAttribute(startup.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, handles, sizeof(HANDLE) * handle_count, NULL, NULL)
     274              :                 ) {
     275              :                         creation_flags |= EXTENDED_STARTUPINFO_PRESENT;
     276              :                 } else {
     277              :                         if (attributes_initialized) {
     278              :                                 DeleteProcThreadAttributeList(startup.lpAttributeList);
     279              :                         }
     280              :                         efree(startup.lpAttributeList);
     281              :                         startup.lpAttributeList = NULL;
     282              :                 }
     283              :         }
     284              :         ok = CreateProcessA(NULL, command_line, NULL, NULL, TRUE, creation_flags, NULL,
     285              :                 cwd && ZSTR_LEN(cwd) > 0 ? ZSTR_VAL(cwd) : NULL,
     286              :                 &startup.StartupInfo, &info
     287              :         );
     288              :         if (startup.lpAttributeList) {
     289              :                 DeleteProcThreadAttributeList(startup.lpAttributeList);
     290              :                 efree(startup.lpAttributeList);
     291              :         }
     292              :         efree(command_line);
     293              :         zend_string_release(line);
     294              :         if (!ok) {
     295              :                 return false;
     296              :         }
     297              : 
     298              :         CloseHandle(info.hThread);
     299              :         *process = (lsp_process_id) info.hProcess;
     300              : 
     301              :         return true;
     302              : }
     303              : 
     304              : static inline bool lsp_process_windows_create_pipe(HANDLE *read_pipe, HANDLE *write_pipe)
     305              : {
     306              :         SECURITY_ATTRIBUTES attributes;
     307              : 
     308              :         memset(&attributes, 0, sizeof(attributes));
     309              :         attributes.nLength = sizeof(attributes);
     310              :         attributes.bInheritHandle = TRUE;
     311              :         attributes.lpSecurityDescriptor = NULL;
     312              : 
     313              :         return CreatePipe(read_pipe, write_pipe, &attributes, 0) != 0;
     314              : }
     315              : 
     316              : static inline bool lsp_process_windows_create_input_pipe(HANDLE *read_pipe, HANDLE *write_pipe)
     317              : {
     318              :         SECURITY_ATTRIBUTES attributes;
     319              :         HANDLE input_read, input_write;
     320              :         LONG counter;
     321              :         char name[128];
     322              :         BOOL connected;
     323              : 
     324              :         memset(&attributes, 0, sizeof(attributes));
     325              :         attributes.nLength = sizeof(attributes);
     326              :         attributes.bInheritHandle = TRUE;
     327              :         attributes.lpSecurityDescriptor = NULL;
     328              :         counter = InterlockedIncrement(&lsp_process_windows_pipe_counter);
     329              :         snprintf(name, sizeof(name), "\\\\.\\pipe\\lsparrot-%lu-%lu-%ld", (unsigned long) GetCurrentProcessId(), (unsigned long) GetTickCount(), (long) counter);
     330              : 
     331              :         input_read = CreateNamedPipeA(
     332              :                 name,
     333              :                 PIPE_ACCESS_INBOUND,
     334              :                 PIPE_TYPE_BYTE | PIPE_WAIT,
     335              :                 1,
     336              :                 65536,
     337              :                 65536,
     338              :                 0,
     339              :                 &attributes
     340              :         );
     341              :         if (input_read == INVALID_HANDLE_VALUE) {
     342              :                 *read_pipe = NULL;
     343              :                 *write_pipe = NULL;
     344              : 
     345              :                 return false;
     346              :         }
     347              : 
     348              :         input_write = CreateFileA(
     349              :                 name,
     350              :                 GENERIC_WRITE,
     351              :                 0,
     352              :                 NULL,
     353              :                 OPEN_EXISTING,
     354              :                 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
     355              :                 NULL
     356              :         );
     357              :         if (input_write == INVALID_HANDLE_VALUE) {
     358              :                 CloseHandle(input_read);
     359              :                 *read_pipe = NULL;
     360              :                 *write_pipe = NULL;
     361              : 
     362              :                 return false;
     363              :         }
     364              : 
     365              :         connected = ConnectNamedPipe(input_read, NULL) ? TRUE : GetLastError() == ERROR_PIPE_CONNECTED;
     366              :         if (!connected) {
     367              :                 CloseHandle(input_read);
     368              :                 CloseHandle(input_write);
     369              :                 *read_pipe = NULL;
     370              :                 *write_pipe = NULL;
     371              : 
     372              :                 return false;
     373              :         }
     374              : 
     375              :         *read_pipe = input_read;
     376              :         *write_pipe = input_write;
     377              : 
     378              :         return true;
     379              : }
     380              : #endif
     381              : 
     382              : #if defined(_WIN32)
     383              : static inline bool lsp_process_windows_write_all_timeout(lsp_pipe_handle pipe, const char *data, size_t length, double timeout)
     384              : {
     385              :         OVERLAPPED overlapped;
     386              :         HANDLE event;
     387              :         DWORD n, error, wait_ms, wait_result;
     388              :         size_t written, chunk;
     389              :         double deadline, now, remaining;
     390              :         bool result;
     391              : 
     392              :         event = CreateEventA(NULL, TRUE, FALSE, NULL);
     393              :         if (!event) {
     394              :                 return false;
     395              :         }
     396              : 
     397              :         written = 0;
     398              :         result = true;
     399              :         deadline = lsp_now_seconds() + (timeout > 0.0 ? timeout : 1.0);
     400              :         while (written < length) {
     401              :                 now = lsp_now_seconds();
     402              :                 if (now >= deadline) {
     403              :                         result = false;
     404              :                         break;
     405              :                 }
     406              : 
     407              :                 remaining = deadline - now;
     408              :                 wait_ms = (DWORD) (remaining * 1000.0);
     409              :                 if (wait_ms == 0) {
     410              :                         wait_ms = 1;
     411              :                 }
     412              : 
     413              :                 chunk = length - written;
     414              :                 if (chunk > 65536u) {
     415              :                         chunk = 65536u;
     416              :                 }
     417              : 
     418              :                 memset(&overlapped, 0, sizeof(overlapped));
     419              :                 ResetEvent(event);
     420              :                 overlapped.hEvent = event;
     421              :                 n = 0;
     422              :                 if (!WriteFile((HANDLE) pipe, data + written, (DWORD) chunk, &n, &overlapped)) {
     423              :                         error = GetLastError();
     424              :                         if (error != ERROR_IO_PENDING) {
     425              :                                 result = false;
     426              :                                 break;
     427              :                         }
     428              : 
     429              :                         wait_result = WaitForSingleObject(event, wait_ms);
     430              :                         if (wait_result != WAIT_OBJECT_0) {
     431              :                                 CancelIo((HANDLE) pipe);
     432              :                                 GetOverlappedResult((HANDLE) pipe, &overlapped, &n, TRUE);
     433              :                                 result = false;
     434              :                                 break;
     435              :                         }
     436              : 
     437              :                         n = 0;
     438              :                         if (!GetOverlappedResult((HANDLE) pipe, &overlapped, &n, FALSE)) {
     439              :                                 result = false;
     440              :                                 break;
     441              :                         }
     442              :                 }
     443              : 
     444              :                 if (n == 0) {
     445              :                         result = false;
     446              :                         break;
     447              :                 }
     448              : 
     449              :                 written += (size_t) n;
     450              :         }
     451              : 
     452              :         CloseHandle(event);
     453              : 
     454              :         return result;
     455              : }
     456              : #endif
     457              : 
     458              : #if !defined(_WIN32)
     459            4 : static inline bool lsp_process_wait_pipe_writable(lsp_pipe_handle pipe, double deadline)
     460              : {
     461              :         fd_set write_fds;
     462              :         struct timeval timeout;
     463              :         double now, remaining;
     464              :         int fd, result;
     465              : 
     466            4 :         fd = (int) pipe;
     467              :         for (;;) {
     468            4 :                 now = lsp_now_seconds();
     469            4 :                 if (now >= deadline) {
     470            0 :                         return false;
     471              :                 }
     472              : 
     473            4 :                 remaining = deadline - now;
     474            4 :                 timeout.tv_sec = (long) remaining;
     475            4 :                 timeout.tv_usec = (long) ((remaining - (double) timeout.tv_sec) * 1000000.0);
     476            4 :                 if (timeout.tv_sec == 0 && timeout.tv_usec <= 0) {
     477            0 :                         timeout.tv_usec = 1000;
     478              :                 }
     479              : 
     480           68 :                 FD_ZERO(&write_fds);
     481            4 :                 FD_SET(fd, &write_fds);
     482            4 :                 result = select(fd + 1, NULL, &write_fds, NULL, &timeout);
     483            4 :                 if (result > 0) {
     484            0 :                         return true;
     485              :                 }
     486            4 :                 if (result == 0) {
     487            4 :                         return false;
     488              :                 }
     489            0 :                 if (errno != EINTR) {
     490            0 :                         return false;
     491              :                 }
     492              :         }
     493              : }
     494              : #endif
     495              : 
     496        15585 : extern double lsp_now_seconds(void)
     497              : {
     498              : #if defined(_WIN32)
     499              :         ULONGLONG ticks;
     500              : 
     501              :         ticks = GetTickCount64();
     502              : 
     503              :         return (double) ticks / 1000.0;
     504              : #elif LSP_HAVE_POSIX_PROCESS
     505              :         struct timeval tv;
     506              : 
     507        15585 :         gettimeofday(&tv, NULL);
     508              : 
     509        15585 :         return (double) tv.tv_sec + ((double) tv.tv_usec / 1000000.0);
     510              : #else
     511              :         return (double) time(NULL);
     512              : #endif
     513              : }
     514              : 
     515          456 : extern void lsp_pipe_close(lsp_pipe_handle *pipe)
     516              : {
     517          456 :         if (!pipe || !lsp_pipe_handle_valid(*pipe)) {
     518           96 :                 return;
     519              :         }
     520              : 
     521              : #if defined(_WIN32)
     522              :         CloseHandle((HANDLE) *pipe);
     523              : #else
     524          360 :         close((int) *pipe);
     525              : #endif
     526          360 :         *pipe = LSP_INVALID_PIPE_HANDLE;
     527              : }
     528              : 
     529          396 : extern bool lsp_pipe_write_all_timeout(lsp_pipe_handle pipe, const char *data, size_t length, double timeout)
     530              : {
     531              : #if defined(_WIN32)
     532              :         return lsp_process_windows_write_all_timeout(pipe, data, length, timeout);
     533              : #else
     534              :         size_t written;
     535              :         ssize_t n;
     536              :         double deadline;
     537              : 
     538          396 :         written = 0;
     539          396 :         deadline = lsp_now_seconds() + (timeout > 0.0 ? timeout : 1.0);
     540          792 :         while (written < length) {
     541          400 :                 n = write((int) pipe, data + written, length - written);
     542          400 :                 if (n > 0) {
     543          396 :                         written += (size_t) n;
     544          396 :                         continue;
     545              :                 }
     546            4 :                 if (n == 0) {
     547            0 :                         if (!lsp_process_wait_pipe_writable(pipe, deadline)) {
     548            0 :                                 return false;
     549              :                         }
     550            0 :                         continue;
     551              :                 }
     552            4 :                 if (errno == EINTR) {
     553            0 :                         continue;
     554              :                 }
     555            4 :                 if (errno == EAGAIN || errno == EWOULDBLOCK) {
     556            4 :                         if (!lsp_process_wait_pipe_writable(pipe, deadline)) {
     557            4 :                                 return false;
     558              :                         }
     559            0 :                         continue;
     560              :                 }
     561              : 
     562            0 :                 return false;
     563              :         }
     564              : 
     565          392 :         return true;
     566              : #endif
     567              : }
     568              : 
     569         1938 : extern bool lsp_pipe_read_available(lsp_pipe_handle pipe, smart_str *output, bool *closed)
     570              : {
     571              :         char buffer[4096];
     572              : #if defined(_WIN32)
     573              :         DWORD available, n, wanted;
     574              : #else
     575              :         ssize_t n;
     576              : #endif
     577              : 
     578         1938 :         *closed = false;
     579         1938 :         if (!lsp_pipe_handle_valid(pipe)) {
     580            0 :                 *closed = true;
     581              : 
     582            0 :                 return true;
     583              :         }
     584              : 
     585              : #if defined(_WIN32)
     586              :         for (;;) {
     587              :                 available = 0;
     588              :                 if (!PeekNamedPipe((HANDLE) pipe, NULL, 0, NULL, &available, NULL)) {
     589              :                         *closed = true;
     590              : 
     591              :                         return true;
     592              :                 }
     593              :                 if (available == 0) {
     594              :                         return true;
     595              :                 }
     596              : 
     597              :                 wanted = available < sizeof(buffer) ? available : (DWORD) sizeof(buffer);
     598              :                 n = 0;
     599              :                 if (!ReadFile((HANDLE) pipe, buffer, wanted, &n, NULL)) {
     600              :                         *closed = GetLastError() == ERROR_BROKEN_PIPE;
     601              : 
     602              :                         return *closed;
     603              :                 }
     604              :                 if (n == 0) {
     605              :                         *closed = true;
     606              : 
     607              :                         return true;
     608              :                 }
     609              :                 smart_str_appendl(output, buffer, (size_t) n);
     610              :         }
     611              : #else
     612              :         for (;;) {
     613         2054 :                 n = read((int) pipe, buffer, sizeof(buffer));
     614         2054 :                 if (n > 0) {
     615          116 :                         smart_str_appendl(output, buffer, (size_t) n);
     616          116 :                         continue;
     617              :                 }
     618         1938 :                 if (n == 0) {
     619            0 :                         *closed = true;
     620              : 
     621            0 :                         return true;
     622              :                 }
     623         1938 :                 if (errno == EINTR) {
     624            0 :                         continue;
     625              :                 }
     626         1938 :                 if (errno == EAGAIN || errno == EWOULDBLOCK) {
     627         1938 :                         return true;
     628              :                 }
     629              : 
     630            0 :                 *closed = true;
     631              : 
     632            0 :                 return false;
     633              :         }
     634              : #endif
     635              : }
     636              : 
     637           60 : extern bool lsp_process_spawn_piped(lsp_command *command, zend_string *cwd, lsp_process_pipes *pipes)
     638              : {
     639              : #if defined(_WIN32)
     640              :         HANDLE child_input_read, child_input_write, child_output_read, child_output_write, child_error_read, child_error_write;
     641              :         bool ok;
     642              : #else
     643              :         lsp_pipe_handle input_read, input_write, output_read, output_write, error_read, error_write;
     644              :         bool ok;
     645              : #endif
     646              : 
     647           60 :         memset(pipes, 0, sizeof(*pipes));
     648           60 :         pipes->process = LSP_INVALID_PROCESS_ID;
     649           60 :         pipes->input = LSP_INVALID_PIPE_HANDLE;
     650           60 :         pipes->output = LSP_INVALID_PIPE_HANDLE;
     651           60 :         pipes->error = LSP_INVALID_PIPE_HANDLE;
     652           60 :         if (!command->argv || command->count == 0) {
     653            0 :                 return false;
     654              :         }
     655              : 
     656              : #if defined(_WIN32)
     657              :         child_input_read = NULL;
     658              :         child_input_write = NULL;
     659              :         child_output_read = NULL;
     660              :         child_output_write = NULL;
     661              :         child_error_read = NULL;
     662              :         child_error_write = NULL;
     663              :         ok = lsp_process_windows_create_input_pipe(&child_input_read, &child_input_write) &&
     664              :                 lsp_process_windows_create_pipe(&child_output_read, &child_output_write) &&
     665              :                 lsp_process_windows_create_pipe(&child_error_read, &child_error_write)
     666              :         ;
     667              :         if (!ok) {
     668              :                 if (child_input_read) {
     669              :                         CloseHandle(child_input_read);
     670              :                 }
     671              :                 if (child_input_write) {
     672              :                         CloseHandle(child_input_write);
     673              :                 }
     674              :                 if (child_output_read) {
     675              :                         CloseHandle(child_output_read);
     676              :                 }
     677              :                 if (child_output_write) {
     678              :                         CloseHandle(child_output_write);
     679              :                 }
     680              :                 if (child_error_read) {
     681              :                         CloseHandle(child_error_read);
     682              :                 }
     683              :                 if (child_error_write) {
     684              :                         CloseHandle(child_error_write);
     685              :                 }
     686              : 
     687              :                 return false;
     688              :         }
     689              : 
     690              :         SetHandleInformation(child_input_write, HANDLE_FLAG_INHERIT, 0);
     691              :         SetHandleInformation(child_output_read, HANDLE_FLAG_INHERIT, 0);
     692              :         SetHandleInformation(child_error_read, HANDLE_FLAG_INHERIT, 0);
     693              :         if (!lsp_process_windows_start(command, cwd, child_input_read, child_output_write, child_error_write, &pipes->process)) {
     694              :                 CloseHandle(child_input_read);
     695              :                 CloseHandle(child_input_write);
     696              :                 CloseHandle(child_output_read);
     697              :                 CloseHandle(child_output_write);
     698              :                 CloseHandle(child_error_read);
     699              :                 CloseHandle(child_error_write);
     700              : 
     701              :                 return false;
     702              :         }
     703              : 
     704              :         CloseHandle(child_input_read);
     705              :         CloseHandle(child_output_write);
     706              :         CloseHandle(child_error_write);
     707              :         pipes->input = (lsp_pipe_handle) child_input_write;
     708              :         pipes->output = (lsp_pipe_handle) child_output_read;
     709              :         pipes->error = (lsp_pipe_handle) child_error_read;
     710              : 
     711              :         return true;
     712              : #else
     713           60 :         input_read = LSP_INVALID_PIPE_HANDLE;
     714           60 :         input_write = LSP_INVALID_PIPE_HANDLE;
     715           60 :         output_read = LSP_INVALID_PIPE_HANDLE;
     716           60 :         output_write = LSP_INVALID_PIPE_HANDLE;
     717           60 :         error_read = LSP_INVALID_PIPE_HANDLE;
     718           60 :         error_write = LSP_INVALID_PIPE_HANDLE;
     719           60 :         if (!lsp_process_pipe_pair(&input_read, &input_write) ||
     720           60 :                 !lsp_process_pipe_pair(&output_read, &output_write) ||
     721           60 :                 !lsp_process_pipe_pair(&error_read, &error_write)
     722              :         ) {
     723            0 :                 goto fail;
     724              :         }
     725              : 
     726           60 :         ok = lsp_process_fork_exec_piped(
     727              :                 command,
     728              :                 cwd,
     729              :                 input_read,
     730              :                 input_write,
     731              :                 output_read,
     732              :                 output_write,
     733              :                 error_read,
     734              :                 error_write,
     735              :                 &pipes->process
     736              :         );
     737           60 :         if (!ok) {
     738            0 :                 goto fail;
     739              :         }
     740              : 
     741           60 :         lsp_pipe_close(&input_read);
     742           60 :         lsp_pipe_close(&output_write);
     743           60 :         lsp_pipe_close(&error_write);
     744           60 :         lsp_process_set_nonblock(input_write);
     745           60 :         lsp_process_set_nonblock(output_read);
     746           60 :         lsp_process_set_nonblock(error_read);
     747           60 :         lsp_process_set_cloexec(input_write);
     748           60 :         lsp_process_set_cloexec(output_read);
     749           60 :         lsp_process_set_cloexec(error_read);
     750           60 :         pipes->input = input_write;
     751           60 :         pipes->output = output_read;
     752           60 :         pipes->error = error_read;
     753              : 
     754           60 :         return true;
     755              : 
     756            0 : fail:
     757            0 :         lsp_pipe_close(&input_read);
     758            0 :         lsp_pipe_close(&input_write);
     759            0 :         lsp_pipe_close(&output_read);
     760            0 :         lsp_pipe_close(&output_write);
     761            0 :         lsp_pipe_close(&error_read);
     762            0 :         lsp_pipe_close(&error_write);
     763            0 :         pipes->process = LSP_INVALID_PROCESS_ID;
     764              : 
     765            0 :         return false;
     766              : #endif
     767              : }
     768              : 
     769           96 : extern lsp_process_id lsp_process_spawn_to_file(lsp_command *command, zend_string *cwd, zend_string *output_file)
     770              : {
     771              : #if defined(_WIN32)
     772              :         SECURITY_ATTRIBUTES attributes;
     773              :         HANDLE file, input;
     774              :         lsp_process_id process;
     775              : #else
     776              :         lsp_process_id process;
     777              :         int input, output;
     778              : #endif
     779              : 
     780           96 :         if (!command->argv || command->count == 0) {
     781            0 :                 return LSP_INVALID_PROCESS_ID;
     782              :         }
     783              : 
     784              : #if defined(_WIN32)
     785              :         memset(&attributes, 0, sizeof(attributes));
     786              :         attributes.nLength = sizeof(attributes);
     787              :         attributes.bInheritHandle = TRUE;
     788              :         attributes.lpSecurityDescriptor = NULL;
     789              :         input = CreateFileA("NUL", GENERIC_READ, FILE_SHARE_READ, &attributes, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
     790              :         if (input == INVALID_HANDLE_VALUE) {
     791              :                 return LSP_INVALID_PROCESS_ID;
     792              :         }
     793              :         file = CreateFileA(ZSTR_VAL(output_file), GENERIC_WRITE, FILE_SHARE_READ, &attributes, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
     794              :         if (file == INVALID_HANDLE_VALUE) {
     795              :                 CloseHandle(input);
     796              : 
     797              :                 return LSP_INVALID_PROCESS_ID;
     798              :         }
     799              : 
     800              :         process = LSP_INVALID_PROCESS_ID;
     801              :         if (!lsp_process_windows_start(command, cwd, input, file, file, &process)) {
     802              :                 CloseHandle(input);
     803              :                 CloseHandle(file);
     804              : 
     805              :                 return LSP_INVALID_PROCESS_ID;
     806              :         }
     807              :         CloseHandle(input);
     808              :         CloseHandle(file);
     809              : 
     810              :         return process;
     811              : #else
     812           96 :         process = LSP_INVALID_PROCESS_ID;
     813           96 :         input = open("/dev/null", O_RDONLY);
     814           96 :         if (input < 0) {
     815            0 :                 return LSP_INVALID_PROCESS_ID;
     816              :         }
     817              : 
     818           96 :         output = open(ZSTR_VAL(output_file), O_WRONLY | O_CREAT | O_TRUNC, 0666);
     819           96 :         if (output < 0) {
     820            0 :                 close(input);
     821              : 
     822            0 :                 return LSP_INVALID_PROCESS_ID;
     823              :         }
     824              : 
     825           96 :         if (!lsp_process_fork_exec_to_file(command, cwd, input, output, &process)) {
     826            0 :                 process = LSP_INVALID_PROCESS_ID;
     827              :         }
     828           96 :         close(input);
     829           96 :         close(output);
     830              : 
     831           96 :         return process;
     832              : #endif
     833              : }
     834              : 
     835            0 : extern zend_string *lsp_process_run_capture(lsp_command *command, zend_string *cwd, double timeout)
     836              : {
     837            0 :         smart_str output = {0};
     838              :         lsp_process_pipes pipes;
     839              :         bool output_closed, error_closed, exited;
     840              :         int status;
     841              :         double deadline;
     842              : 
     843            0 :         if (!lsp_process_spawn_piped(command, cwd, &pipes)) {
     844            0 :                 return zend_empty_string;
     845              :         }
     846              : 
     847            0 :         lsp_pipe_close(&pipes.input);
     848            0 :         output_closed = false;
     849            0 :         error_closed = false;
     850            0 :         exited = false;
     851            0 :         deadline = lsp_now_seconds() + (timeout > 0.0 ? timeout : 30.0);
     852            0 :         while ((!output_closed || !error_closed) || !exited) {
     853            0 :                 if (!output_closed) {
     854            0 :                         lsp_pipe_read_available(pipes.output, &output, &output_closed);
     855              :                 }
     856            0 :                 if (!error_closed) {
     857            0 :                         lsp_pipe_read_available(pipes.error, &output, &error_closed);
     858              :                 }
     859            0 :                 if (!exited && lsp_process_wait_nonblocking(pipes.process, &status)) {
     860            0 :                         exited = true;
     861              :                 }
     862            0 :                 if ((output_closed && error_closed) && exited) {
     863            0 :                         break;
     864              :                 }
     865            0 :                 if (lsp_now_seconds() >= deadline) {
     866              :                         /* The pipes can outlive the child when a descendant inherited
     867              :                          * the write ends. Once the child has been reaped its pid may
     868              :                          * already belong to an unrelated process, so it must never be
     869              :                          * signalled again — just stop reading. */
     870            0 :                         if (!exited) {
     871            0 :                                 lsp_process_terminate(pipes.process);
     872            0 :                                 if (!lsp_process_wait_timeout(pipes.process, &status, 2.0)) {
     873            0 :                                         lsp_process_terminate_force(pipes.process);
     874            0 :                                         lsp_process_wait_timeout(pipes.process, &status, 2.0);
     875              :                                 }
     876              :                         }
     877            0 :                         break;
     878              :                 }
     879            0 :                 lsp_sleep_milliseconds(10);
     880              :         }
     881              : 
     882            0 :         lsp_pipe_close(&pipes.output);
     883            0 :         lsp_pipe_close(&pipes.error);
     884            0 :         lsp_process_close(pipes.process);
     885            0 :         if (!output.s) {
     886            0 :                 return zend_empty_string;
     887              :         }
     888              : 
     889            0 :         smart_str_0(&output);
     890              : 
     891            0 :         return output.s;
     892              : }
     893              : 
     894         4343 : extern bool lsp_process_wait_nonblocking(lsp_process_id process, int *status)
     895              : {
     896              : #if defined(_WIN32)
     897              :         DWORD result, exit_code;
     898              : #else
     899              :         lsp_process_id waited;
     900              :         int local_status;
     901              : #endif
     902              : 
     903         4343 :         if (!lsp_process_id_valid(process)) {
     904            0 :                 return true;
     905              :         }
     906              : 
     907              : #if defined(_WIN32)
     908              :         result = WaitForSingleObject((HANDLE) process, 0);
     909              :         if (result != WAIT_OBJECT_0) {
     910              :                 return false;
     911              :         }
     912              :         exit_code = 0;
     913              :         GetExitCodeProcess((HANDLE) process, &exit_code);
     914              :         if (status) {
     915              :                 *status = (int) exit_code;
     916              :         }
     917              : 
     918              :         return true;
     919              : #else
     920         4343 :         local_status = 0;
     921         4343 :         waited = waitpid(process, &local_status, WNOHANG);
     922         4343 :         if (waited == 0) {
     923         3611 :                 return false;
     924              :         }
     925          732 :         if (status) {
     926          732 :                 *status = local_status;
     927              :         }
     928              : 
     929          732 :         return waited == process || waited < 0;
     930              : #endif
     931              : }
     932              : 
     933          576 : extern bool lsp_process_wait_timeout(lsp_process_id process, int *status, double timeout)
     934              : {
     935              :         double deadline;
     936              : 
     937          576 :         if (!lsp_process_id_valid(process)) {
     938            0 :                 return true;
     939              :         }
     940              : 
     941          576 :         deadline = lsp_now_seconds() + (timeout > 0.0 ? timeout : 0.0);
     942              :         for (;;) {
     943         2074 :                 if (lsp_process_wait_nonblocking(process, status)) {
     944          568 :                         return true;
     945              :                 }
     946         1506 :                 if (timeout <= 0.0 || lsp_now_seconds() >= deadline) {
     947            8 :                         return false;
     948              :                 }
     949         1498 :                 lsp_sleep_milliseconds(10);
     950              :         }
     951              : }
     952              : 
     953            0 : extern void lsp_process_wait(lsp_process_id process, int *status)
     954              : {
     955              : #if defined(_WIN32)
     956              :         DWORD exit_code;
     957              : #else
     958              :         int local_status;
     959              : #endif
     960              : 
     961            0 :         if (!lsp_process_id_valid(process)) {
     962            0 :                 return;
     963              :         }
     964              : 
     965              : #if defined(_WIN32)
     966              :         WaitForSingleObject((HANDLE) process, INFINITE);
     967              :         exit_code = 0;
     968              :         GetExitCodeProcess((HANDLE) process, &exit_code);
     969              :         if (status) {
     970              :                 *status = (int) exit_code;
     971              :         }
     972              : #else
     973            0 :         local_status = 0;
     974            0 :         waitpid(process, &local_status, 0);
     975            0 :         if (status) {
     976            0 :                 *status = local_status;
     977              :         }
     978              : #endif
     979              : }
     980              : 
     981          208 : extern void lsp_process_terminate(lsp_process_id process)
     982              : {
     983          208 :         if (!lsp_process_id_valid(process)) {
     984            0 :                 return;
     985              :         }
     986              : 
     987              : #if defined(_WIN32)
     988              :         TerminateProcess((HANDLE) process, 1);
     989              : #else
     990          208 :         kill(process, SIGTERM);
     991              : #endif
     992              : }
     993              : 
     994            0 : extern void lsp_process_terminate_force(lsp_process_id process)
     995              : {
     996            0 :         if (!lsp_process_id_valid(process)) {
     997            0 :                 return;
     998              :         }
     999              : 
    1000              : #if defined(_WIN32)
    1001              :         TerminateProcess((HANDLE) process, 1);
    1002              : #else
    1003            0 :         kill(process, SIGKILL);
    1004              : #endif
    1005              : }
    1006              : 
    1007          156 : extern void lsp_process_close(lsp_process_id process)
    1008              : {
    1009          156 :         if (!lsp_process_id_valid(process)) {
    1010            0 :                 return;
    1011              :         }
    1012              : 
    1013              : #if defined(_WIN32)
    1014              :         CloseHandle((HANDLE) process);
    1015              : #else
    1016              :         (void) process;
    1017              : #endif
    1018              : }
    1019              : 
    1020              : /* ----------------------------------------------------------------------
    1021              :  * SIGTERM guard
    1022              :  *
    1023              :  * Editors commonly stop a language server with SIGTERM. Dying mid-way
    1024              :  * through a request or through teardown loses the on-disk index cache and
    1025              :  * leaves child processes to escalation timeouts, so while the server loop
    1026              :  * owns the process a SIGTERM only records a stop request: the loop exits
    1027              :  * gracefully at the next wakeup and teardown runs to completion even when
    1028              :  * the signal arrives during it. The previous disposition is restored when
    1029              :  * the server returns. SIGKILL remains available as the hard stop.
    1030              :  * ---------------------------------------------------------------------- */
    1031              : 
    1032              : static volatile sig_atomic_t lsp_terminate_requested_flag = 0;
    1033              : 
    1034              : #if !defined(_WIN32)
    1035              : static struct sigaction lsp_previous_sigterm_action;
    1036              : static bool lsp_sigterm_guard_active = false;
    1037              : 
    1038          142 : static void lsp_sigterm_guard_handler(int signo)
    1039              : {
    1040              :         (void) signo;
    1041          142 :         lsp_terminate_requested_flag = 1;
    1042          142 : }
    1043              : #endif
    1044              : 
    1045          548 : extern void lsp_terminate_guard_install(void)
    1046              : {
    1047              : #if !defined(_WIN32)
    1048              :         struct sigaction action;
    1049              : 
    1050          548 :         if (lsp_sigterm_guard_active) {
    1051            0 :                 return;
    1052              :         }
    1053              : 
    1054          548 :         memset(&action, 0, sizeof(action));
    1055          548 :         action.sa_handler = lsp_sigterm_guard_handler;
    1056          548 :         sigemptyset(&action.sa_mask);
    1057              :         /* No SA_RESTART: the signal must interrupt poll() so the loop notices
    1058              :          * the stop request promptly. */
    1059          548 :         action.sa_flags = 0;
    1060          548 :         if (sigaction(SIGTERM, &action, &lsp_previous_sigterm_action) == 0) {
    1061          548 :                 lsp_sigterm_guard_active = true;
    1062              :         }
    1063              : #endif
    1064          548 :         lsp_terminate_requested_flag = 0;
    1065              : }
    1066              : 
    1067          548 : extern void lsp_terminate_guard_restore(void)
    1068              : {
    1069              : #if !defined(_WIN32)
    1070          548 :         if (!lsp_sigterm_guard_active) {
    1071            0 :                 return;
    1072              :         }
    1073              : 
    1074          548 :         sigaction(SIGTERM, &lsp_previous_sigterm_action, NULL);
    1075          548 :         lsp_sigterm_guard_active = false;
    1076              : #endif
    1077              : }
    1078              : 
    1079         1418 : extern bool lsp_terminate_requested(void)
    1080              : {
    1081         1418 :         return lsp_terminate_requested_flag != 0;
    1082              : }
        

Generated by: LCOV version 2.0-1