]> git.lyx.org Git - features.git/blob - src/support/ForkedCalls.cpp
Add new placeholder $${python} to configure
[features.git] / src / support / ForkedCalls.cpp
1 /**
2  * \file ForkedCalls.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Angus Leeming
8  * \author Alfredo Braunstein
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "support/ForkedCalls.h"
16
17 #include "support/debug.h"
18 #include "support/filetools.h"
19 #include "support/lstrings.h"
20 #include "support/lyxlib.h"
21 #include "support/os.h"
22 #include "support/Timeout.h"
23
24 #include "support/bind.h"
25
26 #include <cerrno>
27 #include <cstring>
28 #include <list>
29 #include <queue>
30 #include <sstream>
31 #include <utility>
32 #include <vector>
33
34 #ifdef _WIN32
35 # define SIGHUP 1
36 # define SIGKILL 9
37 # include <windows.h>
38 # include <process.h>
39 # undef max
40 #else
41 # include <csignal>
42 # include <cstdlib>
43 # ifdef HAVE_UNISTD_H
44 #  include <unistd.h>
45 # endif
46 # include <sys/wait.h>
47 #endif
48
49 using namespace std;
50
51
52 namespace lyx {
53 namespace support {
54
55 namespace {
56
57 /////////////////////////////////////////////////////////////////////
58 //
59 // Murder
60 //
61 /////////////////////////////////////////////////////////////////////
62
63 class Murder {
64 public:
65         //
66         static void killItDead(int secs, pid_t pid)
67         {
68                 if (secs > 0)
69                         new Murder(secs, pid);
70                 else if (pid != 0)
71                         support::kill(pid, SIGKILL);
72         }
73
74         //
75         void kill()
76         {
77                 if (pid_ != 0)
78                         support::kill(pid_, SIGKILL);
79                 lyxerr << "Killed " << pid_ << endl;
80                 delete this;
81         }
82
83 private:
84         //
85         Murder(int secs, pid_t pid)
86                 : timeout_(1000*secs, Timeout::ONETIME), pid_(pid)
87         {
88                 // Connection is closed with this.
89                 timeout_.timeout.connect([this](){ kill(); });
90                 timeout_.start();
91         }
92
93         //
94         Timeout timeout_;
95         //
96         pid_t pid_;
97 };
98
99 } // namespace
100
101
102 /////////////////////////////////////////////////////////////////////
103 //
104 // ForkedProcess
105 //
106 /////////////////////////////////////////////////////////////////////
107
108 ForkedProcess::ForkedProcess()
109         : pid_(0), retval_(0)
110 {}
111
112
113 bool ForkedProcess::IAmAChild = false;
114
115
116 void ForkedProcess::emitSignal()
117 {
118         if (signal_) {
119                 signal_->operator()(pid_, retval_);
120         }
121 }
122
123
124 // Spawn the child process
125 int ForkedProcess::run(Starttype type)
126 {
127         retval_ = 0;
128         pid_ = generateChild();
129         if (pid_ <= 0) { // child or fork failed.
130                 retval_ = 1;
131                 if (pid_ == 0)
132                         //we also do this in fork(), too, but maybe someone will try
133                         //to bypass that
134                         IAmAChild = true;
135                 return retval_;
136         }
137
138         switch (type) {
139         case Wait:
140                 retval_ = waitForChild();
141                 break;
142         case DontWait: {
143                 // Integrate into the Controller
144                 ForkedCallsController::addCall(*this);
145                 break;
146         }
147         }
148
149         return retval_;
150 }
151
152
153 bool ForkedProcess::running() const
154 {
155         if (pid() <= 0)
156                 return false;
157
158 #if !defined (_WIN32)
159         // Un-UNIX like, but we don't have much use for
160         // knowing if a zombie exists, so just reap it first.
161         int waitstatus;
162         waitpid(pid(), &waitstatus, WNOHANG);
163 #endif
164
165         // Racy of course, but it will do.
166         if (support::kill(pid(), 0) && errno == ESRCH)
167                 return false;
168         return true;
169 }
170
171
172 void ForkedProcess::kill(int tol)
173 {
174         lyxerr << "ForkedProcess::kill(" << tol << ')' << endl;
175         if (pid() <= 0) {
176                 lyxerr << "Can't kill non-existent process!" << endl;
177                 return;
178         }
179
180         int const tolerance = max(0, tol);
181         if (tolerance == 0) {
182                 // Kill it dead NOW!
183                 Murder::killItDead(0, pid());
184         } else {
185                 int ret = support::kill(pid(), SIGHUP);
186
187                 // The process is already dead if wait_for_death is false
188                 bool const wait_for_death = (ret == 0 && errno != ESRCH);
189
190                 if (wait_for_death)
191                         Murder::killItDead(tolerance, pid());
192         }
193 }
194
195
196 pid_t ForkedProcess::fork() {
197 #if !defined (HAVE_FORK)
198         return -1;
199 #else
200         pid_t pid = ::fork();
201         if (pid == 0)
202                 IAmAChild = true;
203         return pid;
204 #endif
205 }
206
207
208 // Wait for child process to finish. Returns returncode from child.
209 int ForkedProcess::waitForChild()
210 {
211         // We'll pretend that the child returns 1 on all error conditions.
212         retval_ = 1;
213
214 #if defined (_WIN32)
215         HANDLE const hProcess = HANDLE(pid_);
216
217         DWORD const wait_status = ::WaitForSingleObject(hProcess, INFINITE);
218
219         switch (wait_status) {
220         case WAIT_OBJECT_0: {
221                 DWORD exit_code = 0;
222                 if (!GetExitCodeProcess(hProcess, &exit_code)) {
223                         lyxerr << "GetExitCodeProcess failed waiting for child\n"
224                                << getChildErrorMessage() << endl;
225                 } else
226                         retval_ = exit_code;
227                 break;
228         }
229         case WAIT_FAILED:
230                 lyxerr << "WaitForSingleObject failed waiting for child\n"
231                        << getChildErrorMessage() << endl;
232                 break;
233         }
234
235 #else
236         int status;
237         bool wait = true;
238         while (wait) {
239                 pid_t waitrpid = waitpid(pid_, &status, WUNTRACED);
240                 if (waitrpid == -1) {
241                         lyxerr << "LyX: Error waiting for child:"
242                                << strerror(errno) << endl;
243                         wait = false;
244                 } else if (WIFEXITED(status)) {
245                         // Child exited normally. Update return value.
246                         retval_ = WEXITSTATUS(status);
247                         wait = false;
248                 } else if (WIFSIGNALED(status)) {
249                         lyxerr << "LyX: Child didn't catch signal "
250                                << WTERMSIG(status)
251                                << "and died. Too bad." << endl;
252                         wait = false;
253                 } else if (WIFSTOPPED(status)) {
254                         lyxerr << "LyX: Child (pid: " << pid_
255                                << ") stopped on signal "
256                                << WSTOPSIG(status)
257                                << ". Waiting for child to finish." << endl;
258                 } else {
259                         lyxerr << "LyX: Something rotten happened while "
260                                 "waiting for child " << pid_ << endl;
261                         wait = false;
262                 }
263         }
264 #endif
265         return retval_;
266 }
267
268
269 /////////////////////////////////////////////////////////////////////
270 //
271 // ForkedCall
272 //
273 /////////////////////////////////////////////////////////////////////
274
275 ForkedCall::ForkedCall(string const & path, string const & lpath)
276         : cmd_prefix_(to_filesystem8bit(from_utf8(latexEnvCmdPrefix(path, lpath))))
277 {}
278
279
280 int ForkedCall::startScript(Starttype wait, string const & what)
281 {
282         if (wait != Wait) {
283                 retval_ = startScript(what, sigPtr());
284                 return retval_;
285         }
286
287         command_ = commandPrep(trim(what));
288         signal_.reset();
289         return run(Wait);
290 }
291
292
293 int ForkedCall::startScript(string const & what, sigPtr signal)
294 {
295         command_ = commandPrep(trim(what));
296         signal_  = signal;
297
298         return run(DontWait);
299 }
300
301
302 // generate child in background
303 int ForkedCall::generateChild()
304 {
305         if (command_.empty())
306                 return 1;
307
308 #if !defined (_WIN32)
309         // POSIX
310
311         // Split the input command up into an array of words stored
312         // in a contiguous block of memory. The array contains pointers
313         // to each word.
314         // Don't forget the terminating `\0' character.
315         char const * const c_str = command_.c_str();
316         vector<char> vec(c_str, c_str + command_.size() + 1);
317
318         // Splitting the command up into an array of words means replacing
319         // the whitespace between words with '\0'. Life is complicated
320         // however, because words protected by quotes can contain whitespace.
321         //
322         // The strategy we adopt is:
323         // 1. If we're not inside quotes, then replace white space with '\0'.
324         // 2. If we are inside quotes, then don't replace the white space
325         //    but do remove the quotes themselves. We do this naively by
326         //    replacing the quote with '\0' which is fine if quotes
327         //    delimit the entire word. However, if quotes do not delimit the
328         //    entire word (i.e., open quote is inside word), simply discard
329         //    them such as not to break the current word.
330         char inside_quote = 0;
331         char c_before_open_quote = ' ';
332         vector<char>::iterator it = vec.begin();
333         vector<char>::iterator itc = vec.begin();
334         vector<char>::iterator const end = vec.end();
335         for (; it != end; ++it, ++itc) {
336                 char const c = *it;
337                 if (!inside_quote) {
338                         if (c == '\'' || c == '"') {
339                                 if (c_before_open_quote == ' ')
340                                         *itc = '\0';
341                                 else
342                                         --itc;
343                                 inside_quote = c;
344                         } else {
345                                 if (c == ' ')
346                                         *itc = '\0';
347                                 else
348                                         *itc = c;
349                                 c_before_open_quote = c;
350                         }
351                 } else if (c == inside_quote) {
352                         if (c_before_open_quote == ' ')
353                                 *itc = '\0';
354                         else
355                                 --itc;
356                         inside_quote = 0;
357                 } else
358                         *itc = c;
359         }
360
361         // Clear what remains.
362         for (; itc != end; ++itc)
363                 *itc = '\0';
364
365         // Build an array of pointers to each word.
366         it = vec.begin();
367         vector<char *> argv;
368         char prev = '\0';
369         for (; it != end; ++it) {
370                 if (*it != '\0' && prev == '\0')
371                         argv.push_back(&*it);
372                 prev = *it;
373         }
374         argv.push_back(nullptr);
375
376         // Debug output.
377         if (lyxerr.debugging(Debug::FILES)) {
378                 vector<char *>::iterator ait = argv.begin();
379                 vector<char *>::iterator const aend = argv.end();
380                 lyxerr << "<command>\n\t" << command_
381                        << "\n\tInterpreted as:\n\n";
382                 for (; ait != aend; ++ait)
383                         if (*ait)
384                                 lyxerr << '\t'<< *ait << '\n';
385                 lyxerr << "</command>" << endl;
386         }
387
388         pid_t const cpid = ::fork();
389         if (cpid == 0) {
390                 // Child
391                 execvp(argv[0], &*argv.begin());
392
393                 // If something goes wrong, we end up here
394                 lyxerr << "execvp of \"" << command_ << "\" failed: "
395                        << strerror(errno) << endl;
396                 _exit(1);
397         }
398 #else
399         // Windows
400
401         pid_t cpid = -1;
402
403         STARTUPINFO startup;
404         PROCESS_INFORMATION process;
405
406         memset(&startup, 0, sizeof(STARTUPINFO));
407         memset(&process, 0, sizeof(PROCESS_INFORMATION));
408
409         startup.cb = sizeof(STARTUPINFO);
410
411         if (CreateProcess(0, (LPSTR)line.c_str(), 0, 0, FALSE,
412                 CREATE_NO_WINDOW, 0, 0, &startup, &process)) {
413                 CloseHandle(process.hThread);
414                 cpid = (pid_t)process.hProcess;
415         }
416 #endif
417
418         if (cpid < 0) {
419                 // Error.
420                 lyxerr << "Could not fork: " << strerror(errno) << endl;
421         }
422
423         return cpid;
424 }
425
426
427 /////////////////////////////////////////////////////////////////////
428 //
429 // ForkedCallQueue
430 //
431 /////////////////////////////////////////////////////////////////////
432
433 namespace ForkedCallQueue {
434
435 /// A process in the queue
436 typedef pair<string, ForkedCall::sigPtr> Process;
437
438 /// in-progress queue
439 static queue<Process> callQueue_;
440
441 /// flag whether queue is running
442 static bool running_ = false;
443
444 ///
445 void startCaller();
446 ///
447 void stopCaller();
448 ///
449 void callback(pid_t, int);
450
451 /** Add a process to the queue. Processes are forked sequentially
452  *  only one is running at a time.
453  *  Connect to the returned signal and you'll be informed when
454  *  the process has ended.
455  */
456 ForkedCall::sigPtr add(string const & process)
457 {
458         ForkedCall::sigPtr ptr;
459         ptr.reset(new ForkedCall::sig);
460         callQueue_.push(Process(process, ptr));
461         if (!running_)
462                 startCaller();
463         return ptr;
464 }
465
466
467 void callNext()
468 {
469         if (callQueue_.empty())
470                 return;
471         Process pro = callQueue_.front();
472         callQueue_.pop();
473         // Bind our chain caller
474         pro.second->connect(callback);
475         ForkedCall call;
476         //If we fail to fork the process, then emit the signal
477         //to tell the outside world that it failed.
478         if (call.startScript(pro.first, pro.second) > 0)
479                 pro.second->operator()(0,1);
480 }
481
482
483 void callback(pid_t, int)
484 {
485         if (callQueue_.empty())
486                 stopCaller();
487         else
488                 callNext();
489 }
490
491
492 void startCaller()
493 {
494         LYXERR(Debug::GRAPHICS, "ForkedCallQueue: waking up");
495         running_ = true ;
496         callNext();
497 }
498
499
500 void stopCaller()
501 {
502         running_ = false ;
503         LYXERR(Debug::GRAPHICS, "ForkedCallQueue: I'm going to sleep");
504 }
505
506
507 bool running()
508 {
509         return running_;
510 }
511
512 } // namespace ForkedCallQueue
513
514
515 /////////////////////////////////////////////////////////////////////
516 //
517 // ForkedCallsController
518 //
519 /////////////////////////////////////////////////////////////////////
520
521 #if defined(_WIN32)
522 string const getChildErrorMessage()
523 {
524         DWORD const error_code = ::GetLastError();
525
526         HLOCAL t_message = 0;
527         bool const ok = ::FormatMessage(
528                 FORMAT_MESSAGE_ALLOCATE_BUFFER |
529                 FORMAT_MESSAGE_FROM_SYSTEM,
530                 0, error_code,
531                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
532                 (LPTSTR) &t_message, 0, 0
533                 ) != 0;
534
535         ostringstream ss;
536         ss << "LyX: Error waiting for child: " << error_code;
537
538         if (ok) {
539                 ss << ": " << (LPTSTR)t_message;
540                 ::LocalFree(t_message);
541         } else
542                 ss << ": Error unknown.";
543
544         return ss.str();
545 }
546 #endif
547
548
549 namespace ForkedCallsController {
550
551 typedef shared_ptr<ForkedProcess> ForkedProcessPtr;
552 typedef list<ForkedProcessPtr> ListType;
553 typedef ListType::iterator iterator;
554
555
556 /// The child processes
557 static ListType forkedCalls;
558
559 iterator find_pid(pid_t pid)
560 {
561         return find_if(forkedCalls.begin(), forkedCalls.end(),
562                             lyx::bind(equal_to<pid_t>(),
563                             lyx::bind(&ForkedCall::pid, _1),
564                             pid));
565 }
566
567
568 void addCall(ForkedProcess const & newcall)
569 {
570         forkedCalls.push_back(newcall.clone());
571 }
572
573
574 // Check the list of dead children and emit any associated signals.
575 void handleCompletedProcesses()
576 {
577         ListType::iterator it  = forkedCalls.begin();
578         ListType::iterator end = forkedCalls.end();
579         while (it != end) {
580                 ForkedProcessPtr actCall = *it;
581                 bool remove_it = false;
582
583 #if defined(_WIN32)
584                 HANDLE const hProcess = HANDLE(actCall->pid());
585
586                 DWORD const wait_status = ::WaitForSingleObject(hProcess, 0);
587
588                 switch (wait_status) {
589                 case WAIT_TIMEOUT:
590                         // Still running
591                         break;
592                 case WAIT_OBJECT_0: {
593                         DWORD exit_code = 0;
594                         if (!GetExitCodeProcess(hProcess, &exit_code)) {
595                                 lyxerr << "GetExitCodeProcess failed waiting for child\n"
596                                        << getChildErrorMessage() << endl;
597                                 // Child died, so pretend it returned 1
598                                 actCall->setRetValue(1);
599                         } else {
600                                 actCall->setRetValue(exit_code);
601                         }
602                         CloseHandle(hProcess);
603                         remove_it = true;
604                         break;
605                 }
606                 case WAIT_FAILED:
607                         lyxerr << "WaitForSingleObject failed waiting for child\n"
608                                << getChildErrorMessage() << endl;
609                         actCall->setRetValue(1);
610                         CloseHandle(hProcess);
611                         remove_it = true;
612                         break;
613                 }
614 #else
615                 pid_t pid = actCall->pid();
616                 int stat_loc;
617                 pid_t const waitrpid = waitpid(pid, &stat_loc, WNOHANG);
618
619                 if (waitrpid == -1) {
620                         lyxerr << "LyX: Error waiting for child: "
621                                << strerror(errno) << endl;
622
623                         // Child died, so pretend it returned 1
624                         actCall->setRetValue(1);
625                         remove_it = true;
626
627                 } else if (waitrpid == 0) {
628                         // Still running. Move on to the next child.
629
630                 } else if (WIFEXITED(stat_loc)) {
631                         // Ok, the return value goes into retval.
632                         actCall->setRetValue(WEXITSTATUS(stat_loc));
633                         remove_it = true;
634
635                 } else if (WIFSIGNALED(stat_loc)) {
636                         // Child died, so pretend it returned 1
637                         actCall->setRetValue(1);
638                         remove_it = true;
639
640                 } else if (WIFSTOPPED(stat_loc)) {
641                         lyxerr << "LyX: Child (pid: " << pid
642                                << ") stopped on signal "
643                                << WSTOPSIG(stat_loc)
644                                << ". Waiting for child to finish." << endl;
645
646                 } else {
647                         lyxerr << "LyX: Something rotten happened while "
648                                 "waiting for child " << pid << endl;
649
650                         // Child died, so pretend it returned 1
651                         actCall->setRetValue(1);
652                         remove_it = true;
653                 }
654 #endif
655
656                 if (remove_it) {
657                         forkedCalls.erase(it);
658                         actCall->emitSignal();
659
660                         /* start all over: emitting the signal can result
661                          * in changing the list (Ab)
662                          */
663                         it = forkedCalls.begin();
664                 } else {
665                         ++it;
666                 }
667         }
668 }
669
670
671 // Kill the process prematurely and remove it from the list
672 // within tolerance secs
673 void kill(pid_t pid, int tolerance)
674 {
675         ListType::iterator it = find_pid(pid);
676         if (it == forkedCalls.end())
677                 return;
678
679         (*it)->kill(tolerance);
680         forkedCalls.erase(it);
681 }
682
683 } // namespace ForkedCallsController
684
685 } // namespace support
686 } // namespace lyx