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