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 : /* Resident analyzer runner: one long-lived PHP process per (analyzer,
17 : * project root) that executes per-file analysis and type-query commands on
18 : * behalf of the LSP server. The runner pre-requires the project's Composer
19 : * autoloader and, when ext-pcntl is available, executes PHP CLI analyzers
20 : * via fork+include so the booted engine (and opcache CLI file cache, which
21 : * the runner enables) is reused instead of paying a full interpreter and
22 : * bootstrap start per request. Non-PHP analyzer entry points (and platforms
23 : * without fork) transparently fall back to proc_open inside the runner, and
24 : * any runner failure falls back to a direct one-shot process spawn. */
25 :
26 : static const char lsp_runner_script_source[] =
27 : "<?php\n"
28 : "error_reporting(E_ERROR | E_PARSE);\n"
29 : "$in = fopen('php://stdin', 'rb');\n"
30 : "$projectRoot = realpath((string) ($argv[1] ?? ''));\n"
31 : "if (!is_string($projectRoot) || $projectRoot === '') { exit(1); }\n"
32 : "$analyzer = (string) ($argv[2] ?? '');\n"
33 : "$autoload = (string) ($argv[3] ?? '');\n"
34 : "function lsp_runner_path_is_same_or_under(string $path, string $root): bool {\n"
35 : " $path = rtrim(str_replace('\\\\', '/', $path), '/');\n"
36 : " $root = rtrim(str_replace('\\\\', '/', $root), '/');\n"
37 : " if (DIRECTORY_SEPARATOR === '\\\\') { $path = strtolower($path); $root = strtolower($root); }\n"
38 : " return $path === $root || strncmp($path, $root . '/', strlen($root) + 1) === 0;\n"
39 : "}\n"
40 : "function lsp_runner_real_project_file(string $path, string $projectRoot): ?string {\n"
41 : " if ($path === '' || str_contains($path, \"\\0\")) { return null; }\n"
42 : " $real = realpath($path);\n"
43 : " if (!is_string($real) || !is_file($real) || !lsp_runner_path_is_same_or_under($real, $projectRoot)) { return null; }\n"
44 : " return $real;\n"
45 : "}\n"
46 : "function lsp_runner_real_project_dir(string $path, string $projectRoot): ?string {\n"
47 : " if ($path === '' || str_contains($path, \"\\0\")) { return $projectRoot; }\n"
48 : " $real = realpath($path);\n"
49 : " if (!is_string($real) || !is_dir($real) || !lsp_runner_path_is_same_or_under($real, $projectRoot)) { return null; }\n"
50 : " return $real;\n"
51 : "}\n"
52 : "function lsp_runner_analyzer_basename_allowed(string $target, string $analyzer): bool {\n"
53 : " $name = basename($target);\n"
54 : " if (DIRECTORY_SEPARATOR === '\\\\') { $name = strtolower($name); }\n"
55 : " if ($analyzer === 'phpstan') { return $name === 'phpstan' || $name === 'phpstan.bat' || $name === 'phpstan.cmd'; }\n"
56 : " if ($analyzer === 'psalm') { return $name === 'psalm' || $name === 'psalm.bat' || $name === 'psalm.cmd'; }\n"
57 : " return false;\n"
58 : "}\n"
59 : "function lsp_runner_php_binary_name(string $path): bool {\n"
60 : " return preg_match('/^php(?:[0-9.]+)?(?:\\\\.exe)?$/i', basename($path)) === 1;\n"
61 : "}\n"
62 : "function lsp_runner_command_target(array $argvList, string $projectRoot, string $analyzer): ?array {\n"
63 : " if (!isset($argvList[0]) || !is_string($argvList[0])) { return null; }\n"
64 : " $targetIndex = 0;\n"
65 : " if (lsp_runner_php_binary_name($argvList[0])) {\n"
66 : " $targetIndex = -1;\n"
67 : " foreach ($argvList as $index => $arg) {\n"
68 : " if ($index === 0 || !is_string($arg)) { continue; }\n"
69 : " $real = lsp_runner_real_project_file($arg, $projectRoot);\n"
70 : " if ($real !== null && lsp_runner_analyzer_basename_allowed($real, $analyzer) && lsp_runner_target_is_php_script($real)) {\n"
71 : " $targetIndex = $index;\n"
72 : " break;\n"
73 : " }\n"
74 : " }\n"
75 : " }\n"
76 : " if ($targetIndex < 0 || !is_string($argvList[$targetIndex])) { return null; }\n"
77 : " $target = lsp_runner_real_project_file($argvList[$targetIndex], $projectRoot);\n"
78 : " if ($target === null || !lsp_runner_analyzer_basename_allowed($target, $analyzer) || !lsp_runner_target_is_php_script($target)) { return null; }\n"
79 : " $scriptArgv = array_slice($argvList, $targetIndex);\n"
80 : " $scriptArgv[0] = $target;\n"
81 : " return [$target, $scriptArgv, $targetIndex];\n"
82 : "}\n"
83 : "$autoloadReal = lsp_runner_real_project_file($autoload, $projectRoot);\n"
84 : "if ($autoloadReal !== null) {\n"
85 : " require_once $autoloadReal;\n"
86 : "}\n"
87 : "$canFork = function_exists('pcntl_fork') && function_exists('pcntl_waitpid')\n"
88 : " && function_exists('pcntl_wexitstatus') && DIRECTORY_SEPARATOR === '/';\n"
89 : "function lsp_runner_read_frame($in): ?array {\n"
90 : " $length = 0;\n"
91 : " for (;;) {\n"
92 : " $line = fgets($in);\n"
93 : " if ($line === false) { return null; }\n"
94 : " $line = rtrim($line, \"\\r\\n\");\n"
95 : " if ($line === '') { break; }\n"
96 : " if (stripos($line, 'Content-Length:') === 0) { $length = (int) trim(substr($line, 15)); }\n"
97 : " }\n"
98 : " if ($length <= 0) { return null; }\n"
99 : " $body = '';\n"
100 : " while (strlen($body) < $length) {\n"
101 : " $chunk = fread($in, $length - strlen($body));\n"
102 : " if ($chunk === false || $chunk === '') { return null; }\n"
103 : " $body .= $chunk;\n"
104 : " }\n"
105 : " $decoded = json_decode($body, true);\n"
106 : " return is_array($decoded) ? $decoded : null;\n"
107 : "}\n"
108 : "function lsp_runner_write_frame(array $payload): void {\n"
109 : " $json = json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE);\n"
110 : " fwrite(STDOUT, 'Content-Length: ' . strlen($json) . \"\\r\\n\\r\\n\" . $json);\n"
111 : " fflush(STDOUT);\n"
112 : "}\n"
113 : "function lsp_runner_target_is_php_script(string $target): bool {\n"
114 : " $head = (string) @file_get_contents($target, false, null, 0, 128);\n"
115 : " if (strncmp($head, '<?php', 5) === 0) { return true; }\n"
116 : " if (strncmp($head, '#!', 2) === 0) {\n"
117 : " $firstLine = strtok($head, \"\\n\");\n"
118 : " return $firstLine !== false && preg_match('/(?:^|[\\\\s\\\\/])php[0-9.]*(?:\\\\s|$)/', trim($firstLine)) === 1;\n"
119 : " }\n"
120 : " return false;\n"
121 : "}\n"
122 : "function lsp_runner_run_fork(array $argvList, string $cwd, string $projectRoot, string $analyzer): ?array {\n"
123 : " $commandTarget = lsp_runner_command_target($argvList, $projectRoot, $analyzer);\n"
124 : " if ($commandTarget === null) { return null; }\n"
125 : " [$target, $scriptArgv] = $commandTarget;\n"
126 : " $stdoutFile = tempnam(sys_get_temp_dir(), 'lspr');\n"
127 : " $stderrFile = tempnam(sys_get_temp_dir(), 'lspr');\n"
128 : " if ($stdoutFile === false || $stderrFile === false) { return null; }\n"
129 : " $pid = pcntl_fork();\n"
130 : " if ($pid < 0) { @unlink($stdoutFile); @unlink($stderrFile); return null; }\n"
131 : " if ($pid === 0) {\n"
132 : " fclose(STDIN);\n"
133 : " fclose(STDOUT);\n"
134 : " fclose(STDERR);\n"
135 : " $childIn = fopen('/dev/null', 'rb');\n"
136 : " $childOut = fopen($stdoutFile, 'wb');\n"
137 : " $childErr = fopen($stderrFile, 'wb');\n"
138 : " if ($cwd !== '') { @chdir($cwd); }\n"
139 : " $_SERVER['argv'] = $scriptArgv;\n"
140 : " $_SERVER['argc'] = count($scriptArgv);\n"
141 : " $GLOBALS['argv'] = $scriptArgv;\n"
142 : " $GLOBALS['argc'] = count($scriptArgv);\n"
143 : " $argv = $scriptArgv;\n"
144 : " $argc = count($scriptArgv);\n"
145 : " try {\n"
146 : " include $target;\n"
147 : " } catch (Throwable $error) {\n"
148 : " fwrite($childErr, (string) $error);\n"
149 : " exit(255);\n"
150 : " }\n"
151 : " exit(0);\n"
152 : " }\n"
153 : " $status = 0;\n"
154 : " pcntl_waitpid($pid, $status);\n"
155 : " $output = (string) @file_get_contents($stdoutFile) . (string) @file_get_contents($stderrFile);\n"
156 : " @unlink($stdoutFile);\n"
157 : " @unlink($stderrFile);\n"
158 : " return [pcntl_wifexited($status) ? pcntl_wexitstatus($status) : 255, $output];\n"
159 : "}\n"
160 : "function lsp_runner_run_proc(array $argvList, string $cwd, string $projectRoot, string $analyzer): array {\n"
161 : " $commandTarget = lsp_runner_command_target($argvList, $projectRoot, $analyzer);\n"
162 : " if ($commandTarget === null) { return [127, '']; }\n"
163 : " $argvList[$commandTarget[2]] = $commandTarget[0];\n"
164 : " $null = DIRECTORY_SEPARATOR === '\\\\' ? 'NUL' : '/dev/null';\n"
165 : " $proc = @proc_open($argvList, [0 => ['file', $null, 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, $cwd !== '' ? $cwd : $projectRoot);\n"
166 : " if (!is_resource($proc)) { return [127, '']; }\n"
167 : " stream_set_blocking($pipes[1], false);\n"
168 : " stream_set_blocking($pipes[2], false);\n"
169 : " $open = [$pipes[1], $pipes[2]];\n"
170 : " $output = '';\n"
171 : " while ($open !== []) {\n"
172 : " $read = $open;\n"
173 : " $write = null;\n"
174 : " $except = null;\n"
175 : " if (@stream_select($read, $write, $except, 1) === false) { break; }\n"
176 : " foreach ($read as $stream) {\n"
177 : " $chunk = fread($stream, 65536);\n"
178 : " if ($chunk !== false && $chunk !== '') {\n"
179 : " $output .= $chunk;\n"
180 : " } elseif (feof($stream)) {\n"
181 : " fclose($stream);\n"
182 : " $remaining = [];\n"
183 : " foreach ($open as $candidate) {\n"
184 : " if ($candidate !== $stream) { $remaining[] = $candidate; }\n"
185 : " }\n"
186 : " $open = $remaining;\n"
187 : " }\n"
188 : " }\n"
189 : " }\n"
190 : " return [proc_close($proc), $output];\n"
191 : "}\n"
192 : "for (;;) {\n"
193 : " $job = lsp_runner_read_frame($in);\n"
194 : " if ($job === null) { exit(0); }\n"
195 : " $argvList = $job['argv'] ?? null;\n"
196 : " $cwd = lsp_runner_real_project_dir((string) ($job['cwd'] ?? ''), $projectRoot);\n"
197 : " if ($cwd === null) { $cwd = $projectRoot; }\n"
198 : " $id = $job['id'] ?? 0;\n"
199 : " if (!is_array($argvList) || $argvList === []) {\n"
200 : " lsp_runner_write_frame(['id' => $id, 'exitCode' => 127, 'output' => '']);\n"
201 : " continue;\n"
202 : " }\n"
203 : " $result = $canFork ? lsp_runner_run_fork($argvList, $cwd, $projectRoot, $analyzer) : null;\n"
204 : " if ($result === null) { $result = lsp_runner_run_proc($argvList, $cwd, $projectRoot, $analyzer); }\n"
205 : " lsp_runner_write_frame(['id' => $id, 'exitCode' => $result[0], 'output' => $result[1]]);\n"
206 : "}\n"
207 : ;
208 :
209 : typedef struct _lsp_runner_session {
210 : lsp_process_pipes pipes;
211 : smart_str rx;
212 : zend_string *analyzer;
213 : zend_string *project_root;
214 : uint64_t jobs_completed;
215 : double last_activity;
216 : zend_long next_job_id;
217 : /* Deferred type-query descriptors keyed by job id: interactive requests
218 : * stop waiting after a short budget, and the answer is collected here
219 : * later (lsp_runner_pump_pending) into the type cache. */
220 : HashTable pending;
221 : bool pending_initialized;
222 : } lsp_runner_session;
223 :
224 28 : static inline void lsp_runner_session_free(lsp_runner_session *session)
225 : {
226 : zval *descriptor;
227 : zend_string *analysis_file;
228 28 : int status = 0;
229 :
230 28 : if (lsp_process_id_valid(session->pipes.process)) {
231 28 : lsp_pipe_close(&session->pipes.input);
232 28 : lsp_pipe_close(&session->pipes.output);
233 28 : lsp_pipe_close(&session->pipes.error);
234 : /* A wedged runner (or an analyzer child it forked) may ignore
235 : * SIGTERM; never block the single-threaded request loop on it —
236 : * escalate to SIGKILL after a short grace period. */
237 28 : lsp_process_terminate(session->pipes.process);
238 28 : if (!lsp_process_wait_timeout(session->pipes.process, &status, 2.0)) {
239 0 : lsp_process_terminate_force(session->pipes.process);
240 0 : lsp_process_wait_timeout(session->pipes.process, &status, 1.0);
241 : }
242 28 : lsp_process_close(session->pipes.process);
243 : }
244 :
245 28 : smart_str_free(&session->rx);
246 :
247 28 : if (session->pending_initialized) {
248 28 : ZEND_HASH_FOREACH_VAL(&session->pending, descriptor) {
249 0 : analysis_file = lsp_array_string(descriptor, "analysisFile");
250 0 : if (analysis_file) {
251 0 : VCWD_UNLINK(ZSTR_VAL(analysis_file));
252 : }
253 : } ZEND_HASH_FOREACH_END();
254 28 : zend_hash_destroy(&session->pending);
255 : }
256 :
257 28 : if (session->analyzer) {
258 28 : zend_string_release(session->analyzer);
259 : }
260 :
261 28 : if (session->project_root) {
262 28 : zend_string_release(session->project_root);
263 : }
264 :
265 28 : efree(session);
266 28 : }
267 :
268 28 : extern void lsp_runner_session_destroy(zval *value)
269 : {
270 28 : lsp_runner_session *session = (lsp_runner_session *) Z_PTR_P(value);
271 :
272 28 : if (session) {
273 28 : lsp_runner_session_free(session);
274 : }
275 28 : }
276 :
277 28 : static inline zend_string *lsp_runner_session_key(const char *analyzer, zend_string *project_root)
278 : {
279 28 : return strpprintf(0, "%s:%s", analyzer, ZSTR_VAL(project_root));
280 : }
281 :
282 28 : static inline zend_string *lsp_runner_script_path(zend_string *project_root)
283 : {
284 28 : return strpprintf(0, "%s/.lsparrot/runner/lsp-runner.php", ZSTR_VAL(project_root));
285 : }
286 :
287 28 : static inline bool lsp_runner_write_script(zend_string *project_root, zend_string *script_path)
288 : {
289 : zend_string *dir, *contents;
290 : bool result;
291 :
292 28 : dir = strpprintf(0, "%s/.lsparrot/runner", ZSTR_VAL(project_root));
293 28 : lsp_mkdir_p(dir);
294 28 : contents = zend_string_init(lsp_runner_script_source, sizeof(lsp_runner_script_source) - 1, 0);
295 28 : result = lsp_write_string_file(script_path, contents);
296 28 : zend_string_release(contents);
297 28 : zend_string_release(dir);
298 :
299 28 : return result;
300 : }
301 :
302 28 : static inline const char *lsp_runner_php_binary(void)
303 : {
304 28 : if (PG(php_binary) && PG(php_binary)[0] != '\0') {
305 28 : return PG(php_binary);
306 : }
307 :
308 0 : return "php";
309 : }
310 :
311 28 : static inline lsp_runner_session *lsp_runner_session_start(const char *analyzer, zend_string *project_root)
312 : {
313 : lsp_runner_session *session;
314 : lsp_command command;
315 : zend_string *script_path, *autoload, *opcache_dir, *opcache_flag;
316 : bool spawned;
317 :
318 28 : script_path = lsp_runner_script_path(project_root);
319 28 : if (!lsp_runner_write_script(project_root, script_path)) {
320 0 : zend_string_release(script_path);
321 :
322 0 : return NULL;
323 : }
324 :
325 28 : opcache_dir = strpprintf(0, "%s/.lsparrot/runner/opcache", ZSTR_VAL(project_root));
326 28 : lsp_mkdir_p(opcache_dir);
327 28 : opcache_flag = strpprintf(0, "-dopcache.file_cache=%s", ZSTR_VAL(opcache_dir));
328 28 : autoload = strpprintf(0, "%s/vendor/autoload.php", ZSTR_VAL(project_root));
329 :
330 28 : lsp_command_init(&command);
331 28 : lsp_command_add(&command, lsp_runner_php_binary());
332 28 : lsp_command_add(&command, "-dopcache.enable_cli=1");
333 28 : lsp_command_add_zstr(&command, opcache_flag);
334 28 : lsp_command_add_zstr(&command, script_path);
335 28 : lsp_command_add_zstr(&command, project_root);
336 28 : lsp_command_add(&command, analyzer);
337 28 : if (lsp_is_regular_file(autoload)) {
338 0 : lsp_command_add_zstr(&command, autoload);
339 : }
340 :
341 28 : session = ecalloc(1, sizeof(*session));
342 28 : spawned = lsp_process_spawn_piped(&command, project_root, &session->pipes);
343 28 : lsp_command_destroy(&command);
344 28 : zend_string_release(autoload);
345 28 : zend_string_release(opcache_flag);
346 28 : zend_string_release(opcache_dir);
347 28 : zend_string_release(script_path);
348 :
349 28 : if (!spawned) {
350 0 : efree(session);
351 :
352 0 : return NULL;
353 : }
354 :
355 28 : session->analyzer = zend_string_init(analyzer, strlen(analyzer), 0);
356 28 : session->project_root = zend_string_copy(project_root);
357 28 : session->next_job_id = 1;
358 28 : zend_hash_init(&session->pending, 4, NULL, ZVAL_PTR_DTOR, 0);
359 28 : session->pending_initialized = true;
360 :
361 28 : return session;
362 : }
363 :
364 28 : static inline lsp_runner_session *lsp_runner_session_ensure(lsp_server *server, const char *analyzer, zend_string *project_root)
365 : {
366 : lsp_runner_session *session;
367 : zend_string *key;
368 : zval *existing, ptr;
369 :
370 28 : key = lsp_runner_session_key(analyzer, project_root);
371 28 : existing = zend_hash_find(&server->runner_sessions, key);
372 28 : if (existing) {
373 0 : zend_string_release(key);
374 :
375 0 : session = (lsp_runner_session *) Z_PTR_P(existing);
376 0 : session->last_activity = lsp_now_seconds();
377 :
378 0 : return session;
379 : }
380 :
381 28 : session = lsp_runner_session_start(analyzer, project_root);
382 28 : if (!session) {
383 0 : zend_string_release(key);
384 :
385 0 : return NULL;
386 : }
387 :
388 28 : session->last_activity = lsp_now_seconds();
389 28 : ZVAL_PTR(&ptr, session);
390 28 : zend_hash_update(&server->runner_sessions, key, &ptr);
391 28 : zend_string_release(key);
392 :
393 28 : return session;
394 : }
395 :
396 : /* Resident runners keep a booted PHP process per (analyzer, project) for
397 : * interactive type queries. Long editing sessions touching many projects
398 : * would otherwise accumulate processes forever; reap sessions that have been
399 : * idle past the timeout and have nothing pending. */
400 : #define LSP_RUNNER_IDLE_TIMEOUT_SECONDS 300.0
401 :
402 : /* Forked index workers inherit every runner pipe fd; extra references keep
403 : * the pipes open and delay EOF-based subprocess-exit detection in the
404 : * parent. Children call this right after fork(). */
405 568 : extern void lsp_runner_close_pipes_in_child(lsp_server *server)
406 : {
407 : lsp_runner_session *session;
408 : zval *value;
409 :
410 568 : ZEND_HASH_FOREACH_VAL(&server->runner_sessions, value) {
411 0 : if (Z_TYPE_P(value) != IS_PTR) {
412 0 : continue;
413 : }
414 :
415 0 : session = (lsp_runner_session *) Z_PTR_P(value);
416 0 : lsp_pipe_close(&session->pipes.input);
417 0 : lsp_pipe_close(&session->pipes.output);
418 0 : lsp_pipe_close(&session->pipes.error);
419 : } ZEND_HASH_FOREACH_END();
420 568 : }
421 :
422 3104 : extern void lsp_runner_reap_idle_sessions(lsp_server *server)
423 : {
424 : lsp_runner_session *session;
425 : zend_string *key;
426 : zval *value;
427 3104 : double now = lsp_now_seconds();
428 :
429 3236 : ZEND_HASH_FOREACH_STR_KEY_VAL(&server->runner_sessions, key, value) {
430 132 : if (!key || Z_TYPE_P(value) != IS_PTR) {
431 0 : continue;
432 : }
433 :
434 132 : session = (lsp_runner_session *) Z_PTR_P(value);
435 132 : if (session->pending_initialized && zend_hash_num_elements(&session->pending) > 0) {
436 64 : continue;
437 : }
438 :
439 68 : if (session->last_activity > 0.0 && now - session->last_activity > LSP_RUNNER_IDLE_TIMEOUT_SECONDS) {
440 0 : zend_hash_del(&server->runner_sessions, key);
441 : }
442 : } ZEND_HASH_FOREACH_END();
443 3104 : }
444 :
445 0 : static inline void lsp_runner_session_drop(lsp_server *server, lsp_runner_session *session)
446 : {
447 : zend_string *key;
448 :
449 0 : key = lsp_runner_session_key(ZSTR_VAL(session->analyzer), session->project_root);
450 0 : zend_hash_del(&server->runner_sessions, key);
451 0 : zend_string_release(key);
452 0 : }
453 :
454 28 : static inline zend_string *lsp_runner_encode_job(zend_long job_id, lsp_command *command, zend_string *cwd, double timeout)
455 : {
456 28 : smart_str json = {0};
457 28 : zend_string *encoded = NULL;
458 : zval payload, argv_zv;
459 : uint32_t i;
460 :
461 28 : array_init(&payload);
462 28 : add_assoc_long(&payload, "id", job_id);
463 28 : array_init(&argv_zv);
464 316 : for (i = 0; i < command->count; i++) {
465 288 : add_next_index_string(&argv_zv, command->argv[i]);
466 : }
467 28 : add_assoc_zval(&payload, "argv", &argv_zv);
468 28 : add_assoc_str(&payload, "cwd", cwd ? zend_string_copy(cwd) : zend_empty_string);
469 28 : add_assoc_long(&payload, "timeoutMs", (zend_long) (timeout > 0.0 ? timeout * 1000.0 : 30000.0));
470 :
471 28 : if (php_json_encode(&json, &payload, PHP_JSON_UNESCAPED_SLASHES) == SUCCESS && json.s) {
472 28 : smart_str_0(&json);
473 28 : encoded = zend_string_copy(json.s);
474 : }
475 :
476 28 : smart_str_free(&json);
477 28 : zval_ptr_dtor(&payload);
478 :
479 28 : return encoded;
480 : }
481 :
482 : /* Parse one complete Content-Length framed JSON message out of the session
483 : * receive buffer. */
484 411 : static inline bool lsp_runner_parse_frame(lsp_runner_session *session, zval *message)
485 : {
486 : const char *data, *headers_end, *length_marker;
487 : char *body;
488 : size_t available, header_size, content_length;
489 :
490 411 : if (!session->rx.s) {
491 379 : return false;
492 : }
493 :
494 32 : data = ZSTR_VAL(session->rx.s);
495 32 : available = ZSTR_LEN(session->rx.s);
496 32 : headers_end = NULL;
497 32 : if (available > 3) {
498 28 : headers_end = (const char *) php_memnstr((char *) data, "\r\n\r\n", 4, (char *) data + available);
499 : }
500 32 : if (!headers_end) {
501 4 : return false;
502 : }
503 :
504 28 : length_marker = data;
505 28 : if (strncasecmp(length_marker, "Content-Length:", sizeof("Content-Length:") - 1) != 0) {
506 0 : return false;
507 : }
508 :
509 28 : content_length = (size_t) strtoull(length_marker + sizeof("Content-Length:") - 1, NULL, 10);
510 28 : header_size = (headers_end - data) + 4;
511 28 : if (content_length == 0 || available < header_size + content_length) {
512 0 : return false;
513 : }
514 :
515 28 : body = emalloc(content_length + 1);
516 28 : memcpy(body, data + header_size, content_length);
517 28 : body[content_length] = '\0';
518 28 : ZVAL_UNDEF(message);
519 28 : php_json_decode_ex(message, body, content_length, PHP_JSON_OBJECT_AS_ARRAY, 64);
520 28 : efree(body);
521 :
522 : /* Consume the frame. */
523 28 : if (available > header_size + content_length) {
524 0 : memmove(ZSTR_VAL(session->rx.s), data + header_size + content_length, available - header_size - content_length);
525 0 : ZSTR_LEN(session->rx.s) = available - header_size - content_length;
526 : } else {
527 28 : ZSTR_LEN(session->rx.s) = 0;
528 : }
529 :
530 28 : if (Z_TYPE_P(message) != IS_ARRAY) {
531 0 : if (!Z_ISUNDEF_P(message)) {
532 0 : zval_ptr_dtor(message);
533 : }
534 :
535 0 : return false;
536 : }
537 :
538 28 : return true;
539 : }
540 :
541 : /* A frame whose id is not the one being awaited belongs to a deferred type
542 : * query; hand it to the analyzer layer and drop the pending record. */
543 4 : static inline void lsp_runner_resolve_pending_frame(lsp_server *server, lsp_runner_session *session, zval *message)
544 : {
545 : zval *id_zv, *descriptor, *output_zv;
546 :
547 4 : id_zv = zend_hash_str_find(Z_ARRVAL_P(message), "id", sizeof("id") - 1);
548 4 : if (!id_zv || Z_TYPE_P(id_zv) != IS_LONG) {
549 0 : return;
550 : }
551 :
552 4 : descriptor = zend_hash_index_find(&session->pending, (zend_ulong) Z_LVAL_P(id_zv));
553 4 : if (!descriptor) {
554 0 : return;
555 : }
556 :
557 4 : output_zv = zend_hash_str_find(Z_ARRVAL_P(message), "output", sizeof("output") - 1);
558 4 : lsp_analyzer_deferred_type_completed(server, descriptor, output_zv && Z_TYPE_P(output_zv) == IS_STRING ? Z_STR_P(output_zv) : NULL);
559 4 : zend_hash_index_del(&session->pending, (zend_ulong) Z_LVAL_P(id_zv));
560 : }
561 :
562 28 : static inline zend_string *lsp_runner_wait_response(lsp_server *server, lsp_runner_session *session, zend_long job_id, double timeout, bool *closed)
563 : {
564 28 : smart_str discard = {0};
565 28 : zend_string *output = NULL;
566 : zval message, *id_zv, *output_zv;
567 : double deadline;
568 28 : bool output_closed = false, error_closed = false, matched;
569 :
570 28 : deadline = lsp_now_seconds() + (timeout > 0.0 ? timeout : 30.0);
571 :
572 : for (;;) {
573 339 : lsp_pipe_read_available(session->pipes.output, &session->rx, &output_closed);
574 339 : lsp_pipe_read_available(session->pipes.error, &discard, &error_closed);
575 339 : smart_str_free(&discard);
576 :
577 339 : while (lsp_runner_parse_frame(session, &message)) {
578 24 : id_zv = zend_hash_str_find(Z_ARRVAL(message), "id", sizeof("id") - 1);
579 24 : matched = id_zv && Z_TYPE_P(id_zv) == IS_LONG && Z_LVAL_P(id_zv) == job_id;
580 :
581 24 : if (matched) {
582 24 : output_zv = zend_hash_str_find(Z_ARRVAL(message), "output", sizeof("output") - 1);
583 24 : if (output_zv && Z_TYPE_P(output_zv) == IS_STRING) {
584 24 : output = zend_string_copy(Z_STR_P(output_zv));
585 : } else {
586 0 : output = zend_empty_string;
587 : }
588 : } else {
589 0 : lsp_runner_resolve_pending_frame(server, session, &message);
590 : }
591 :
592 24 : zval_ptr_dtor(&message);
593 :
594 24 : if (matched) {
595 24 : return output;
596 : }
597 : }
598 :
599 315 : if (output_closed || lsp_now_seconds() >= deadline) {
600 4 : if (closed) {
601 4 : *closed = output_closed;
602 : }
603 :
604 4 : return NULL;
605 : }
606 :
607 311 : lsp_sleep_milliseconds(5);
608 : }
609 : }
610 :
611 28 : static inline bool lsp_runner_analyzer_basename_matches(zend_string *path, const char *analyzer)
612 : {
613 : const char *base;
614 : size_t base_length, analyzer_length;
615 :
616 28 : base = lsp_path_basename(path);
617 28 : base_length = strlen(base);
618 28 : analyzer_length = strlen(analyzer);
619 28 : if (base_length == analyzer_length && strcasecmp(base, analyzer) == 0) {
620 28 : return true;
621 : }
622 0 : if (base_length == analyzer_length + 4 && strncasecmp(base, analyzer, analyzer_length) == 0) {
623 0 : return strcasecmp(base + analyzer_length, ".bat") == 0 || strcasecmp(base + analyzer_length, ".cmd") == 0;
624 : }
625 :
626 0 : return false;
627 : }
628 :
629 28 : static inline bool lsp_runner_command_can_use_project_runner(const char *analyzer, zend_string *project_root, lsp_command *command)
630 : {
631 : zend_string *argument;
632 : uint32_t i;
633 : bool result;
634 :
635 28 : result = false;
636 56 : for (i = 0; i < command->count; i++) {
637 56 : argument = zend_string_init(command->argv[i], strlen(command->argv[i]), 0);
638 56 : if (
639 84 : lsp_path_is_same_or_under(argument, project_root) &&
640 56 : lsp_is_regular_file(argument) &&
641 28 : lsp_runner_analyzer_basename_matches(argument, analyzer)
642 : ) {
643 28 : result = true;
644 : }
645 56 : zend_string_release(argument);
646 56 : if (result) {
647 28 : return true;
648 : }
649 : }
650 :
651 0 : return false;
652 : }
653 :
654 0 : extern zend_string *lsp_runner_run_capture(lsp_server *server, const char *analyzer, zend_string *project_root, lsp_command *command, zend_string *cwd, double timeout)
655 : {
656 : lsp_runner_session *session;
657 : zend_string *job, *frame, *output;
658 : zend_long job_id;
659 : bool sent;
660 :
661 0 : if (!lsp_runner_command_can_use_project_runner(analyzer, project_root, command)) {
662 0 : return lsp_run_command_capture(command, cwd, timeout);
663 : }
664 :
665 0 : session = lsp_runner_session_ensure(server, analyzer, project_root);
666 0 : if (!session) {
667 0 : return lsp_run_command_capture(command, cwd, timeout);
668 : }
669 :
670 0 : job_id = session->next_job_id++;
671 0 : job = lsp_runner_encode_job(job_id, command, cwd, timeout);
672 0 : if (!job) {
673 0 : return lsp_run_command_capture(command, cwd, timeout);
674 : }
675 :
676 0 : frame = strpprintf(0, "Content-Length: %zu\r\n\r\n%s", ZSTR_LEN(job), ZSTR_VAL(job));
677 0 : zend_string_release(job);
678 0 : sent = lsp_pipe_write_all_timeout(session->pipes.input, ZSTR_VAL(frame), ZSTR_LEN(frame), 5.0);
679 0 : zend_string_release(frame);
680 :
681 : /* +5s grace so the runner's own timeout frame can still arrive. */
682 0 : output = sent ? lsp_runner_wait_response(server, session, job_id, (timeout > 0.0 ? timeout : 30.0) + 5.0, NULL) : NULL;
683 0 : if (!output) {
684 : /* The runner is wedged or dead: drop the session and fall back to a
685 : * direct one-shot spawn so the request still completes. */
686 0 : lsp_runner_session_drop(server, session);
687 :
688 0 : return lsp_run_command_capture(command, cwd, timeout);
689 : }
690 :
691 0 : session->jobs_completed++;
692 :
693 0 : return output;
694 : }
695 :
696 : /* Interactive variant: waits only wait_timeout for the resident runner. When
697 : * the answer is not ready in time, the job keeps running and `descriptor`
698 : * (ownership transferred) is parked on the session; lsp_runner_pump_pending
699 : * later routes the output to lsp_analyzer_deferred_type_completed. */
700 28 : extern zend_string *lsp_runner_run_capture_deferred(lsp_server *server, const char *analyzer, zend_string *project_root, lsp_command *command, zend_string *cwd, double wait_timeout, double job_timeout, zval *descriptor, bool *deferred)
701 : {
702 : lsp_runner_session *session;
703 : zend_string *job, *frame, *output;
704 : zend_long job_id;
705 28 : bool sent, closed = false;
706 :
707 28 : *deferred = false;
708 :
709 28 : if (!lsp_runner_command_can_use_project_runner(analyzer, project_root, command)) {
710 : /* No resident runner for this command: a one-shot spawn cannot
711 : * outlive the request, so it gets the bounded interactive budget. */
712 0 : return lsp_run_command_capture(command, cwd, wait_timeout);
713 : }
714 :
715 28 : session = lsp_runner_session_ensure(server, analyzer, project_root);
716 28 : if (!session) {
717 0 : return lsp_run_command_capture(command, cwd, wait_timeout);
718 : }
719 :
720 28 : job_id = session->next_job_id++;
721 28 : job = lsp_runner_encode_job(job_id, command, cwd, job_timeout);
722 28 : if (!job) {
723 0 : return lsp_run_command_capture(command, cwd, wait_timeout);
724 : }
725 :
726 28 : frame = strpprintf(0, "Content-Length: %zu\r\n\r\n%s", ZSTR_LEN(job), ZSTR_VAL(job));
727 28 : zend_string_release(job);
728 28 : sent = lsp_pipe_write_all_timeout(session->pipes.input, ZSTR_VAL(frame), ZSTR_LEN(frame), 5.0);
729 28 : zend_string_release(frame);
730 :
731 28 : if (!sent) {
732 0 : lsp_runner_session_drop(server, session);
733 :
734 0 : return lsp_run_command_capture(command, cwd, wait_timeout);
735 : }
736 :
737 28 : output = lsp_runner_wait_response(server, session, job_id, wait_timeout, &closed);
738 28 : if (output) {
739 24 : session->jobs_completed++;
740 :
741 24 : return output;
742 : }
743 :
744 4 : if (closed) {
745 0 : lsp_runner_session_drop(server, session);
746 :
747 0 : return lsp_run_command_capture(command, cwd, wait_timeout);
748 : }
749 :
750 : /* Timed out but the runner is alive: park the job and collect it later. */
751 4 : zend_hash_index_update(&session->pending, (zend_ulong) job_id, descriptor);
752 4 : *deferred = true;
753 :
754 4 : return NULL;
755 : }
756 :
757 3104 : extern void lsp_runner_pump_pending(lsp_server *server)
758 : {
759 : lsp_runner_session *session;
760 3104 : smart_str discard = {0};
761 : zval *value, message;
762 : bool closed;
763 :
764 3236 : ZEND_HASH_FOREACH_VAL(&server->runner_sessions, value) {
765 132 : session = (lsp_runner_session *) Z_PTR_P(value);
766 132 : if (!session || zend_hash_num_elements(&session->pending) == 0) {
767 64 : continue;
768 : }
769 :
770 68 : closed = false;
771 68 : lsp_pipe_read_available(session->pipes.output, &session->rx, &closed);
772 68 : lsp_pipe_read_available(session->pipes.error, &discard, &closed);
773 68 : smart_str_free(&discard);
774 :
775 72 : while (lsp_runner_parse_frame(session, &message)) {
776 4 : lsp_runner_resolve_pending_frame(server, session, &message);
777 4 : zval_ptr_dtor(&message);
778 : }
779 : } ZEND_HASH_FOREACH_END();
780 3104 : }
781 :
782 957 : extern uint32_t lsp_runner_pending_count(lsp_server *server)
783 : {
784 : lsp_runner_session *session;
785 : zval *value;
786 957 : uint32_t count = 0;
787 :
788 994 : ZEND_HASH_FOREACH_VAL(&server->runner_sessions, value) {
789 37 : session = (lsp_runner_session *) Z_PTR_P(value);
790 37 : if (session) {
791 37 : count += zend_hash_num_elements(&session->pending);
792 : }
793 : } ZEND_HASH_FOREACH_END();
794 :
795 957 : return count;
796 : }
797 :
798 504 : extern bool lsp_runner_has_pending_for_uri(lsp_server *server, zend_string *uri)
799 : {
800 : lsp_runner_session *session;
801 : zend_string *pending_uri;
802 : zval *value, *descriptor;
803 504 : bool found = false;
804 :
805 508 : ZEND_HASH_FOREACH_VAL(&server->runner_sessions, value) {
806 4 : session = (lsp_runner_session *) Z_PTR_P(value);
807 4 : if (!session) {
808 0 : continue;
809 : }
810 :
811 4 : ZEND_HASH_FOREACH_VAL(&session->pending, descriptor) {
812 0 : pending_uri = lsp_array_string(descriptor, "uri");
813 0 : if (pending_uri && zend_string_equals(pending_uri, uri)) {
814 0 : found = true;
815 0 : break;
816 : }
817 : } ZEND_HASH_FOREACH_END();
818 :
819 4 : if (found) {
820 0 : break;
821 : }
822 : } ZEND_HASH_FOREACH_END();
823 :
824 504 : return found;
825 : }
826 :
827 548 : extern void lsp_runner_shutdown_all(lsp_server *server)
828 : {
829 548 : zend_hash_clean(&server->runner_sessions);
830 548 : }
831 :
832 116 : extern void lsp_runner_status(lsp_server *server, zval *target)
833 : {
834 : lsp_runner_session *session;
835 : zval runners, entry;
836 116 : int status = 0;
837 : bool alive;
838 :
839 116 : array_init(&runners);
840 :
841 124 : ZEND_HASH_FOREACH_PTR(&server->runner_sessions, session) {
842 8 : if (!session) {
843 0 : continue;
844 : }
845 :
846 16 : alive = lsp_process_id_valid(session->pipes.process) &&
847 8 : !lsp_process_wait_nonblocking(session->pipes.process, &status)
848 : ;
849 8 : if (!alive && lsp_process_id_valid(session->pipes.process)) {
850 : /* The probe above reaped the runner, so its pid may be reused
851 : * by an unrelated process at any moment; forget it so teardown
852 : * cannot signal a stale id. */
853 0 : lsp_pipe_close(&session->pipes.input);
854 0 : lsp_pipe_close(&session->pipes.output);
855 0 : lsp_pipe_close(&session->pipes.error);
856 0 : lsp_process_close(session->pipes.process);
857 0 : session->pipes.process = LSP_INVALID_PROCESS_ID;
858 : }
859 :
860 8 : array_init(&entry);
861 8 : add_assoc_str(&entry, "analyzer", zend_string_copy(session->analyzer));
862 8 : add_assoc_str(&entry, "projectRoot", zend_string_copy(session->project_root));
863 8 : add_assoc_long(&entry, "jobs", (zend_long) session->jobs_completed);
864 8 : add_assoc_bool(&entry, "alive", alive);
865 8 : add_next_index_zval(&runners, &entry);
866 : } ZEND_HASH_FOREACH_END();
867 :
868 116 : add_assoc_zval(target, "runners", &runners);
869 116 : }
|