Add an INSTALL file.
[tatoo.git] / remake.cpp
1 /**
2 @mainpage Remake, a build system that bridges the gap between make and redo.
3
4 As with <b>make</b>, <b>remake</b> uses a centralized rule file, which is
5 named <b>Remakefile</b>. It contains rules with a <em>make</em>-like
6 syntax:
7
8 @verbatim
9 target1 target2 ... : dependency1 dependency2 ...
10         shell script
11         that builds
12         the targets
13 @endverbatim
14
15 A target is known to be up-to-date if all its dependencies are. If it
16 has no known dependencies yet the file already exits, it is assumed to
17 be up-to-date. Obsolete targets are rebuilt thanks to the shell script
18 provided by the rule.
19
20 As with <b>redo</b>, <b>remake</b> supports dynamic dependencies in
21 addition to these static dependencies. Whenever a script executes
22 <tt>remake dependency4 dependency5 ...</tt>, these dependencies are
23 rebuilt if they are obsolete. (So <b>remake</b> acts like
24 <b>redo-ifchange</b>.) Moreover, these dependencies are stored in file
25 <b>.remake</b> so that they are remembered in subsequent runs. Note that
26 dynamic dependencies from previous runs are only used to decide whether a
27 target is obsolete; they are not automatically rebuilt when they are
28 obsolete yet a target depends on them. They will only be rebuilt once the
29 dynamic call to <b>remake</b> is executed.
30
31 In other words, the following two rules have almost the same behavior.
32
33 @verbatim
34 target1 target2 ... : dependency1 dependency2 ...
35         shell script
36
37 target1 target2 ... :
38         remake dependency1 dependency2 ...
39         shell script
40 @endverbatim
41
42 (There is a difference if the targets already exist, have never been
43 built before, and the dependencies are either younger or obsolete, since
44 the targets will not be rebuilt in the second case.)
45
46 The above usage of dynamic dependencies is hardly useful. Their strength
47 lies in the fact that they can be computed on the fly:
48
49 @verbatim
50 %.o : %.c
51         gcc -MMD -MF $1.d -o $1 -c ${1%.o}.c
52         remake -r < $1.d
53         rm $1.d
54
55 %.cmo : %.ml
56         ocamldep ${1%.cmo}.ml | remake -r $1
57         ocamlc -c ${1%.cmo}.ml
58
59 after.xml: before.xml rules.xsl
60         xsltproc --load-trace -o after.xml rules.xsl before.xml 2> deps
61         remake $(sed -n -e "\\,//,! s,^.*URL=\"\\([^\"]*\\).*\$,\\1,p" deps)
62         rm deps
63 @endverbatim
64
65 Note that the first rule fails if any of the header files included by
66 a C source file has to be automatically generated. In that case, one
67 should perform a first call to <b>remake</b> them before calling the
68 compiler. (Dependencies from several calls to <b>remake</b> are
69 cumulative, so they will all be remembered the next time.)
70
71 \section sec-usage Usage
72
73 Usage: <tt>remake <i>options</i> <i>targets</i></tt>
74
75 Options:
76
77 - <tt>-d</tt>: Echo script commands.
78 - <tt>-j[N]</tt>, <tt>--jobs=[N]</tt>: Allow N jobs at once; infinite jobs
79   with no argument.
80 - <tt>-k</tt>, <tt>--keep-going</tt>: Keep going when some targets cannot be made.
81 - <tt>-r</tt>: Look up targets from the dependencies on standard input.
82 - <tt>-s</tt>, <tt>--silent</tt>, <tt>--quiet</tt>: Do not echo targets.
83
84 \section sec-syntax Syntax
85
86 Lines starting with a space character or a tabulation are assumed to be rule
87 scripts. They are only allowed after a rule header.
88
89 Lines starting with <tt>#</tt> are considered to be comments and are ignored.
90 They do interrupt rule scripts though.
91
92 Any other line is either a rule header or a variable definition. If such a
93 line ends with a backslash, the following line break is ignored and the line
94 extends to the next one.
95
96 Rule headers are a nonempty list of names, followed by a colon, followed by
97 another list of names, possibly empty. Variable definitions are a single
98 name followed by equal followed by a list of names, possibly empty. Basically,
99 the syntax of a rule is as follows:
100
101 @verbatim
102 targets : prerequisites
103         shell script
104 @endverbatim
105
106 List of names are space-separated sequences of names. If a name contains a
107 space character, it should be put into double quotes. Names can not be any
108 of the following special characters <tt>:$(),="</tt>. Again, quotation
109 should be used. Quotation marks can be escaped by a backslash inside
110 quoted names.
111
112 \subsection sec-variables Variables
113
114 Variables can be used to factor lists of targets or dependencies. They are
115 expanded as they are encountered during <b>Remakefile</b> parsing.
116
117 @verbatim
118 VAR1 = c d
119 VAR2 = a $(VAR1) b
120 $(VAR2) e :
121 @endverbatim
122
123 Variables can be used inside rule scripts; they are available as non-exported
124 shell variables there.
125
126 \subsection sec-functions Built-in functions
127
128 <b>remake</b> also supports a few built-in functions inspired from <b>make</b>.
129
130 - <tt>$(addprefix <i>prefix</i>, <i>list</i>)</tt> returns the list obtained
131   by prepending its first argument to each element of its second argument.
132 - <tt>$(addsuffix <i>suffix</i>, <i>list</i>)</tt> returns the list obtained
133   by appending its first argument to each element of its second argument.
134
135 Note that functions are ignored inside scripts.
136
137 \section sec-semantics Semantics
138
139 \subsection src-obsolete When are targets obsolete?
140
141 A target is obsolete:
142
143 - if there is no file corresponding to the target, or to one of its siblings
144   in a multi-target rule,
145 - if any of its dynamic dependencies from a previous run or any of its static
146   prerequisites is obsolete,
147 - if the latest file corresponding to its siblings or itself is older than any
148   of its dynamic dependencies or static prerequisites.
149
150 In all the other cases, it is assumed to be up-to-date (and so are all its
151 siblings). Note that the last rule above says "latest" and not "earliest". While
152 it might cause some obsolete targets to go unnoticed in corner cases, it allows
153 for the following kind of rules:
154
155 @verbatim
156 config.h stamp-config_h: config.h.in config.status
157         ./config.status config.h
158         touch stamp-config_h
159 @endverbatim
160
161 A <tt>config.status</tt> file generally does not update header files (here
162 <tt>config.h</tt>) if they would not change. As a consequence, if not for the
163 <tt>stamp-config_h</tt> file above, a header would always be considered obsolete
164 once one of its prerequisites is modified. Note that touching <tt>config.h</tt>
165 rather than <tt>stamp-config_h</tt> would defeat the point of not updating it
166 in the first place, since the program files would need to be rebuilt.
167
168 Once all the static prerequisites of a target have been rebuilt, <b>remake</b>
169 checks if the target still needs to be built. If it was obsolete only because
170 its dependencies needed to be rebuilt and none of them changed, the target is
171 assumed to be up-to-date.
172
173 \subsection sec-rules How are targets (re)built?
174
175 There are two kinds of rules. If any of the targets or prerequisites contains
176 a <tt>%</tt> character, the rule is said to be <em>generic</em>. All the
177 targets of the rule shall then contain a single <tt>%</tt> character. All the
178 other rules are said to be <em>specific</em>.
179
180 A rule is said to <em>match</em> a given target:
181
182 - if it is specific and the target appears inside its target list,
183 - if it is generic and there is a way to replace the <tt>%</tt> character
184   from one of its targets so that it matches the given target.
185
186 When <b>remake</b> tries to build a given target, it looks for a specific rule
187 that matches it. If there is one and its script is nonempty, it uses it to
188 rebuild the target.
189
190 Otherwise, it looks for a generic rule that match the target. If there are
191 several matching rules, it chooses the one with the shortest pattern (and if
192 there are several ones, the earliest one). <b>remake</b> then looks for
193 specific rules that match each target of the generic rule. All the
194 prerequisites of these specific rules are added to those of the generic rule.
195 The script of the generic rule is used to build the target.
196
197 Example:
198
199 @verbatim
200 t%1 t2%: p1 p%2
201         commands building t%1 and t2%
202
203 t2z: p4
204         commands building t2z
205
206 ty1: p3
207
208 # t2x is built by the first rule (which also builds tx1) and its prerequisites are p1, px2
209 # t2y is built by the first rule (which also builds ty1) and its prerequisites are p1, py2, p3
210 # t2z is built by the second rule and its prerequisite is p4
211 @endverbatim
212
213 The set of rules from <b>Remakefile</b> is ill-formed:
214
215 - if any specific rule matching a target of the generic rule has a nonempty script,
216 - if any target of the generic rule is matched by a generic rule with a shorter pattern.
217
218 \section sec-compilation Compilation
219
220 - On Linux, MacOSX, and BSD: <tt>g++ -o remake remake.cpp</tt>
221 - On Windows: <tt>g++ -o remake.exe remake.cpp -lws2_32</tt>
222
223 Installing <b>remake</b> is needed only if <b>Remakefile</b> does not
224 specify the path to the executable for its recursive calls. Thanks to its
225 single source file, <b>remake</b> can be shipped inside other packages and
226 built at configuration time.
227
228 \section sec-differences Differences with other build systems
229
230 Differences with <b>make</b>:
231
232 - Dynamic dependencies are supported.
233 - For rules with multiple targets, the shell script is executed only once
234   and is assumed to build all the targets. There is no need for
235   convoluted rules that are robust enough for parallel builds. For generic
236   rules, this is similar to the behavior of pattern rules from <b>gmake</b>.
237 - As with <b>redo</b>, only one shell is run when executing a script,
238   rather than one per script line. Note that the shells are run with
239   option <tt>-e</tt>, thus causing them to exit as soon as an error is
240   encountered.
241 - The dependencies of generic rules (known as implicit rules in make lingo)
242   are not used to decide between several of them. <b>remake</b> does not
243   select one for which it could satisfy the dependencies.
244 - Variables and built-in functions are expanded as they are encountered
245   during <b>Remakefile</b> parsing.
246
247 Differences with <b>redo</b>:
248
249 - As with <b>make</b>, it is possible to write the following kind of rules
250   in <b>remake</b>.
251 @verbatim
252 Remakefile: Remakefile.in ./config.status
253         ./config.status Remakefile
254 @endverbatim
255 - If a target is already built the first time <b>remake</b> runs, it still
256   uses the static prerequisites of rules mentioning it to check whether it
257   needs to be rebuilt. It does not assume it to be up-to-date. As with
258   <b>redo</b> though, if its obsolete status would be due to a dynamic
259   dependency, it will go unnoticed; it should be removed beforehand.
260 - <b>remake</b> has almost no features: no checksum-based dependencies, no
261   compatibility with token servers, etc.
262
263 Differences with both <b>make</b> and <b>redo</b>:
264
265 - Multiple targets are supported.
266 - When executing shell scripts, positional variables <tt>$1</tt>,
267   <tt>$2</tt>, etc, point to the target names of the rule obtained after
268   substituting <tt>%</tt>. No other variables are defined.
269
270 \section sec-limitations Limitations
271
272 - When the user or a script calls <b>remake</b>, the current working
273   directory should be the one containing <b>Remakefile</b> (and thus
274   <b>.remake</b> too).
275 - Some cases of ill-formed rules are not caught by <b>remake</b> and can
276   thus lead to unpredictable behaviors.
277
278 \section sec-links Links
279
280 @see http://cr.yp.to/redo.html for the philosophy of <b>redo</b> and
281 https://github.com/apenwarr/redo for an implementation and some comprehensive documentation.
282
283 \section sec-licensing Licensing
284
285 @author Guillaume Melquiond
286 @version 0.5
287 @date 2012-2013
288 @copyright
289 This program is free software: you can redistribute it and/or modify
290 it under the terms of the GNU General Public License as published by
291 the Free Software Foundation, either version 3 of the License, or
292 (at your option) any later version.
293 \n
294 This program is distributed in the hope that it will be useful,
295 but WITHOUT ANY WARRANTY; without even the implied warranty of
296 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
297 GNU General Public License for more details.
298 */
299
300 #ifdef _WIN32
301 #define WIN32_LEAN_AND_MEAN
302 #define WINDOWS
303 #endif
304
305 #include <fstream>
306 #include <iostream>
307 #include <list>
308 #include <map>
309 #include <set>
310 #include <sstream>
311 #include <string>
312 #include <vector>
313 #include <cassert>
314 #include <cstdlib>
315 #include <ctime>
316 #include <errno.h>
317 #include <fcntl.h>
318 #include <signal.h>
319 #include <unistd.h>
320 #include <sys/stat.h>
321 #include <sys/types.h>
322
323 #ifdef __APPLE__
324 #define MACOSX
325 #endif
326
327 #ifdef __linux__
328 #define LINUX
329 #endif
330
331 #ifdef WINDOWS
332 #include <windows.h>
333 #include <winbase.h>
334 #include <winsock2.h>
335 #define pid_t HANDLE
336 typedef SOCKET socket_t;
337 #else
338 #include <sys/socket.h>
339 #include <sys/un.h>
340 #include <sys/wait.h>
341 typedef int socket_t;
342 enum { INVALID_SOCKET = -1 };
343 #endif
344
345 #if defined(WINDOWS) || defined(MACOSX)
346 enum { MSG_NOSIGNAL = 0 };
347 #endif
348
349 typedef std::list<std::string> string_list;
350
351 typedef std::set<std::string> string_set;
352
353 /**
354  * Reference-counted shared object.
355  * @note The default constructor delays the creation of the object until it
356  *       is first dereferenced.
357  */
358 template<class T>
359 struct ref_ptr
360 {
361         struct content
362         {
363                 size_t cnt;
364                 T val;
365                 content(): cnt(1) {}
366                 content(T const &t): cnt(1), val(t) {}
367         };
368         mutable content *ptr;
369         ref_ptr(): ptr(NULL) {}
370         ref_ptr(T const &t): ptr(new content(t)) {}
371         ref_ptr(ref_ptr const &p): ptr(p.ptr) { if (ptr) ++ptr->cnt; }
372         ~ref_ptr() { if (ptr && --ptr->cnt == 0) delete ptr; }
373         ref_ptr &operator=(ref_ptr const &p)
374         {
375                 if (ptr == p.ptr) return *this;
376                 if (ptr && --ptr->cnt == 0) delete ptr;
377                 ptr = p.ptr;
378                 if (ptr) ++ptr->cnt;
379                 return *this;
380         }
381         T &operator*() const
382         {
383                 if (!ptr) ptr = new content;
384                 return ptr->val;
385         }
386         T *operator->() const { return &**this; }
387 };
388
389 struct dependency_t
390 {
391         string_list targets;
392         string_set deps;
393 };
394
395 typedef std::map<std::string, ref_ptr<dependency_t> > dependency_map;
396
397 typedef std::map<std::string, string_list> variable_map;
398
399 /**
400  * Build status of a target.
401  */
402 enum status_e
403 {
404         Uptodate, ///< Target is up-to-date.
405         Todo,     ///< Target is missing or obsolete.
406         Recheck,  ///< Target has an obsolete dependency.
407         Running,  ///< Target is being rebuilt.
408         Remade,   ///< Target was successfully rebuilt.
409         Failed    ///< Build failed for target.
410 };
411
412 /**
413  * Build status of a target.
414  */
415 struct status_t
416 {
417         status_e status; ///< Actual status.
418         time_t last;     ///< Last-modified date.
419 };
420
421 typedef std::map<std::string, status_t> status_map;
422
423 /**
424  * A rule loaded from Remakefile.
425  */
426 struct rule_t
427 {
428         string_list targets; ///< Files produced by this rule.
429         string_list deps;    ///< Files used for an implicit call to remake at the start of the script.
430         std::string script;  ///< Shell script for building the targets.
431 };
432
433 typedef std::list<rule_t> rule_list;
434
435 typedef std::map<std::string, ref_ptr<rule_t> > rule_map;
436
437 typedef std::map<int, string_list> job_targets_map;
438
439 typedef std::map<int, variable_map> job_variables_map;
440
441 typedef std::map<pid_t, int> pid_job_map;
442
443 /**
444  * Client waiting for a request complete.
445  *
446  * There are two kinds of clients:
447  * - real clients, which are instances of remake created by built scripts,
448  * - pseudo clients, which are created by the server to build specific targets.
449  *
450  * Among pseudo clients, there are two categories:
451  * - original clients, which are created for the targets passed on the
452  *   command line by the user or for the initial regeneration of the rule file,
453  * - dependency clients, which are created to handle rules that have
454  *   explicit dependencies and thus to emulate a call to remake.
455  */
456 struct client_t
457 {
458         socket_t socket;     ///< Socket used to reply to the client (invalid for pseudo clients).
459         int job_id;          ///< Job for which the built script called remake and spawned the client (negative for original clients).
460         bool failed;         ///< Whether some targets failed in mode -k.
461         string_list pending; ///< Targets not yet started.
462         string_set running;  ///< Targets being built.
463         rule_t *delayed;     ///< Rule that implicitly created a dependency client, and which script has to be started on request completion.
464         variable_map variables; ///< Variable that are passed on the command line of a remake invocation.
465         client_t(): socket(INVALID_SOCKET), job_id(-1), failed(false), delayed(NULL) {}
466 };
467
468 typedef std::list<client_t> client_list;
469
470 /**
471  * Map from variable names to their content.
472  */
473 static variable_map variables;
474
475 /**
476  * Precomputed variable assignments for shell usage.
477  */
478 static std::string variable_block;
479
480 /**
481  * Map from targets to their known dependencies.
482  */
483 static dependency_map dependencies;
484
485 /**
486  * Map from targets to their build status.
487  */
488 static status_map status;
489
490 /**
491  * Set of generic rules loaded from Remakefile.
492  */
493 static rule_list generic_rules;
494
495 /**
496  * Map from targets to specific rules loaded from Remakefile.
497  */
498 static rule_map specific_rules;
499
500 /**
501  * Map from jobs to targets being built.
502  */
503 static job_targets_map job_targets;
504
505 /**
506  * Map from jobs to job specific variables
507  */
508 static job_variables_map job_variables;
509
510 /**
511  * Map from jobs to shell pids.
512  */
513 static pid_job_map job_pids;
514
515 /**
516  * List of clients waiting for a request to complete.
517  * New clients are put to front, so that the build process is depth-first.
518  */
519 static client_list clients;
520
521 /**
522  * Maximum number of parallel jobs (non-positive if unbounded).
523  * Can be modified by the -j option.
524  */
525 static int max_active_jobs = 1;
526
527 /**
528  * Whether to keep building targets in case of failure.
529  * Can be modified by the -k option.
530  */
531 static bool keep_going = false;
532
533 /**
534  * Number of jobs currently running:
535  * - it increases when a process is created in #run_script,
536  * - it decreases when a completion message is received in #finalize_job.
537  *
538  * @note There might be some jobs running while #clients is empty.
539  *       Indeed, if a client requested two targets to be rebuilt, if they
540  *       are running concurrently, if one of them fails, the client will
541  *       get a failure notice and might terminate before the other target
542  *       finishes.
543  */
544 static int running_jobs = 0;
545
546 /**
547  * Number of jobs currently waiting for a build request to finish:
548  * - it increases when a build request is received in #accept_client
549  *   (since the client is presumably waiting for the reply),
550  * - it decreases when a reply is sent in #complete_request.
551  */
552 static int waiting_jobs = 0;
553
554 /**
555  * Global counter used to produce increasing job numbers.
556  * @see job_targets
557  */
558 static int job_counter = 0;
559
560 /**
561  * Socket on which the server listens for client request.
562  */
563 static socket_t socket_fd;
564
565 /**
566  * Whether the request of an original client failed.
567  */
568 static bool build_failure;
569
570 /**
571  * Name of the server socket in the file system.
572  */
573 static char *socket_name;
574
575 /**
576  * Name of the first target of the first specific rule, used for default run.
577  */
578 static std::string first_target;
579
580 /**
581  * Whether a short message should be displayed for each target.
582  */
583 static bool show_targets = true;
584
585 /**
586  * Whether script commands are echoed.
587  */
588 static bool echo_scripts = false;
589
590 static time_t now = time(NULL);
591
592 static std::string working_dir;
593
594 #ifndef WINDOWS
595 static volatile sig_atomic_t got_SIGCHLD = 0;
596
597 static void child_sig_handler(int)
598 {
599         got_SIGCHLD = 1;
600 }
601 #endif
602
603 struct log
604 {
605         bool active, open;
606         int depth;
607         log(): active(false), open(false), depth(0)
608         {
609         }
610         std::ostream &operator()()
611         {
612                 if (open) std::cerr << std::endl;
613                 assert(depth >= 0);
614                 std::cerr << std::string(depth * 2, ' ');
615                 open = false;
616                 return std::cerr;
617         }
618         std::ostream &operator()(bool o)
619         {
620                 if (o && open) std::cerr << std::endl;
621                 if (!o) --depth;
622                 assert(depth >= 0);
623                 if (o || !open) std::cerr << std::string(depth * 2, ' ');
624                 if (o) ++depth;
625                 open = o;
626                 return std::cerr;
627         }
628 };
629
630 log debug;
631
632 struct log_auto_close
633 {
634         bool still_open;
635         log_auto_close(): still_open(true)
636         {
637         }
638         ~log_auto_close()
639         {
640                 if (debug.active && still_open) debug(false) << "done\n";
641         }
642 };
643
644 #define DEBUG if (debug.active) debug()
645 #define DEBUG_open log_auto_close auto_close; if (debug.active) debug(true)
646 #define DEBUG_close if ((auto_close.still_open = false), debug.active) debug(false)
647
648 /**
649  * Return the original string if it does not contain any special characters,
650  * a quoted and escaped string otherwise.
651  */
652 static std::string escape_string(std::string const &s)
653 {
654         char const *quoted_char = ",: '";
655         char const *escaped_char = "\"\\$!";
656         bool need_quotes = false;
657         size_t len = s.length(), nb = len;
658         for (size_t i = 0; i < len; ++i)
659         {
660                 if (strchr(quoted_char, s[i])) need_quotes = true;
661                 if (strchr(escaped_char, s[i])) ++nb;
662         }
663         if (nb != len) need_quotes = true;
664         if (!need_quotes) return s;
665         std::string t(nb + 2, '\\');
666         t[0] = '"';
667         for (size_t i = 0, j = 1; i < len; ++i, ++j)
668         {
669                 if (strchr(escaped_char, s[i])) ++j;
670                 t[j] = s[i];
671         }
672         t[nb + 1] = '"';
673         return t;
674 }
675
676 /**
677  * Initialize #working_dir.
678  */
679 void init_working_dir(const char* argv0)
680 {
681         char buf[1024];
682 #ifdef WINDOWS
683         char const *delim = "/\\";
684 #else
685         char delim = '/';
686 #endif
687         if (!getenv("REMAKE_SOCKET"))
688         {
689           std::string path = argv0;
690           
691           size_t found = path.find_last_of(delim);
692           if (found != std::string::npos)
693           {
694             path = path.substr(0, found);
695             std::cout << "Entering directory `" << path << "'" << std::endl;
696             if (chdir(path.c_str()))
697             {
698               perror("Failed to change working directory");
699             exit(EXIT_FAILURE);
700             }
701           }
702         }
703
704         char *res = getcwd(buf, sizeof(buf));
705         if (!res)
706         {
707                 perror("Failed to get working directory");
708                 exit(EXIT_FAILURE);
709         }
710         working_dir = buf;
711 }
712
713 /**
714  * Normalize an absolute path with respect to the working directory.
715  * Paths outside the working subtree are left unchanged.
716  */
717 static std::string normalize_abs(std::string const &s)
718 {
719         size_t l = working_dir.length();
720         if (s.compare(0, l, working_dir)) return s;
721         size_t ll = s.length();
722         if (ll == l) return ".";
723         if (s[l] != '/')
724         {
725                 size_t pos = s.rfind('/', l);
726                 assert(pos != std::string::npos);
727                 return s.substr(pos + 1);
728         }
729         if (ll == l + 1) return ".";
730         return s.substr(l + 1);
731 }
732
733 /**
734  * Normalize a target name.
735  */
736 static std::string normalize(std::string const &s)
737 {
738 #ifdef WINDOWS
739         char const *delim = "/\\";
740 #else
741         char delim = '/';
742 #endif
743         size_t prev = 0, len = s.length();
744         size_t pos = s.find_first_of(delim);
745         if (pos == std::string::npos) return s;
746         bool absolute = pos == 0;
747         string_list l;
748         for (;;)
749         {
750                 if (pos != prev)
751                 {
752                         std::string n = s.substr(prev, pos - prev);
753                         if (n == "..")
754                         {
755                                 if (!l.empty()) l.pop_back();
756                                 else if (!absolute)
757                                         return normalize(working_dir + '/' + s);
758                         }
759                         else if (n != ".")
760                                 l.push_back(n);
761                 }
762                 ++pos;
763                 if (pos >= len) break;
764                 prev = pos;
765                 pos = s.find_first_of(delim, prev);
766                 if (pos == std::string::npos) pos = len;
767         }
768         string_list::const_iterator i = l.begin(), i_end = l.end();
769         if (i == i_end) return absolute ? "/" : ".";
770         std::string n;
771         if (absolute) n.push_back('/');
772         n.append(*i);
773         for (++i; i != i_end; ++i)
774         {
775                 n.push_back('/');
776                 n.append(*i);
777         }
778         if (absolute) return normalize_abs(n);
779         return n;
780 }
781
782 /**
783  * Normalize the content of a list of targets.
784  */
785 static void normalize_list(string_list &l)
786 {
787         for (string_list::iterator i = l.begin(),
788              i_end = l.end(); i != i_end; ++i)
789         {
790                 *i = normalize(*i);
791         }
792 }
793
794 /**
795  * Skip spaces.
796  */
797 static void skip_spaces(std::istream &in)
798 {
799         char c;
800         while (strchr(" \t", (c = in.get()))) {}
801         if (in.good()) in.putback(c);
802 }
803
804 /**
805  * Skip end of line.
806  */
807 static void skip_eol(std::istream &in)
808 {
809         char c;
810         while (strchr("\r\n", (c = in.get()))) {}
811         if (in.good()) in.putback(c);
812 }
813
814 enum token_e { Word, Eol, Eof, Colon, Equal, Dollar, Rightpar, Comma };
815
816 /**
817  * Skip spaces and return the kind of the next token.
818  */
819 static token_e next_token(std::istream &in)
820 {
821         while (true)
822         {
823                 skip_spaces(in);
824                 char c = in.peek();
825                 if (!in.good()) return Eof;
826                 switch (c)
827                 {
828                 case ':': return Colon;
829                 case ',': return Comma;
830                 case '=': return Equal;
831                 case '$': return Dollar;
832                 case ')': return Rightpar;
833                 case '\r':
834                 case '\n':
835                         return Eol;
836                 case '\\':
837                         in.ignore(1);
838                         c = in.peek();
839                         if (c != '\r' && c != '\n')
840                         {
841                                 in.putback('\\');
842                                 return Word;
843                         }
844                         skip_eol(in);
845                         break;
846                 default:
847                         return Word;
848                 }
849         }
850 }
851
852 /**
853  * Read a (possibly quoted) word.
854  */
855 static std::string read_word(std::istream &in)
856 {
857         int c = in.get();
858         std::string res;
859         if (!in.good()) return res;
860         char const *separators = " \t\r\n:$(),=\"";
861         bool quoted = c == '"';
862         if (!quoted)
863         {
864                 if (strchr(separators, c))
865                 {
866                         in.putback(c);
867                         return res;
868                 }
869                 res += c;
870         }
871         while (true)
872         {
873                 c = in.get();
874                 if (!in.good()) return res;
875                 if (quoted)
876                 {
877                         if (c == '\\')
878                                 res += in.get();
879                         else if (c == '"')
880                                 return res;
881                         else
882                                 res += c;
883                 }
884                 else
885                 {
886                         if (strchr(separators, c))
887                         {
888                                 in.putback(c);
889                                 return res;
890                         }
891                         res += c;
892                 }
893         }
894 }
895
896 static string_list read_words(std::istream &in);
897
898 /**
899  * Execute a built-in function @a name and append its result to @a dest.
900  */
901 static void execute_function(std::istream &in, std::string const &name, string_list &dest)
902 {
903         if (false)
904         {
905                 error:
906                 std::cerr << "Failed to load rules: syntax error" << std::endl;
907                 exit(EXIT_FAILURE);
908         }
909         skip_spaces(in);
910         string_list fix = read_words(in);
911         if (next_token(in) != Comma) goto error;
912         in.ignore(1);
913         string_list names = read_words(in);
914         if (next_token(in) != Rightpar) goto error;
915         in.ignore(1);
916         size_t fixl = fix.size();
917         if (name == "addprefix")
918         {
919                 for (string_list::const_iterator i = names.begin(),
920                      i_end = names.end(); i != i_end; ++i)
921                 {
922                         if (!fixl)
923                         {
924                                 dest.push_back(*i);
925                                 continue;
926                         }
927                         string_list::const_iterator k = fix.begin();
928                         for (size_t j = 1; j != fixl; ++j)
929                         {
930                                 dest.push_back(*k++);
931                         }
932                         dest.push_back(*k++ + *i);
933                 }
934         }
935         else if (name == "addsuffix")
936         {
937                 for (string_list::const_iterator i = names.begin(),
938                      i_end = names.end(); i != i_end; ++i)
939                 {
940                         if (!fixl)
941                         {
942                                 dest.push_back(*i);
943                                 continue;
944                         }
945                         string_list::const_iterator k = fix.begin();
946                         dest.push_back(*i + *k++);
947                         for (size_t j = 1; j != fixl; ++j)
948                         {
949                                 dest.push_back(*k++);
950                         }
951                 }
952         }
953         else goto error;
954 }
955
956 /**
957  * Read a list of words, possibly executing functions.
958  */
959 static string_list read_words(std::istream &in)
960 {
961         if (false)
962         {
963                 error:
964                 std::cerr << "Failed to load rules: syntax error" << std::endl;
965                 exit(EXIT_FAILURE);
966         }
967         string_list res;
968         while (true)
969         {
970                 switch (next_token(in))
971                 {
972                 case Word:
973                         res.push_back(read_word(in));
974                         break;
975                 case Dollar:
976                 {
977                         in.ignore(1);
978                         if (in.get() != '(') goto error;
979                         std::string name = read_word(in);
980                         if (name.empty()) goto error;
981                         token_e tok = next_token(in);
982                         if (tok == Rightpar)
983                         {
984                                 in.ignore(1);
985                                 variable_map::const_iterator i = variables.find(name);
986                                 if (i != variables.end())
987                                         res.insert(res.end(), i->second.begin(), i->second.end());
988                         }
989                         else execute_function(in, name, res);
990                         break;
991                 }
992                 default:
993                         return res;
994                 }
995         }
996 }
997
998 /**
999  * Serialize a variable map.
1000  */
1001 std::string serialize_variables(variable_map &vars, char sep = ' ')
1002 {
1003   std::ostringstream buf;
1004   for(variable_map::const_iterator i = vars.begin(),
1005         i_end = vars.end(); i != i_end; ++i)
1006   {
1007     buf << i->first << '=';
1008     bool first = true;
1009     std::string val;
1010     for (string_list::const_iterator j = i->second.begin(),
1011            j_end = i->second.end(); j != j_end; ++j)
1012     {
1013       if (first) first = false;
1014       else val += " ";
1015       val += *j;
1016     }
1017     buf << escape_string(val) << sep;
1018   }
1019   std::string s = buf.str();
1020   return s;
1021 }
1022
1023 /**
1024  * Load dependencies from @a in.
1025  */
1026 static void load_dependencies(std::istream &in)
1027 {
1028         while (!in.eof())
1029         {
1030                 string_list targets = read_words(in);
1031                 if (targets.empty()) return;
1032                 DEBUG << "reading dependencies of target " << targets.front() << std::endl;
1033                 if (in.get() != ':')
1034                 {
1035                         std::cerr << "Failed to load database" << std::endl;
1036                         exit(EXIT_FAILURE);
1037                 }
1038                 ref_ptr<dependency_t> dep;
1039                 dep->targets = targets;
1040                 string_list d = read_words(in);
1041                 dep->deps.insert(d.begin(), d.end());
1042                 for (string_list::const_iterator i = targets.begin(),
1043                      i_end = targets.end(); i != i_end; ++i)
1044                 {
1045                         dependencies[*i] = dep;
1046                 }
1047                 skip_eol(in);
1048         }
1049 }
1050
1051 /**
1052  * Load known dependencies from file <tt>.remake</tt>.
1053  */
1054 static void load_dependencies()
1055 {
1056         DEBUG_open << "Loading database... ";
1057         std::ifstream in(".remake");
1058         if (!in.good())
1059         {
1060                 DEBUG_close << "not found\n";
1061                 return;
1062         }
1063         load_dependencies(in);
1064 }
1065
1066 /**
1067  * Read a rule starting with target @a first, if nonempty.
1068  * Store into #generic_rules or #specific_rules depending on its genericity.
1069  */
1070 static void load_rule(std::istream &in, std::string const &first)
1071 {
1072         DEBUG_open << "Reading rule for target " << first << "... ";
1073         if (false)
1074         {
1075                 error:
1076                 DEBUG_close << "failed\n";
1077                 std::cerr << "Failed to load rules: syntax error" << std::endl;
1078                 exit(EXIT_FAILURE);
1079         }
1080         rule_t rule;
1081
1082         // Read targets and check genericity.
1083         string_list targets = read_words(in);
1084         if (!first.empty()) targets.push_front(first);
1085         else if (targets.empty()) goto error;
1086         else DEBUG << "actual target: " << targets.front() << std::endl;
1087         bool generic = false;
1088         normalize_list(targets);
1089         for (string_list::const_iterator i = targets.begin(),
1090              i_end = targets.end(); i != i_end; ++i)
1091         {
1092                 if (i->empty()) goto error;
1093                 if ((i->find('%') != std::string::npos) != generic)
1094                 {
1095                         if (i == targets.begin()) generic = true;
1096                         else goto error;
1097                 }
1098         }
1099         std::swap(rule.targets, targets);
1100         skip_spaces(in);
1101         if (in.get() != ':') goto error;
1102
1103         // Read dependencies.
1104         rule.deps = read_words(in);
1105         normalize_list(rule.deps);
1106         skip_spaces(in);
1107         char c = in.get();
1108         if (c != '\r' && c != '\n') goto error;
1109         skip_eol(in);
1110
1111         // Read script.
1112         std::ostringstream buf;
1113         while (true)
1114         {
1115                 char c = in.get();
1116                 if (!in.good()) break;
1117                 if (c == '\t' || c == ' ')
1118                 {
1119                         in.get(*buf.rdbuf());
1120                         if (in.fail() && !in.eof()) in.clear();
1121                 }
1122                 else if (c == '\r' || c == '\n')
1123                         buf << c;
1124                 else
1125                 {
1126                         in.putback(c);
1127                         break;
1128                 }
1129         }
1130         rule.script = buf.str();
1131
1132         // Add generic rules to the correct set.
1133         if (generic)
1134         {
1135                 generic_rules.push_back(rule);
1136                 return;
1137         }
1138
1139         // Rules with a nonempty script lump all their targets in the same
1140         // dependency set, while other rules behave as if they had been
1141         // replicated for each of their targets.
1142         if (!rule.script.empty())
1143         {
1144                 ref_ptr<dependency_t> dep;
1145                 dep->targets = rule.targets;
1146                 dep->deps.insert(rule.deps.begin(), rule.deps.end());
1147                 for (string_list::const_iterator i = rule.targets.begin(),
1148                      i_end = rule.targets.end(); i != i_end; ++i)
1149                 {
1150                         ref_ptr<dependency_t> &d = dependencies[*i];
1151                         dep->deps.insert(d->deps.begin(), d->deps.end());
1152                         d = dep;
1153                 }
1154         }
1155         else
1156         {
1157                 for (string_list::const_iterator i = rule.targets.begin(),
1158                      i_end = rule.targets.end(); i != i_end; ++i)
1159                 {
1160                         ref_ptr<dependency_t> &dep = dependencies[*i];
1161                         if (dep->targets.empty()) dep->targets.push_back(*i);
1162                         dep->deps.insert(rule.deps.begin(), rule.deps.end());
1163                 }
1164         }
1165
1166         if (first_target.empty())
1167                 first_target = rule.targets.front();
1168
1169         ref_ptr<rule_t> r(rule);
1170         for (string_list::const_iterator i = rule.targets.begin(),
1171              i_end = rule.targets.end(); i != i_end; ++i)
1172         {
1173                 std::pair<rule_map::iterator,bool> j =
1174                         specific_rules.insert(std::make_pair(*i, r));
1175                 if (j.second) continue;
1176                 std::cerr << "Failed to load rules: " << *i
1177                         << " cannot be the target of several rules" << std::endl;
1178                 exit(EXIT_FAILURE);
1179         }
1180 }
1181
1182 /**
1183  * Save all the dependencies in file <tt>.remake</tt>.
1184  */
1185 static void save_dependencies()
1186 {
1187         DEBUG_open << "Saving database... ";
1188         std::ofstream db(".remake");
1189         while (!dependencies.empty())
1190         {
1191                 ref_ptr<dependency_t> dep = dependencies.begin()->second;
1192                 for (string_list::const_iterator i = dep->targets.begin(),
1193                      i_end = dep->targets.end(); i != i_end; ++i)
1194                 {
1195                         db << escape_string(*i) << ' ';
1196                         dependencies.erase(*i);
1197                 }
1198                 db << ':';
1199                 for (string_set::const_iterator i = dep->deps.begin(),
1200                      i_end = dep->deps.end(); i != i_end; ++i)
1201                 {
1202                         db << ' ' << escape_string(*i);
1203                 }
1204                 db << std::endl;
1205         }
1206 }
1207
1208 /**
1209  * Load rules.
1210  * If some rules have dependencies and non-generic targets, add these
1211  * dependencies to the targets.
1212  */
1213 static void load_rules()
1214 {
1215         DEBUG_open << "Loading rules... ";
1216         if (false)
1217         {
1218                 error:
1219                 std::cerr << "Failed to load rules: syntax error" << std::endl;
1220                 exit(EXIT_FAILURE);
1221         }
1222         std::ifstream in("Remakefile");
1223         if (!in.good())
1224         {
1225                 std::cerr << "Failed to load rules: no Remakefile found" << std::endl;
1226                 exit(EXIT_FAILURE);
1227         }
1228         skip_eol(in);
1229
1230         // Read rules
1231         while (in.good())
1232         {
1233                 char c = in.peek();
1234                 if (c == '#')
1235                 {
1236                         while (in.get() != '\n') {}
1237                         skip_eol(in);
1238                         continue;
1239                 }
1240                 if (c == ' ' || c == '\t') goto error;
1241                 token_e tok = next_token(in);
1242                 if (tok == Word)
1243                 {
1244                         std::string name = read_word(in);
1245                         if (name.empty()) goto error;
1246                         if (next_token(in) == Equal)
1247                         {
1248                                 in.ignore(1);
1249                                 DEBUG << "Assignment to variable " << name << std::endl;
1250                                 variables[name] = read_words(in);
1251                                 skip_eol(in);
1252                         }
1253                         else load_rule(in, name);
1254                 }
1255                 else if (tok == Dollar)
1256                         load_rule(in, std::string());
1257                 else goto error;
1258         }
1259
1260         // Generate script for variable assignment
1261         std::ostringstream buf;
1262         for (variable_map::const_iterator i = variables.begin(),
1263              i_end = variables.end(); i != i_end; ++i)
1264         {
1265                 std::ostringstream var;
1266                 bool first = true;
1267                 for (string_list::const_iterator j = i->second.begin(),
1268                      j_end = i->second.end(); j != j_end; ++j)
1269                 {
1270                         if (first) first = false;
1271                         else var << ' ';
1272                         var << *j;
1273                 }
1274                 buf << i->first << '=' << escape_string(var.str()) << std::endl;
1275         }
1276         variable_block = buf.str();
1277 }
1278
1279 /**
1280  * Substitute a pattern into a list of strings.
1281  */
1282 static void substitute_pattern(std::string const &pat, string_list const &src, string_list &dst)
1283 {
1284         for (string_list::const_iterator i = src.begin(),
1285              i_end = src.end(); i != i_end; ++i)
1286         {
1287                 size_t pos = i->find('%');
1288                 if (pos == std::string::npos)dst.push_back(*i);
1289                 else dst.push_back(i->substr(0, pos) + pat + i->substr(pos + 1));
1290         }
1291 }
1292
1293 /**
1294  * Find a generic rule matching @a target:
1295  * - the one leading to shorter matches has priority,
1296  * - among equivalent rules, the earliest one has priority.
1297  */
1298 static rule_t find_generic_rule(std::string const &target)
1299 {
1300         size_t tlen = target.length(), plen = tlen + 1;
1301         rule_t rule;
1302         for (rule_list::const_iterator i = generic_rules.begin(),
1303              i_end = generic_rules.end(); i != i_end; ++i)
1304         {
1305                 for (string_list::const_iterator j = i->targets.begin(),
1306                      j_end = i->targets.end(); j != j_end; ++j)
1307                 {
1308                         size_t len = j->length();
1309                         if (tlen < len) continue;
1310                         if (plen <= tlen - (len - 1)) continue;
1311                         size_t pos = j->find('%');
1312                         if (pos == std::string::npos) continue;
1313                         size_t len2 = len - (pos + 1);
1314                         if (j->compare(0, pos, target, 0, pos) ||
1315                             j->compare(pos + 1, len2, target, tlen - len2, len2))
1316                                 continue;
1317                         plen = tlen - (len - 1);
1318                         std::string pat = target.substr(pos, plen);
1319                         rule = rule_t();
1320                         rule.script = i->script;
1321                         substitute_pattern(pat, i->targets, rule.targets);
1322                         substitute_pattern(pat, i->deps, rule.deps);
1323                         break;
1324                 }
1325         }
1326         return rule;
1327 }
1328
1329 /**
1330  * Find a specific rule matching @a target. Return a generic one otherwise.
1331  * If there is both a specific rule with an empty script and a generic rule, the
1332  * generic one is returned after adding the dependencies of the specific one.
1333  */
1334 static rule_t find_rule(std::string const &target)
1335 {
1336         rule_map::const_iterator i = specific_rules.find(target),
1337                 i_end = specific_rules.end();
1338         // If there is a specific rule with a script, return it.
1339         if (i != i_end && !i->second->script.empty()) return *i->second;
1340         rule_t grule = find_generic_rule(target);
1341         // If there is no generic rule, return the specific rule (no script), if any.
1342         if (grule.targets.empty())
1343         {
1344                 if (i != i_end) return *i->second;
1345                 return grule;
1346         }
1347         // Optimize the lookup when there is only one target (alread looked up).
1348         if (grule.targets.size() == 1)
1349         {
1350                 if (i != i_end)
1351                         grule.deps.insert(grule.deps.end(),
1352                                 i->second->deps.begin(), i->second->deps.end());
1353                 return grule;
1354         }
1355         // Add the dependencies of the specific rules of every target to the
1356         // generic rule. If any of those rules has a nonempty script, error out.
1357         for (string_list::const_iterator j = grule.targets.begin(),
1358              j_end = grule.targets.end(); j != j_end; ++j)
1359         {
1360                 i = specific_rules.find(*j);
1361                 if (i == i_end) continue;
1362                 if (!i->second->script.empty()) return rule_t();
1363                 grule.deps.insert(grule.deps.end(),
1364                         i->second->deps.begin(), i->second->deps.end());
1365         }
1366         return grule;
1367 }
1368
1369 /**
1370  * Compute and memoize the status of @a target:
1371  * - if the file does not exist, the target is obsolete,
1372  * - if any dependency is obsolete or younger than the file, it is obsolete,
1373  * - otherwise it is up-to-date.
1374  *
1375  * @note With multiple targets, they all share the same status. (If one is
1376  *       obsolete, they all are.) For the second rule above, the latest target
1377  *       is chosen, not the oldest!
1378  */
1379 static status_t const &get_status(std::string const &target)
1380 {
1381         std::pair<status_map::iterator,bool> i =
1382                 status.insert(std::make_pair(target, status_t()));
1383         status_t &ts = i.first->second;
1384         if (!i.second) return ts;
1385         DEBUG_open << "Checking status of " << target << "... ";
1386         dependency_map::const_iterator j = dependencies.find(target);
1387         if (j == dependencies.end())
1388         {
1389                 struct stat s;
1390                 if (stat(target.c_str(), &s) != 0)
1391                 {
1392                         DEBUG_close << "missing\n";
1393                         ts.status = Todo;
1394                         ts.last = 0;
1395                         return ts;
1396                 }
1397                 DEBUG_close << "up-to-date\n";
1398                 ts.status = Uptodate;
1399                 ts.last = s.st_mtime;
1400                 return ts;
1401         }
1402         dependency_t const &dep = *j->second;
1403         status_e st = Uptodate;
1404         time_t latest = 0;
1405         for (string_list::const_iterator k = dep.targets.begin(),
1406              k_end = dep.targets.end(); k != k_end; ++k)
1407         {
1408                 struct stat s;
1409                 if (stat(k->c_str(), &s) != 0)
1410                 {
1411                         if (st == Uptodate) DEBUG_close << *k << " missing\n";
1412                         s.st_mtime = 0;
1413                         st = Todo;
1414                 }
1415                 status[*k].last = s.st_mtime;
1416                 if (s.st_mtime > latest) latest = s.st_mtime;
1417         }
1418         if (st == Todo) goto update;
1419         for (string_set::const_iterator k = dep.deps.begin(),
1420              k_end = dep.deps.end(); k != k_end; ++k)
1421         {
1422                 status_t const &ts_ = get_status(*k);
1423                 if (latest < ts_.last)
1424                 {
1425                         DEBUG_close << "older than " << *k << std::endl;
1426                         st = Todo;
1427                         goto update;
1428                 }
1429                 if (ts_.status == Uptodate) continue;
1430                 if (st == Uptodate)
1431                         DEBUG << "obsolete dependency " << *k << std::endl;
1432                 st = Recheck;
1433         }
1434         if (st == Uptodate) DEBUG_close << "all siblings up-to-date\n";
1435         update:
1436         for (string_list::const_iterator k = dep.targets.begin(),
1437              k_end = dep.targets.end(); k != k_end; ++k)
1438         {
1439                 status[*k].status = st;
1440         }
1441         return ts;
1442 }
1443
1444 /**
1445  * Change the status of @a target to #Remade or #Uptodate depending on whether
1446  * its modification time changed.
1447  */
1448 static void update_status(std::string const &target)
1449 {
1450         DEBUG_open << "Rechecking status of " << target << "... ";
1451         status_map::iterator i = status.find(target);
1452         assert (i != status.end());
1453         status_t &ts = i->second;
1454         ts.status = Remade;
1455         if (ts.last >= now)
1456         {
1457                 DEBUG_close << "possibly remade\n";
1458                 return;
1459         }
1460         struct stat s;
1461         if (stat(target.c_str(), &s) != 0)
1462         {
1463                 DEBUG_close << "missing\n";
1464                 ts.last = 0;
1465         }
1466         else if (s.st_mtime != ts.last)
1467         {
1468                 DEBUG_close << "remade\n";
1469                 ts.last = s.st_mtime;
1470         }
1471         else
1472         {
1473                 DEBUG_close << "unchanged\n";
1474                 ts.status = Uptodate;
1475         }
1476 }
1477
1478 /**
1479  * Check if all the prerequisites of @a target ended being up-to-date.
1480  */
1481 static bool still_need_rebuild(std::string const &target)
1482 {
1483         DEBUG_open << "Rechecking obsoleteness of " << target << "... ";
1484         status_map::const_iterator i = status.find(target);
1485         assert (i != status.end());
1486         if (i->second.status != Recheck) return true;
1487         dependency_map::const_iterator j = dependencies.find(target);
1488         assert(j != dependencies.end());
1489         dependency_t const &dep = *j->second;
1490         for (string_set::const_iterator k = dep.deps.begin(),
1491              k_end = dep.deps.end(); k != k_end; ++k)
1492         {
1493                 if (status[*k].status != Uptodate) return true;
1494         }
1495         for (string_list::const_iterator k = dep.targets.begin(),
1496              k_end = dep.targets.end(); k != k_end; ++k)
1497         {
1498                 status[*k].status = Uptodate;
1499         }
1500         DEBUG_close << "no longer obsolete\n";
1501         return false;
1502 }
1503
1504 /**
1505  * Handle job completion.
1506  */
1507 static void complete_job(int job_id, bool success)
1508 {
1509         DEBUG_open << "Completing job " << job_id << "... ";
1510         job_targets_map::iterator i = job_targets.find(job_id);
1511         assert(i != job_targets.end());
1512         string_list const &targets = i->second;
1513         if (success)
1514         {
1515                 for (string_list::const_iterator j = targets.begin(),
1516                      j_end = targets.end(); j != j_end; ++j)
1517                 {
1518                         update_status(*j);
1519                 }
1520         }
1521         else
1522         {
1523                 DEBUG_close << "failed\n";
1524                 std::cerr << "Failed to build";
1525                 for (string_list::const_iterator j = targets.begin(),
1526                      j_end = targets.end(); j != j_end; ++j)
1527                 {
1528                         status[*j].status = Failed;
1529                         std::cerr << ' ' << *j;
1530                         remove(j->c_str());
1531                 }
1532                 std::cerr << std::endl;
1533         }
1534         job_targets.erase(i);
1535 }
1536
1537 /**
1538  * Execute the script from @a rule.
1539  */
1540 static bool run_script(int job_id, rule_t const &rule)
1541 {
1542         if (show_targets)
1543         {
1544                 std::cout << "Building";
1545                 for (string_list::const_iterator i = rule.targets.begin(),
1546                      i_end = rule.targets.end(); i != i_end; ++i)
1547                 {
1548                         std::cout << ' ' << *i;
1549                 }
1550                 std::cout << std::endl;
1551         }
1552
1553         ref_ptr<dependency_t> dep;
1554         dep->targets = rule.targets;
1555         dep->deps.insert(rule.deps.begin(), rule.deps.end());
1556         for (string_list::const_iterator i = rule.targets.begin(),
1557              i_end = rule.targets.end(); i != i_end; ++i)
1558         {
1559                 dependencies[*i] = dep;
1560         }
1561
1562         DEBUG_open << "Starting script for job " << job_id << " with variables ("
1563                    << (job_id >= 0 ? serialize_variables(job_variables[job_id], ' ') : "")
1564                    << ") ... ";
1565 #ifdef WINDOWS
1566         HANDLE pfd[2];
1567         if (false)
1568         {
1569                 error2:
1570                 CloseHandle(pfd[0]);
1571                 CloseHandle(pfd[1]);
1572                 error:
1573                 DEBUG_close << "failed\n";
1574                 complete_job(job_id, false);
1575                 return false;
1576         }
1577         if (!CreatePipe(&pfd[0], &pfd[1], NULL, 0))
1578                 goto error;
1579         if (!SetHandleInformation(pfd[0], HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT))
1580                 goto error2;
1581         STARTUPINFO si;
1582         ZeroMemory(&si, sizeof(STARTUPINFO));
1583         si.cb = sizeof(STARTUPINFO);
1584         si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
1585         si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
1586         si.hStdInput = pfd[0];
1587         si.dwFlags |= STARTF_USESTDHANDLES;
1588         PROCESS_INFORMATION pi;
1589         ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
1590         std::ostringstream buf;
1591         buf << job_id;
1592         if (!SetEnvironmentVariable("REMAKE_JOB_ID", buf.str().c_str()))
1593                 goto error2;
1594         std::ostringstream argv;
1595         argv << "SH.EXE -e -s";
1596         if (echo_scripts) argv << " -v";
1597         for (string_list::const_iterator i = rule.targets.begin(),
1598              i_end = rule.targets.end(); i != i_end; ++i)
1599         {
1600                 argv << " \"" << escape_string(*i) << '"';
1601         }
1602         if (!CreateProcess(NULL, (char *)argv.str().c_str(), NULL, NULL,
1603             true, 0, NULL, NULL, &si, &pi))
1604         {
1605                 goto error2;
1606         }
1607         CloseHandle(pi.hThread);
1608         std::string script = variable_block
1609                 + (job_id >= 0 ? serialize_variables(job_variables[job_id], '\n') : "")
1610                 + rule.script;
1611         DWORD len = script.length(), wlen;
1612         if (!WriteFile(pfd[1], script.c_str(), len, &wlen, NULL) || wlen < len)
1613                 std::cerr << "Unexpected failure while sending script to shell" << std::endl;
1614         CloseHandle(pfd[0]);
1615         CloseHandle(pfd[1]);
1616         ++running_jobs;
1617         job_pids[pi.hProcess] = job_id;
1618         return true;
1619 #else
1620         int pfd[2];
1621         if (false)
1622         {
1623                 error2:
1624                 close(pfd[0]);
1625                 close(pfd[1]);
1626                 error:
1627                 DEBUG_close << "failed\n";
1628                 complete_job(job_id, false);
1629                 return false;
1630         }
1631         if (pipe(pfd) == -1)
1632                 goto error;
1633         if (pid_t pid = fork())
1634         {
1635                 if (pid == -1) goto error2;
1636                 std::string script = variable_block
1637                         + (job_id >= 0 ? serialize_variables(job_variables[job_id], '\n') : "")
1638                         + rule.script;
1639                 ssize_t len = script.length();
1640                 if (write(pfd[1], script.c_str(), len) < len)
1641                         std::cerr << "Unexpected failure while sending script to shell" << std::endl;
1642                 close(pfd[0]);
1643                 close(pfd[1]);
1644                 ++running_jobs;
1645                 job_pids[pid] = job_id;
1646                 return true;
1647         }
1648         // Child process starts here.
1649         std::ostringstream buf;
1650         buf << job_id;
1651         if (setenv("REMAKE_JOB_ID", buf.str().c_str(), 1))
1652                 _exit(EXIT_FAILURE);
1653         int num = echo_scripts ? 4 : 3;
1654         char const **argv = new char const *[num + rule.targets.size() + 1];
1655         argv[0] = "sh";
1656         argv[1] = "-e";
1657         argv[2] = "-s";
1658         if (echo_scripts) argv[3] = "-v";
1659         for (string_list::const_iterator i = rule.targets.begin(),
1660              i_end = rule.targets.end(); i != i_end; ++i, ++num)
1661         {
1662                 argv[num] = i->c_str();
1663         }
1664         argv[num] = NULL;
1665         if (pfd[0] != 0)
1666         {
1667                 dup2(pfd[0], 0);
1668                 close(pfd[0]);
1669         }
1670         close(pfd[1]);
1671         execv("/bin/sh", (char **)argv);
1672         _exit(EXIT_FAILURE);
1673 #endif
1674 }
1675
1676 /**
1677  * Create a job for @a target according to the loaded rules.
1678  * Mark all the targets from the rule as running and reset their dependencies.
1679  * If the rule has dependencies, create a new client to build them just
1680  * before @a current, and change @a current so that it points to it.
1681  */
1682 static bool start(std::string const &target, client_list::iterator &current)
1683 {
1684         DEBUG_open << "Starting job " << job_counter << " for " << target << "... ";
1685         rule_t rule = find_rule(target);
1686         if (rule.targets.empty())
1687         {
1688                 status[target].status = Failed;
1689                 DEBUG_close << "failed\n";
1690                 std::cerr << "No rule for building " << target << std::endl;
1691                 return false;
1692         }
1693         for (string_list::const_iterator i = rule.targets.begin(),
1694              i_end = rule.targets.end(); i != i_end; ++i)
1695         {
1696                 status[*i].status = Running;
1697         }
1698         int job_id = job_counter++;
1699         job_targets[job_id] = rule.targets;
1700         DEBUG << "Setting variables of job: " << job_id << " (spawn by: "
1701               << current->job_id << ") to "
1702               << serialize_variables(current->variables, ' ') << std::endl;
1703         job_variables[job_id] = current->variables;
1704         if (!rule.deps.empty())
1705         {
1706                 DEBUG << "Current client has job_id: " << job_id
1707                       << " and variables " << serialize_variables(current->variables, ' ')
1708                       << std::endl;
1709                 client_t dep_client = client_t();
1710                 dep_client.variables = current->variables;
1711                 current = clients.insert(current, dep_client);
1712                 current->job_id = job_id;
1713                 current->pending = rule.deps;
1714                 current->delayed = new rule_t(rule);
1715                 return true;
1716         }
1717         return run_script(job_id, rule);
1718 }
1719
1720 /**
1721  * Send a reply to a client then remove it.
1722  * If the client was a dependency client, start the actual script.
1723  */
1724 static void complete_request(client_t &client, bool success)
1725 {
1726         DEBUG_open << "Completing request from client of job " << client.job_id << "... ";
1727         if (client.delayed)
1728         {
1729                 assert(client.socket == INVALID_SOCKET);
1730                 if (success)
1731                 {
1732                         if (still_need_rebuild(client.delayed->targets.front()))
1733                                 run_script(client.job_id, *client.delayed);
1734                         else complete_job(client.job_id, true);
1735                 }
1736                 else complete_job(client.job_id, false);
1737                 delete client.delayed;
1738         }
1739         else if (client.socket != INVALID_SOCKET)
1740         {
1741                 char res = success ? 1 : 0;
1742                 send(client.socket, &res, 1, 0);
1743         #ifdef WINDOWS
1744                 closesocket(client.socket);
1745         #else
1746                 close(client.socket);
1747         #endif
1748                 --waiting_jobs;
1749         }
1750
1751         if (client.job_id < 0 && !success) build_failure = true;
1752 }
1753
1754 /**
1755  * Return whether there are slots for starting new jobs.
1756  */
1757 static bool has_free_slots()
1758 {
1759         if (max_active_jobs <= 0) return true;
1760         return running_jobs - waiting_jobs < max_active_jobs;
1761 }
1762
1763 /**
1764  * Update clients as long as there are free slots:
1765  * - check for running targets that have finished,
1766  * - start as many pending targets as allowed,
1767  * - complete the request if there are neither running nor pending targets
1768  *   left or if any of them failed.
1769  */
1770 static void update_clients()
1771 {
1772         DEBUG_open << "Updating clients... ";
1773         for (client_list::iterator i = clients.begin(), i_next = i,
1774              i_end = clients.end(); i != i_end && has_free_slots(); i = i_next)
1775         {
1776                 ++i_next;
1777                 DEBUG_open << "Handling client from job " << i->job_id << "... ";
1778                 if (false)
1779                 {
1780                         failed:
1781                         complete_request(*i, false);
1782                         clients.erase(i);
1783                         DEBUG_close << "failed\n";
1784                         continue;
1785                 }
1786
1787                 // Remove running targets that have finished.
1788                 for (string_set::iterator j = i->running.begin(), j_next = j,
1789                      j_end = i->running.end(); j != j_end; j = j_next)
1790                 {
1791                         ++j_next;
1792                         status_map::const_iterator k = status.find(*j);
1793                         assert(k != status.end());
1794                         switch (k->second.status)
1795                         {
1796                         case Running:
1797                                 break;
1798                         case Failed:
1799                                 if (!keep_going) goto failed;
1800                                 i->failed = true;
1801                                 // no break
1802                         case Uptodate:
1803                         case Remade:
1804                                 i->running.erase(j);
1805                                 break;
1806                         case Recheck:
1807                         case Todo:
1808                                 assert(false);
1809                         }
1810                 }
1811
1812                 // Start pending targets.
1813                 while (!i->pending.empty())
1814                 {
1815                         std::string target = i->pending.front();
1816                         i->pending.pop_front();
1817                         switch (get_status(target).status)
1818                         {
1819                         case Running:
1820                                 i->running.insert(target);
1821                                 break;
1822                         case Failed:
1823                                 pending_failed:
1824                                 if (!keep_going) goto failed;
1825                                 i->failed = true;
1826                                 // no break
1827                         case Uptodate:
1828                         case Remade:
1829                                 break;
1830                         case Recheck:
1831                         case Todo:
1832                                 client_list::iterator j = i;
1833                                 if (!start(target, i)) goto pending_failed;
1834                                 j->running.insert(target);
1835                                 if (!has_free_slots()) return;
1836                                 // Job start might insert a dependency client.
1837                                 i_next = i;
1838                                 ++i_next;
1839                                 break;
1840                         }
1841                 }
1842
1843                 // Try to complete request.
1844                 // (This might start a new job if it was a dependency client.)
1845                 if (i->running.empty())
1846                 {
1847                         if (i->failed) goto failed;
1848                         complete_request(*i, true);
1849                         clients.erase(i);
1850                         DEBUG_close << "finished\n";
1851                 }
1852         }
1853 }
1854
1855 /**
1856  * Create a named unix socket that listens for build requests. Also set
1857  * the REMAKE_SOCKET environment variable that will be inherited by all
1858  * the job scripts.
1859  */
1860 static void create_server()
1861 {
1862         if (false)
1863         {
1864                 error:
1865                 perror("Failed to create server");
1866 #ifndef WINDOWS
1867                 error2:
1868 #endif
1869                 exit(EXIT_FAILURE);
1870         }
1871         DEBUG_open << "Creating server... ";
1872
1873 #ifdef WINDOWS
1874         // Prepare a windows socket.
1875         struct sockaddr_in socket_addr;
1876         socket_addr.sin_family = AF_INET;
1877         socket_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
1878         socket_addr.sin_port = 0;
1879
1880         // Create and listen to the socket.
1881         socket_fd = socket(AF_INET, SOCK_STREAM, 0);
1882         if (socket_fd < 0) goto error;
1883         if (!SetHandleInformation((HANDLE)socket_fd, HANDLE_FLAG_INHERIT, 0))
1884                 goto error;
1885         if (bind(socket_fd, (struct sockaddr *)&socket_addr, sizeof(sockaddr_in)))
1886                 goto error;
1887         int len = sizeof(sockaddr_in);
1888         if (getsockname(socket_fd, (struct sockaddr *)&socket_addr, &len))
1889                 goto error;
1890         std::ostringstream buf;
1891         buf << socket_addr.sin_port;
1892         if (!SetEnvironmentVariable("REMAKE_SOCKET", buf.str().c_str()))
1893                 goto error;
1894         if (listen(socket_fd, 1000)) goto error;
1895 #else
1896         // Set a handler for SIGCHLD then block the signal (unblocked during select).
1897         sigset_t sigmask;
1898         sigemptyset(&sigmask);
1899         sigaddset(&sigmask, SIGCHLD);
1900         if (sigprocmask(SIG_BLOCK, &sigmask, NULL) == -1) goto error;
1901         struct sigaction sa;
1902         sa.sa_flags = 0;
1903         sa.sa_handler = &child_sig_handler;
1904         sigemptyset(&sa.sa_mask);
1905         if (sigaction(SIGCHLD, &sa, NULL) == -1) goto error;
1906
1907         // Prepare a named unix socket in temporary directory.
1908         socket_name = tempnam(NULL, "rmk-");
1909         if (!socket_name) goto error2;
1910         struct sockaddr_un socket_addr;
1911         size_t len = strlen(socket_name);
1912         if (len >= sizeof(socket_addr.sun_path) - 1) goto error2;
1913         socket_addr.sun_family = AF_UNIX;
1914         strcpy(socket_addr.sun_path, socket_name);
1915         len += sizeof(socket_addr.sun_family);
1916         if (setenv("REMAKE_SOCKET", socket_name, 1)) goto error;
1917
1918         // Create and listen to the socket.
1919 #ifdef LINUX
1920         socket_fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
1921         if (socket_fd < 0) goto error;
1922 #else
1923         socket_fd = socket(AF_UNIX, SOCK_STREAM, 0);
1924         if (socket_fd < 0) goto error;
1925         if (fcntl(socket_fd, F_SETFD, FD_CLOEXEC) < 0) goto error;
1926 #endif
1927         if (bind(socket_fd, (struct sockaddr *)&socket_addr, len))
1928                 goto error;
1929         if (listen(socket_fd, 1000)) goto error;
1930 #endif
1931 }
1932
1933 /**
1934  * Accept a connection from a client, get the job it spawned from,
1935  * get the targets, and mark them as dependencies of the job targets.
1936  */
1937 void accept_client()
1938 {
1939         DEBUG_open << "Handling client request... ";
1940
1941         // Accept connection.
1942 #ifdef WINDOWS
1943         socket_t fd = accept(socket_fd, NULL, NULL);
1944         if (fd == INVALID_SOCKET) return;
1945         if (!SetHandleInformation((HANDLE)fd, HANDLE_FLAG_INHERIT, 0))
1946         {
1947                 error2:
1948                 std::cerr << "Unexpected failure while setting connection with client" << std::endl;
1949                 closesocket(fd);
1950                 return;
1951         }
1952         // WSAEventSelect puts sockets into nonblocking mode, so disable it here.
1953         u_long nbio = 0;
1954         if (ioctlsocket(fd, FIONBIO, &nbio)) goto error2;
1955 #elif defined(LINUX)
1956         int fd = accept4(socket_fd, NULL, NULL, SOCK_CLOEXEC);
1957         if (fd < 0) return;
1958 #else
1959         int fd = accept(socket_fd, NULL, NULL);
1960         if (fd < 0) return;
1961         if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) return;
1962 #endif
1963         clients.push_front(client_t());
1964         client_list::iterator proc = clients.begin();
1965
1966         if (false)
1967         {
1968                 error:
1969                 DEBUG_close << "failed\n";
1970                 std::cerr << "Received an ill-formed client message" << std::endl;
1971         #ifdef WINDOWS
1972                 closesocket(fd);
1973         #else
1974                 close(fd);
1975         #endif
1976                 clients.erase(proc);
1977                 return;
1978         }
1979
1980         // Receive message. Stop when encountering two nuls in a row.
1981         std::vector<char> buf;
1982         size_t len = 0;
1983         while (len < sizeof(int) + 2 || buf[len - 1] || buf[len - 2])
1984         {
1985                 buf.resize(len + 1024);
1986                 ssize_t l = recv(fd, &buf[0] + len, 1024, 0);
1987                 if (l <= 0) goto error;
1988                 len += l;
1989         }
1990
1991         // Parse job that spawned the client.
1992         int job_id;
1993         memcpy(&job_id, &buf[0], sizeof(int));
1994         proc->socket = fd;
1995         proc->job_id = job_id;
1996         job_targets_map::const_iterator i = job_targets.find(job_id);
1997         if (i == job_targets.end()) goto error;
1998         DEBUG << "receiving request from job " << job_id << std::endl;
1999
2000         // Parse the targets and mark them as dependencies from the job targets.
2001         dependency_t &dep = *dependencies[job_targets[job_id].front()];
2002         char const *p = &buf[0] + sizeof(int);
2003         while (true)
2004         {
2005                 len = strlen(p);
2006                 if (len == 1 && p[0] == 1)
2007                 {
2008                         //Finished parsing targets.
2009                         p += 2;
2010                         ++waiting_jobs;
2011                         break;
2012                 }
2013                 std::string target(p, p + len);
2014                 DEBUG << "adding dependency " << target << " to job " << job_id << std::endl;
2015                 proc->pending.push_back(target);
2016                 dep.deps.insert(target);
2017                 p += len + 1;
2018         }
2019
2020         while (true)
2021         {
2022                 len = strlen(p);
2023                 if (len == 0) return;
2024                 std::string line(p, p + len);
2025                 std::istringstream in (line);
2026                 std::string name = read_word(in);
2027                 if (next_token(in) != Equal) {
2028                   std::cerr << '\'' << line << "'" << std::endl;
2029                   goto error;
2030                 }
2031                 in.ignore(1); // ignore =.
2032                 DEBUG << "adding variable " << line << " to job " << job_id << std::endl;
2033                 string_list l = read_words(in);
2034                 proc->variables[name] = l;
2035                 p += len + 1;
2036         }
2037
2038
2039 }
2040
2041 /**
2042  * Loop until all the jobs have finished.
2043  */
2044 void server_loop()
2045 {
2046         while (true)
2047         {
2048                 update_clients();
2049                 if (running_jobs == 0)
2050                 {
2051                         assert(clients.empty());
2052                         break;
2053                 }
2054                 DEBUG_open << "Handling events... ";
2055         #ifdef WINDOWS
2056                 size_t len = job_pids.size() + 1;
2057                 HANDLE h[len];
2058                 int num = 0;
2059                 for (pid_job_map::const_iterator i = job_pids.begin(),
2060                      i_end = job_pids.end(); i != i_end; ++i, ++num)
2061                 {
2062                         h[num] = i->first;
2063                 }
2064                 WSAEVENT aev = WSACreateEvent();
2065                 h[num] = aev;
2066                 WSAEventSelect(socket_fd, aev, FD_ACCEPT);
2067                 DWORD w = WaitForMultipleObjects(len, h, false, INFINITE);
2068                 WSAEventSelect(socket_fd, aev, 0);
2069                 WSACloseEvent(aev);
2070                 if (w < WAIT_OBJECT_0 || WAIT_OBJECT_0 + len <= w)
2071                         continue;
2072                 if (w == WAIT_OBJECT_0 + len - 1)
2073                 {
2074                         accept_client();
2075                         continue;
2076                 }
2077                 pid_t pid = h[w - WAIT_OBJECT_0];
2078                 DWORD s = 0;
2079                 bool res = GetExitCodeProcess(pid, &s) && s == 0;
2080                 CloseHandle(pid);
2081                 pid_job_map::iterator i = job_pids.find(pid);
2082                 assert(i != job_pids.end());
2083                 int job_id = i->second;
2084                 job_pids.erase(i);
2085                 --running_jobs;
2086                 complete_job(job_id, res);
2087         #else
2088                 sigset_t emptymask;
2089                 sigemptyset(&emptymask);
2090                 fd_set fdset;
2091                 FD_ZERO(&fdset);
2092                 FD_SET(socket_fd, &fdset);
2093                 int ret = pselect(socket_fd + 1, &fdset, NULL, NULL, NULL, &emptymask);
2094                 if (ret > 0 /* && FD_ISSET(socket_fd, &fdset)*/) accept_client();
2095                 if (!got_SIGCHLD) continue;
2096                 got_SIGCHLD = 0;
2097                 pid_t pid;
2098                 int status;
2099                 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
2100                 {
2101                         bool res = WIFEXITED(status) && WEXITSTATUS(status) == 0;
2102                         pid_job_map::iterator i = job_pids.find(pid);
2103                         assert(i != job_pids.end());
2104                         int job_id = i->second;
2105                         job_pids.erase(i);
2106                         --running_jobs;
2107                         complete_job(job_id, res);
2108                 }
2109         #endif
2110         }
2111 }
2112
2113 /**
2114  * Load dependencies and rules, listen to client requests, and loop until
2115  * all the requests have completed.
2116  * If Remakefile is obsolete, perform a first run with it only, then reload
2117  * the rules, and perform a second with the original clients.
2118  */
2119 void server_mode(string_list const &targets)
2120 {
2121         load_dependencies();
2122         load_rules();
2123         create_server();
2124         if (get_status("Remakefile").status != Uptodate)
2125         {
2126                 clients.push_back(client_t());
2127                 clients.back().pending.push_back("Remakefile");
2128                 server_loop();
2129                 if (build_failure) goto early_exit;
2130                 variables.clear();
2131                 specific_rules.clear();
2132                 generic_rules.clear();
2133                 first_target.clear();
2134                 load_rules();
2135         }
2136         clients.push_back(client_t());
2137         if (!targets.empty()) clients.back().pending = targets;
2138         else if (!first_target.empty())
2139                 clients.back().pending.push_back(first_target);
2140         server_loop();
2141         early_exit:
2142         close(socket_fd);
2143         remove(socket_name);
2144         save_dependencies();
2145         exit(build_failure ? EXIT_FAILURE : EXIT_SUCCESS);
2146 }
2147
2148 /**
2149  * Connect to the server @a socket_name, send a build request for @a targets,
2150  * and exit with the status returned by the server.
2151  */
2152 void client_mode(char *socket_name, string_list const &targets)
2153 {
2154         if (false)
2155         {
2156                 error:
2157                 perror("Failed to send targets to server");
2158                 exit(EXIT_FAILURE);
2159         }
2160         if (targets.empty()) exit(EXIT_SUCCESS);
2161         DEBUG_open << "Connecting to server... ";
2162
2163         // Connect to server.
2164 #ifdef WINDOWS
2165         struct sockaddr_in socket_addr;
2166         socket_fd = socket(AF_INET, SOCK_STREAM, 0);
2167         if (socket_fd < 0) goto error;
2168         socket_addr.sin_family = AF_INET;
2169         socket_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2170         socket_addr.sin_port = atoi(socket_name);
2171         if (connect(socket_fd, (struct sockaddr *)&socket_addr, sizeof(sockaddr_in)))
2172                 goto error;
2173 #else
2174         struct sockaddr_un socket_addr;
2175         size_t len = strlen(socket_name);
2176         if (len >= sizeof(socket_addr.sun_path) - 1) exit(EXIT_FAILURE);
2177         socket_fd = socket(AF_UNIX, SOCK_STREAM, 0);
2178         if (socket_fd < 0) goto error;
2179         socket_addr.sun_family = AF_UNIX;
2180         strcpy(socket_addr.sun_path, socket_name);
2181         if (connect(socket_fd, (struct sockaddr *)&socket_addr, sizeof(socket_addr.sun_family) + len))
2182                 goto error;
2183 #ifdef MACOSX
2184         int set_option = 1;
2185         if (setsockopt(socket_fd, SOL_SOCKET, SO_NOSIGPIPE, &set_option, sizeof(set_option)))
2186                 goto error;
2187 #endif
2188 #endif
2189
2190         // Send current job id.
2191         char *id = getenv("REMAKE_JOB_ID");
2192         int job_id = id ? atoi(id) : -1;
2193         if (send(socket_fd, (char *)&job_id, sizeof(job_id), MSG_NOSIGNAL) != sizeof(job_id))
2194                 goto error;
2195
2196         // Send targets.
2197         for (string_list::const_iterator i = targets.begin(),
2198              i_end = targets.end(); i != i_end; ++i)
2199         {
2200                 DEBUG_open << "Sending " << *i << "... ";
2201                 ssize_t len = i->length() + 1;
2202                 if (send(socket_fd, i->c_str(), len, MSG_NOSIGNAL) != len)
2203                         goto error;
2204         }
2205         // send 10 as as separator between targets and variables.
2206         char result = 1;
2207         if (send(socket_fd, &result, 1, MSG_NOSIGNAL) != 1) goto error;
2208         result = 0;
2209         if (send(socket_fd, &result, 1, MSG_NOSIGNAL) != 1) goto error;
2210         // Send variables.
2211         // (maybe split vars in small chunks and send... seems like an overkil)
2212         std::string vars = serialize_variables(variables, 0);
2213         ssize_t sent = vars.size();
2214         DEBUG << "Sending variables: '" << vars << "' to the server" << std::endl;
2215         if (send(socket_fd, vars.data(), sent, MSG_NOSIGNAL) != sent)
2216           goto error;
2217
2218         // Send terminating nul and wait for reply.
2219         if (send(socket_fd, &result, 1, MSG_NOSIGNAL) != 1) goto error;
2220         if (recv(socket_fd, &result, 1, 0) != 1) exit(EXIT_FAILURE);
2221         exit(result ? EXIT_SUCCESS : EXIT_FAILURE);
2222 }
2223
2224 /**
2225  * Display usage and exit with @a exit_status.
2226  */
2227 void usage(int exit_status)
2228 {
2229         std::cerr << "Usage: remake [options] [target] ...\n"
2230                 "Options\n"
2231                 "  -d                     Echo script commands.\n"
2232                 "  -d -d                  Print lots of debugging information.\n"
2233                 "  -h, --help             Print this message and exit.\n"
2234                 "  -j[N], --jobs=[N]      Allow N jobs at once; infinite jobs with no arg.\n"
2235                 "  -k                     Keep going when some targets cannot be made.\n"
2236                 "  -r                     Look up targets from the dependencies on standard input.\n"
2237                 "  -v V=X, --var V=X      Initialize variable V with X"
2238                 "  -s, --silent, --quiet  Do not echo targets.\n";
2239         exit(exit_status);
2240 }
2241
2242 /**
2243  * This program behaves in two different ways.
2244  *
2245  * - If the environment contains the REMAKE_SOCKET variable, the client
2246  *   connects to this socket and sends to the server its build targets.
2247  *   It exits once it receives the server reply.
2248  *
2249  * - Otherwise, it creates a server that waits for build requests. It
2250  *   also creates a pseudo-client that requests the targets passed on the
2251  *   command line.
2252  */
2253 int main(int argc, char *argv[])
2254 {
2255         init_working_dir(argv[0]);
2256
2257         string_list targets;
2258         bool indirect_targets = false;
2259
2260         // Parse command-line arguments.
2261         for (int i = 1; i < argc; ++i)
2262         {
2263                 std::string arg = argv[i];
2264                 if (arg.empty()) usage(EXIT_FAILURE);
2265                 if (arg == "-h" || arg == "--help") usage(EXIT_SUCCESS);
2266                 if (arg == "-d")
2267                         if (echo_scripts) debug.active = true;
2268                         else echo_scripts = true;
2269                 else if (arg == "-k" || arg =="--keep-going")
2270                         keep_going = true;
2271                 else if (arg == "-s" || arg == "--silent" || arg == "--quiet")
2272                         show_targets = false;
2273                 else if (arg == "-r")
2274                         indirect_targets = true;
2275                 else if (arg.compare(0, 2, "-j") == 0)
2276                         max_active_jobs = atoi(arg.c_str() + 2);
2277                 else if (arg.compare(0, 7, "--jobs=") == 0)
2278                         max_active_jobs = atoi(arg.c_str() + 7);
2279                 else if (arg == "-v" || arg == "--var")
2280                 {
2281                   ++i;
2282                   if (i == argc) usage(EXIT_FAILURE);
2283                   arg = argv[i];
2284                   std::istringstream in (arg);
2285                   std::string name = read_word(in);
2286                   if (next_token(in) != Equal) {
2287                     std::cerr << "Invalid variable '" << arg << "'" << std::endl;
2288                     exit(EXIT_FAILURE);
2289                   }
2290                   in.ignore(1);
2291                   string_list l = read_words(in);
2292                   variables[name] = l;
2293                 }
2294                 else
2295                 {
2296                         if (arg[0] == '-') usage(1);
2297                         targets.push_back(normalize(arg));
2298                         DEBUG << "New target: " << arg << '\n';
2299                 }
2300         }
2301
2302         if (indirect_targets)
2303         {
2304                 load_dependencies(std::cin);
2305                 string_list l;
2306                 targets.swap(l);
2307                 if (l.empty() && !dependencies.empty())
2308                 {
2309                         l.push_back(dependencies.begin()->second->targets.front());
2310                 }
2311                 for (string_list::const_iterator i = l.begin(),
2312                      i_end = l.end(); i != i_end; ++i)
2313                 {
2314                         dependency_map::const_iterator j = dependencies.find(*i);
2315                         if (j == dependencies.end()) continue;
2316                         dependency_t const &dep = *j->second;
2317                         for (string_set::const_iterator k = dep.deps.begin(),
2318                              k_end = dep.deps.end(); k != k_end; ++k)
2319                         {
2320                                 targets.push_back(normalize(*k));
2321                         }
2322                 }
2323                 dependencies.clear();
2324         }
2325
2326 #ifdef WINDOWS
2327         WSADATA wsaData;
2328         if (WSAStartup(MAKEWORD(2,2), &wsaData))
2329         {
2330                 std::cerr << "Unexpected failure while initializing Windows Socket" << std::endl;
2331                 return 1;
2332         }
2333 #endif
2334
2335         // Run as client if REMAKE_SOCKET is present in the environment.
2336         if (char *sn = getenv("REMAKE_SOCKET")) client_mode(sn, targets);
2337
2338         // Otherwise run as server.
2339         server_mode(targets);
2340 }