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