]> git.lyx.org Git - lyx.git/blob - src/support/ForkedCalls.cpp
Let paragraph::requestSpellcheck() consider contained insets
[lyx.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         // Make sure that a V2 python is run, if available.
309         string const line = cmd_prefix_ +
310                 (prefixIs(command_, "python -tt")
311                  ? os::python() + command_.substr(10) : command_);
312
313 #if !defined (_WIN32)
314         // POSIX
315
316         // Split the input command up into an array of words stored
317         // in a contiguous block of memory. The array contains pointers
318         // to each word.
319         // Don't forget the terminating `\0' character.
320         char const * const c_str = line.c_str();
321         vector<char> vec(c_str, c_str + line.size() + 1);
322
323         // Splitting the command up into an array of words means replacing
324         // the whitespace between words with '\0'. Life is complicated
325         // however, because words protected by quotes can contain whitespace.
326         //
327         // The strategy we adopt is:
328         // 1. If we're not inside quotes, then replace white space with '\0'.
329         // 2. If we are inside quotes, then don't replace the white space
330         //    but do remove the quotes themselves. We do this naively by
331         //    replacing the quote with '\0' which is fine if quotes
332         //    delimit the entire word. However, if quotes do not delimit the
333         //    entire word (i.e., open quote is inside word), simply discard
334         //    them such as not to break the current word.
335         char inside_quote = 0;
336         char c_before_open_quote = ' ';
337         vector<char>::iterator it = vec.begin();
338         vector<char>::iterator itc = vec.begin();
339         vector<char>::iterator const end = vec.end();
340         for (; it != end; ++it, ++itc) {
341                 char const c = *it;
342                 if (!inside_quote) {
343                         if (c == '\'' || c == '"') {
344                                 if (c_before_open_quote == ' ')
345                                         *itc = '\0';
346                                 else
347                                         --itc;
348                                 inside_quote = c;
349                         } else {
350                                 if (c == ' ')
351                                         *itc = '\0';
352                                 else
353                                         *itc = c;
354                                 c_before_open_quote = c;
355                         }
356                 } else if (c == inside_quote) {
357                         if (c_before_open_quote == ' ')
358                                 *itc = '\0';
359                         else
360                                 --itc;
361                         inside_quote = 0;
362                 } else
363                         *itc = c;
364         }
365
366         // Clear what remains.
367         for (; itc != end; ++itc)
368                 *itc = '\0';
369
370         // Build an array of pointers to each word.
371         it = vec.begin();
372         vector<char *> argv;
373         char prev = '\0';
374         for (; it != end; ++it) {
375                 if (*it != '\0' && prev == '\0')
376                         argv.push_back(&*it);
377                 prev = *it;
378         }
379         argv.push_back(nullptr);
380
381         // Debug output.
382         if (lyxerr.debugging(Debug::FILES)) {
383                 vector<char *>::iterator ait = argv.begin();
384                 vector<char *>::iterator const aend = argv.end();
385                 lyxerr << "<command>\n\t" << line
386                        << "\n\tInterpreted as:\n\n";
387                 for (; ait != aend; ++ait)
388                         if (*ait)
389                                 lyxerr << '\t'<< *ait << '\n';
390                 lyxerr << "</command>" << endl;
391         }
392
393         pid_t const cpid = ::fork();
394         if (cpid == 0) {
395                 // Child
396                 execvp(argv[0], &*argv.begin());
397
398                 // If something goes wrong, we end up here
399                 lyxerr << "execvp of \"" << command_ << "\" failed: "
400                        << strerror(errno) << endl;
401                 _exit(1);
402         }
403 #else
404         // Windows
405
406         pid_t cpid = -1;
407
408         STARTUPINFO startup;
409         PROCESS_INFORMATION process;
410
411         memset(&startup, 0, sizeof(STARTUPINFO));
412         memset(&process, 0, sizeof(PROCESS_INFORMATION));
413
414         startup.cb = sizeof(STARTUPINFO);
415
416         if (CreateProcess(0, (LPSTR)line.c_str(), 0, 0, FALSE,
417                 CREATE_NO_WINDOW, 0, 0, &startup, &process)) {
418                 CloseHandle(process.hThread);
419                 cpid = (pid_t)process.hProcess;
420         }
421 #endif
422
423         if (cpid < 0) {
424                 // Error.
425                 lyxerr << "Could not fork: " << strerror(errno) << endl;
426         }
427
428         return cpid;
429 }
430
431
432 /////////////////////////////////////////////////////////////////////
433 //
434 // ForkedCallQueue
435 //
436 /////////////////////////////////////////////////////////////////////
437
438 namespace ForkedCallQueue {
439
440 /// A process in the queue
441 typedef pair<string, ForkedCall::sigPtr> Process;
442
443 /// in-progress queue
444 static queue<Process> callQueue_;
445
446 /// flag whether queue is running
447 static bool running_ = false;
448
449 ///
450 void startCaller();
451 ///
452 void stopCaller();
453 ///
454 void callback(pid_t, int);
455
456 /** Add a process to the queue. Processes are forked sequentially
457  *  only one is running at a time.
458  *  Connect to the returned signal and you'll be informed when
459  *  the process has ended.
460  */
461 ForkedCall::sigPtr add(string const & process)
462 {
463         ForkedCall::sigPtr ptr;
464         ptr.reset(new ForkedCall::sig);
465         callQueue_.push(Process(process, ptr));
466         if (!running_)
467                 startCaller();
468         return ptr;
469 }
470
471
472 void callNext()
473 {
474         if (callQueue_.empty())
475                 return;
476         Process pro = callQueue_.front();
477         callQueue_.pop();
478         // Bind our chain caller
479         pro.second->connect(callback);
480         ForkedCall call;
481         //If we fail to fork the process, then emit the signal
482         //to tell the outside world that it failed.
483         if (call.startScript(pro.first, pro.second) > 0)
484                 pro.second->operator()(0,1);
485 }
486
487
488 void callback(pid_t, int)
489 {
490         if (callQueue_.empty())
491                 stopCaller();
492         else
493                 callNext();
494 }
495
496
497 void startCaller()
498 {
499         LYXERR(Debug::GRAPHICS, "ForkedCallQueue: waking up");
500         running_ = true ;
501         callNext();
502 }
503
504
505 void stopCaller()
506 {
507         running_ = false ;
508         LYXERR(Debug::GRAPHICS, "ForkedCallQueue: I'm going to sleep");
509 }
510
511
512 bool running()
513 {
514         return running_;
515 }
516
517 } // namespace ForkedCallQueue
518
519
520 /////////////////////////////////////////////////////////////////////
521 //
522 // ForkedCallsController
523 //
524 /////////////////////////////////////////////////////////////////////
525
526 #if defined(_WIN32)
527 string const getChildErrorMessage()
528 {
529         DWORD const error_code = ::GetLastError();
530
531         HLOCAL t_message = 0;
532         bool const ok = ::FormatMessage(
533                 FORMAT_MESSAGE_ALLOCATE_BUFFER |
534                 FORMAT_MESSAGE_FROM_SYSTEM,
535                 0, error_code,
536                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
537                 (LPTSTR) &t_message, 0, 0
538                 ) != 0;
539
540         ostringstream ss;
541         ss << "LyX: Error waiting for child: " << error_code;
542
543         if (ok) {
544                 ss << ": " << (LPTSTR)t_message;
545                 ::LocalFree(t_message);
546         } else
547                 ss << ": Error unknown.";
548
549         return ss.str();
550 }
551 #endif
552
553
554 namespace ForkedCallsController {
555
556 typedef shared_ptr<ForkedProcess> ForkedProcessPtr;
557 typedef list<ForkedProcessPtr> ListType;
558 typedef ListType::iterator iterator;
559
560
561 /// The child processes
562 static ListType forkedCalls;
563
564 iterator find_pid(pid_t pid)
565 {
566         return find_if(forkedCalls.begin(), forkedCalls.end(),
567                             lyx::bind(equal_to<pid_t>(),
568                             lyx::bind(&ForkedCall::pid, _1),
569                             pid));
570 }
571
572
573 void addCall(ForkedProcess const & newcall)
574 {
575         forkedCalls.push_back(newcall.clone());
576 }
577
578
579 // Check the list of dead children and emit any associated signals.
580 void handleCompletedProcesses()
581 {
582         ListType::iterator it  = forkedCalls.begin();
583         ListType::iterator end = forkedCalls.end();
584         while (it != end) {
585                 ForkedProcessPtr actCall = *it;
586                 bool remove_it = false;
587
588 #if defined(_WIN32)
589                 HANDLE const hProcess = HANDLE(actCall->pid());
590
591                 DWORD const wait_status = ::WaitForSingleObject(hProcess, 0);
592
593                 switch (wait_status) {
594                 case WAIT_TIMEOUT:
595                         // Still running
596                         break;
597                 case WAIT_OBJECT_0: {
598                         DWORD exit_code = 0;
599                         if (!GetExitCodeProcess(hProcess, &exit_code)) {
600                                 lyxerr << "GetExitCodeProcess failed waiting for child\n"
601                                        << getChildErrorMessage() << endl;
602                                 // Child died, so pretend it returned 1
603                                 actCall->setRetValue(1);
604                         } else {
605                                 actCall->setRetValue(exit_code);
606                         }
607                         CloseHandle(hProcess);
608                         remove_it = true;
609                         break;
610                 }
611                 case WAIT_FAILED:
612                         lyxerr << "WaitForSingleObject failed waiting for child\n"
613                                << getChildErrorMessage() << endl;
614                         actCall->setRetValue(1);
615                         CloseHandle(hProcess);
616                         remove_it = true;
617                         break;
618                 }
619 #else
620                 pid_t pid = actCall->pid();
621                 int stat_loc;
622                 pid_t const waitrpid = waitpid(pid, &stat_loc, WNOHANG);
623
624                 if (waitrpid == -1) {
625                         lyxerr << "LyX: Error waiting for child: "
626                                << strerror(errno) << endl;
627
628                         // Child died, so pretend it returned 1
629                         actCall->setRetValue(1);
630                         remove_it = true;
631
632                 } else if (waitrpid == 0) {
633                         // Still running. Move on to the next child.
634
635                 } else if (WIFEXITED(stat_loc)) {
636                         // Ok, the return value goes into retval.
637                         actCall->setRetValue(WEXITSTATUS(stat_loc));
638                         remove_it = true;
639
640                 } else if (WIFSIGNALED(stat_loc)) {
641                         // Child died, so pretend it returned 1
642                         actCall->setRetValue(1);
643                         remove_it = true;
644
645                 } else if (WIFSTOPPED(stat_loc)) {
646                         lyxerr << "LyX: Child (pid: " << pid
647                                << ") stopped on signal "
648                                << WSTOPSIG(stat_loc)
649                                << ". Waiting for child to finish." << endl;
650
651                 } else {
652                         lyxerr << "LyX: Something rotten happened while "
653                                 "waiting for child " << pid << endl;
654
655                         // Child died, so pretend it returned 1
656                         actCall->setRetValue(1);
657                         remove_it = true;
658                 }
659 #endif
660
661                 if (remove_it) {
662                         forkedCalls.erase(it);
663                         actCall->emitSignal();
664
665                         /* start all over: emitting the signal can result
666                          * in changing the list (Ab)
667                          */
668                         it = forkedCalls.begin();
669                 } else {
670                         ++it;
671                 }
672         }
673 }
674
675
676 // Kill the process prematurely and remove it from the list
677 // within tolerance secs
678 void kill(pid_t pid, int tolerance)
679 {
680         ListType::iterator it = find_pid(pid);
681         if (it == forkedCalls.end())
682                 return;
683
684         (*it)->kill(tolerance);
685         forkedCalls.erase(it);
686 }
687
688 } // namespace ForkedCallsController
689
690 } // namespace support
691 } // namespace lyx