]> git.lyx.org Git - lyx.git/blob - src/support/ForkedCalls.cpp
592053b6cf23a6fe04d03ed14f5fa976f5380c7b
[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 <boost/bind.hpp>
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 using boost::bind;
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(boost::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())
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 /* FIXME fork() is not usable on Mac OS X 10.6 (snow leopard) 
196  *   Use something else like threads.
197  *
198  * Since I do not know how to determine at run time what is the OS X
199  * version, I just disable forking altogether for now (JMarc)
200  */
201 #if !defined (HAVE_FORK) || defined(__APPLE__)
202         return -1;
203 #else
204         pid_t pid = ::fork();
205         if (pid == 0)
206                 IAmAChild = true;
207         return pid;
208 #endif
209 }
210
211
212 // Wait for child process to finish. Returns returncode from child.
213 int ForkedProcess::waitForChild()
214 {
215         // We'll pretend that the child returns 1 on all error conditions.
216         retval_ = 1;
217
218 #if defined (_WIN32)
219         HANDLE const hProcess = HANDLE(pid_);
220
221         DWORD const wait_status = ::WaitForSingleObject(hProcess, INFINITE);
222
223         switch (wait_status) {
224         case WAIT_OBJECT_0: {
225                 DWORD exit_code = 0;
226                 if (!GetExitCodeProcess(hProcess, &exit_code)) {
227                         lyxerr << "GetExitCodeProcess failed waiting for child\n"
228                                << getChildErrorMessage() << endl;
229                 } else
230                         retval_ = exit_code;
231                 break;
232         }
233         case WAIT_FAILED:
234                 lyxerr << "WaitForSingleObject failed waiting for child\n"
235                        << getChildErrorMessage() << endl;
236                 break;
237         }
238
239 #else
240         int status;
241         bool wait = true;
242         while (wait) {
243                 pid_t waitrpid = waitpid(pid_, &status, WUNTRACED);
244                 if (waitrpid == -1) {
245                         lyxerr << "LyX: Error waiting for child:"
246                                << strerror(errno) << endl;
247                         wait = false;
248                 } else if (WIFEXITED(status)) {
249                         // Child exited normally. Update return value.
250                         retval_ = WEXITSTATUS(status);
251                         wait = false;
252                 } else if (WIFSIGNALED(status)) {
253                         lyxerr << "LyX: Child didn't catch signal "
254                                << WTERMSIG(status)
255                                << "and died. Too bad." << endl;
256                         wait = false;
257                 } else if (WIFSTOPPED(status)) {
258                         lyxerr << "LyX: Child (pid: " << pid_
259                                << ") stopped on signal "
260                                << WSTOPSIG(status)
261                                << ". Waiting for child to finish." << endl;
262                 } else {
263                         lyxerr << "LyX: Something rotten happened while "
264                                 "waiting for child " << pid_ << endl;
265                         wait = false;
266                 }
267         }
268 #endif
269         return retval_;
270 }
271
272
273 /////////////////////////////////////////////////////////////////////
274 //
275 // ForkedCall
276 //
277 /////////////////////////////////////////////////////////////////////
278
279
280 int ForkedCall::startScript(Starttype wait, string const & what)
281 {
282         if (wait != Wait) {
283                 retval_ = startScript(what, SignalTypePtr());
284                 return retval_;
285         }
286
287         command_ = what;
288         signal_.reset();
289         return run(Wait);
290 }
291
292
293 int ForkedCall::startScript(string const & what, SignalTypePtr signal)
294 {
295         command_ = what;
296         signal_  = signal;
297
298         return run(DontWait);
299 }
300
301
302 // generate child in background
303 int ForkedCall::generateChild()
304 {
305         string line = trim(command_);
306         if (line.empty())
307                 return 1;
308
309         // Split the input command up into an array of words stored
310         // in a contiguous block of memory. The array contains pointers
311         // to each word.
312         // Don't forget the terminating `\0' character.
313         char const * const c_str = line.c_str();
314         vector<char> vec(c_str, c_str + line.size() + 1);
315
316         // Splitting the command up into an array of words means replacing
317         // the whitespace between words with '\0'. Life is complicated
318         // however, because words protected by quotes can contain whitespace.
319         //
320         // The strategy we adopt is:
321         // 1. If we're not inside quotes, then replace white space with '\0'.
322         // 2. If we are inside quotes, then don't replace the white space
323         //    but do remove the quotes themselves. We do this naively by
324         //    replacing the quote with '\0' which is fine if quotes
325         //    delimit the entire word.
326         char inside_quote = 0;
327         vector<char>::iterator it = vec.begin();
328         vector<char>::iterator const end = vec.end();
329         for (; it != end; ++it) {
330                 char const c = *it;
331                 if (!inside_quote) {
332                         if (c == ' ')
333                                 *it = '\0';
334                         else if (c == '\'' || c == '"') {
335 #if defined (_WIN32)
336                                 // How perverse!
337                                 // spawnvp *requires* the quotes or it will
338                                 // split the arg at the internal whitespace!
339                                 // Make shure the quote is a DOS-style one.
340                                 *it = '"';
341 #else
342                                 *it = '\0';
343 #endif
344                                 inside_quote = c;
345                         }
346                 } else if (c == inside_quote) {
347 #if defined (_WIN32)
348                         *it = '"';
349 #else
350                         *it = '\0';
351 #endif
352                         inside_quote = 0;
353                 }
354         }
355
356         // Build an array of pointers to each word.
357         it = vec.begin();
358         vector<char *> argv;
359         char prev = '\0';
360         for (; it != end; ++it) {
361                 if (*it != '\0' && prev == '\0')
362                         argv.push_back(&*it);
363                 prev = *it;
364         }
365         argv.push_back(0);
366
367         // Debug output.
368         if (lyxerr.debugging(Debug::FILES)) {
369                 vector<char *>::iterator ait = argv.begin();
370                 vector<char *>::iterator const aend = argv.end();
371                 lyxerr << "<command>\n\t" << line
372                        << "\n\tInterpretted as:\n\n";
373                 for (; ait != aend; ++ait)
374                         if (*ait)
375                                 lyxerr << '\t'<< *ait << '\n';
376                 lyxerr << "</command>" << endl;
377         }
378
379 #ifdef _WIN32
380         pid_t const cpid = spawnvp(_P_NOWAIT, argv[0], &*argv.begin());
381 #else // POSIX
382         pid_t const cpid = ::fork();
383         if (cpid == 0) {
384                 // Child
385                 execvp(argv[0], &*argv.begin());
386
387                 // If something goes wrong, we end up here
388                 lyxerr << "execvp of \"" << command_ << "\" failed: "
389                        << strerror(errno) << endl;
390                 _exit(1);
391         }
392 #endif
393
394         if (cpid < 0) {
395                 // Error.
396                 lyxerr << "Could not fork: " << strerror(errno) << endl;
397         }
398
399         return cpid;
400 }
401
402
403 /////////////////////////////////////////////////////////////////////
404 //
405 // ForkedCallQueue
406 //
407 /////////////////////////////////////////////////////////////////////
408
409 namespace ForkedCallQueue {
410
411 /// A process in the queue
412 typedef pair<string, ForkedCall::SignalTypePtr> Process;
413 /** Add a process to the queue. Processes are forked sequentially
414  *  only one is running at a time.
415  *  Connect to the returned signal and you'll be informed when
416  *  the process has ended.
417  */
418 ForkedCall::SignalTypePtr add(string const & process);
419
420 /// in-progress queue
421 static queue<Process> callQueue_;
422
423 /// flag whether queue is running
424 static bool running_ = 0;
425
426 ///
427 void startCaller();
428 ///
429 void stopCaller();
430 ///
431 void callback(pid_t, int);
432
433 ForkedCall::SignalTypePtr add(string const & process)
434 {
435         ForkedCall::SignalTypePtr ptr;
436         ptr.reset(new ForkedCall::SignalType);
437         callQueue_.push(Process(process, ptr));
438         if (!running_)
439                 startCaller();
440         return ptr;
441 }
442
443
444 void callNext()
445 {
446         if (callQueue_.empty())
447                 return;
448         Process pro = callQueue_.front();
449         callQueue_.pop();
450         // Bind our chain caller
451         pro.second->connect(boost::bind(&ForkedCallQueue::callback, _1, _2));
452         ForkedCall call;
453         //If we fail to fork the process, then emit the signal
454         //to tell the outside world that it failed.
455         if (call.startScript(pro.first, pro.second) > 0)
456                 pro.second->operator()(0,1);
457 }
458
459
460 void callback(pid_t, int)
461 {
462         if (callQueue_.empty())
463                 stopCaller();
464         else
465                 callNext();
466 }
467
468
469 void startCaller()
470 {
471         LYXERR(Debug::GRAPHICS, "ForkedCallQueue: waking up");
472         running_ = true ;
473         callNext();
474 }
475
476
477 void stopCaller()
478 {
479         running_ = false ;
480         LYXERR(Debug::GRAPHICS, "ForkedCallQueue: I'm going to sleep");
481 }
482
483
484 bool running()
485 {
486         return running_;
487 }
488
489 } // namespace ForkedCallsQueue
490
491
492
493 /////////////////////////////////////////////////////////////////////
494 //
495 // ForkedCallsController
496 //
497 /////////////////////////////////////////////////////////////////////
498
499 #if defined(_WIN32)
500 string const getChildErrorMessage()
501 {
502         DWORD const error_code = ::GetLastError();
503
504         HLOCAL t_message = 0;
505         bool const ok = ::FormatMessage(
506                 FORMAT_MESSAGE_ALLOCATE_BUFFER |
507                 FORMAT_MESSAGE_FROM_SYSTEM,
508                 0, error_code,
509                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
510                 (LPTSTR) &t_message, 0, 0
511                 ) != 0;
512
513         ostringstream ss;
514         ss << "LyX: Error waiting for child: " << error_code;
515
516         if (ok) {
517                 ss << ": " << (LPTSTR)t_message;
518                 ::LocalFree(t_message);
519         } else
520                 ss << ": Error unknown.";
521
522         return ss.str();
523 }
524 #endif
525
526
527 namespace ForkedCallsController {
528
529 typedef boost::shared_ptr<ForkedProcess> ForkedProcessPtr;
530 typedef list<ForkedProcessPtr> ListType;
531 typedef ListType::iterator iterator;
532
533
534 /// The child processes
535 static ListType forkedCalls;
536
537 iterator find_pid(pid_t pid)
538 {
539         return find_if(forkedCalls.begin(), forkedCalls.end(),
540                        bind(equal_to<pid_t>(),
541                             bind(&ForkedCall::pid, _1),
542                             pid));
543 }
544
545
546 void addCall(ForkedProcess const & newcall)
547 {
548         forkedCalls.push_back(newcall.clone());
549 }
550
551
552 // Check the list of dead children and emit any associated signals.
553 void handleCompletedProcesses()
554 {
555         ListType::iterator it  = forkedCalls.begin();
556         ListType::iterator end = forkedCalls.end();
557         while (it != end) {
558                 ForkedProcessPtr actCall = *it;
559                 bool remove_it = false;
560
561 #if defined(_WIN32)
562                 HANDLE const hProcess = HANDLE(actCall->pid());
563
564                 DWORD const wait_status = ::WaitForSingleObject(hProcess, 0);
565
566                 switch (wait_status) {
567                 case WAIT_TIMEOUT:
568                         // Still running
569                         break;
570                 case WAIT_OBJECT_0: {
571                         DWORD exit_code = 0;
572                         if (!GetExitCodeProcess(hProcess, &exit_code)) {
573                                 lyxerr << "GetExitCodeProcess failed waiting for child\n"
574                                        << getChildErrorMessage() << endl;
575                                 // Child died, so pretend it returned 1
576                                 actCall->setRetValue(1);
577                         } else {
578                                 actCall->setRetValue(exit_code);
579                         }
580                         remove_it = true;
581                         break;
582                 }
583                 case WAIT_FAILED:
584                         lyxerr << "WaitForSingleObject failed waiting for child\n"
585                                << getChildErrorMessage() << endl;
586                         actCall->setRetValue(1);
587                         remove_it = true;
588                         break;
589                 }
590 #else
591                 pid_t pid = actCall->pid();
592                 int stat_loc;
593                 pid_t const waitrpid = waitpid(pid, &stat_loc, WNOHANG);
594
595                 if (waitrpid == -1) {
596                         lyxerr << "LyX: Error waiting for child: "
597                                << strerror(errno) << endl;
598
599                         // Child died, so pretend it returned 1
600                         actCall->setRetValue(1);
601                         remove_it = true;
602
603                 } else if (waitrpid == 0) {
604                         // Still running. Move on to the next child.
605
606                 } else if (WIFEXITED(stat_loc)) {
607                         // Ok, the return value goes into retval.
608                         actCall->setRetValue(WEXITSTATUS(stat_loc));
609                         remove_it = true;
610
611                 } else if (WIFSIGNALED(stat_loc)) {
612                         // Child died, so pretend it returned 1
613                         actCall->setRetValue(1);
614                         remove_it = true;
615
616                 } else if (WIFSTOPPED(stat_loc)) {
617                         lyxerr << "LyX: Child (pid: " << pid
618                                << ") stopped on signal "
619                                << WSTOPSIG(stat_loc)
620                                << ". Waiting for child to finish." << endl;
621
622                 } else {
623                         lyxerr << "LyX: Something rotten happened while "
624                                 "waiting for child " << pid << endl;
625
626                         // Child died, so pretend it returned 1
627                         actCall->setRetValue(1);
628                         remove_it = true;
629                 }
630 #endif
631
632                 if (remove_it) {
633                         forkedCalls.erase(it);
634                         actCall->emitSignal();
635
636                         /* start all over: emiting the signal can result
637                          * in changing the list (Ab)
638                          */
639                         it = forkedCalls.begin();
640                 } else {
641                         ++it;
642                 }
643         }
644 }
645
646
647 // Kill the process prematurely and remove it from the list
648 // within tolerance secs
649 void kill(pid_t pid, int tolerance)
650 {
651         ListType::iterator it = find_pid(pid);
652         if (it == forkedCalls.end())
653                 return;
654
655         (*it)->kill(tolerance);
656         forkedCalls.erase(it);
657 }
658
659 } // namespace ForkedCallsController
660
661 } // namespace support
662 } // namespace lyx