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