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