Update to latest master of remake.
[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 ... : prerequisite1 prerequisite2 ...
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 prerequisites are. If it
16 has no known prerequisites 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 prerequisite4 prerequisite5 ...</tt>, these prerequisites are
23 rebuilt if they are obsolete. (So <b>remake</b> acts like
24 <b>redo-ifchange</b>.) Moreover, all the 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 ... : prerequisite1 prerequisite2 ...
35         shell script
36
37 target1 target2 ... :
38         remake prerequisite1 prerequisite2 ...
39         shell script
40 @endverbatim
41
42 (There is a difference if the targets already exist, have never been
43 built before, and the prerequisites 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 $@.d -o $@ -c $<
52         remake -r < $@.d
53         rm $@.d
54
55 %.cmo : %.ml
56         ocamldep $< | remake -r $@
57         ocamlc -c $<
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>-f FILE</tt>: Read <tt>FILE</tt> as <b>Remakefile</b>.
79 - <tt>-j[N]</tt>, <tt>--jobs=[N]</tt>: Allow <tt>N</tt> jobs at once;
80   infinite jobs with no argument.
81 - <tt>-k</tt>, <tt>--keep-going</tt>: Keep going when some targets cannot be made.
82 - <tt>-r</tt>: Look up targets from the dependencies on standard input.
83 - <tt>-s</tt>, <tt>--silent</tt>, <tt>--quiet</tt>: Do not echo targets.
84
85 \section sec-syntax Syntax
86
87 Lines starting with a space character or a tabulation are assumed to be rule
88 scripts. They are only allowed after a rule header.
89
90 Lines starting with <tt>#</tt> are considered to be comments and are ignored.
91 They do interrupt rule scripts though.
92
93 Any other line is either a variable definition or a rule header. If such a
94 line ends with a backslash, the following line break is ignored and the line
95 extends to the next one.
96
97 Variable definitions are a single name followed by equal followed by a list
98 of names, possibly empty.
99
100 Rule headers are a nonempty list of names, followed by a colon, followed by
101 another list of names, possibly empty. Basically, the syntax of a rule is as
102 follows:
103
104 @verbatim
105 targets : prerequisites
106         shell script
107 @endverbatim
108
109 List of names are space-separated sequences of names. If a name contains a
110 space character, it should be put into double quotes. Names can not be any
111 of the following special characters <tt>:$(),="</tt>. Again, quotation
112 should be used. Quotation marks can be escaped by a backslash inside
113 quoted names.
114
115 \subsection sec-variables Variables
116
117 Variables can be used to factor lists of targets or prerequisites. They are
118 expanded as they are encountered during <b>Remakefile</b> parsing.
119
120 @verbatim
121 VAR2 = a
122 VAR1 = c d
123 VAR2 += $(VAR1) b
124 $(VAR2) e :
125 @endverbatim
126
127 Variable assignments can appear instead of prerequisites inside non-generic
128 rules with no script. They are then expanded inside the corresponding
129 generic rule.
130
131 @verbatim
132 foo.o: CFLAGS += -DBAR
133
134 %.o : %.c
135         gcc $(CFLAGS) -MMD -MF $@.d -o $@ -c $<
136         remake -r < $@.d
137         rm $@.d
138 @endverbatim
139
140 Note: contrarily to <b>make</b>, variable names have to be enclosed in
141 parentheses. For instance, <tt>$y</tt> is not a shorthand for <tt>\$(y)</tt> and
142 is left unexpanded.
143
144 \subsection sec-autovars Automatic variables
145
146 The following special symbols can appear inside scripts:
147
148 - <tt>$&lt;</tt> expands to the first static prerequisite of the rule.
149 - <tt>$^</tt> expands to all the static prerequisites of the rule, including
150   duplicates if any.
151 - <tt>$\@</tt> expands to the first target of the rule.
152 - <tt>$*</tt> expands to the string that matched <tt>%</tt> in a generic rule.
153 - <tt>$$</tt> expands to a single dollar symbol.
154
155 Note: contrarily to <b>make</b>, there are no corresponding variables. For
156 instance, <tt>$^</tt> is not a shorthand for <tt>$(^)</tt>. Another
157 difference is that <tt>$\@</tt> is always the first target, not the one that
158 triggered the rule.
159
160 \subsection sec-functions Built-in functions
161
162 <b>remake</b> also supports a few built-in functions inspired from <b>make</b>.
163
164 - <tt>$(addprefix <i>prefix</i>, <i>list</i>)</tt> returns the list obtained
165   by prepending its first argument to each element of its second argument.
166 - <tt>$(addsuffix <i>suffix</i>, <i>list</i>)</tt> returns the list obtained
167   by appending its first argument to each element of its second argument.
168
169 \subsection sec-order Order-only prerequisites
170
171 If the static prerequisites of a rule contain a pipe symbol, prerequisites
172 on its right do not cause the targets to become obsolete if they are newer
173 (unless they are also dynamically registered as dependencies). They are
174 meant to be used when the targets do not directly depend on them, but the
175 computation of their dynamic dependencies does.
176
177 @verbatim
178 %.o : %.c | parser.h
179         gcc -MMD -MF $@.d -o $@ -c $<
180         remake -r < $@.d
181         rm $@.d
182
183 parser.c parser.h: parser.y
184         yacc -d -o parser.c parser.y
185 @endverbatim
186
187 \subsection sec-special-var Special variables
188
189 Variable <tt>.OPTIONS</tt> is handled specially. Its content enables some
190 features of <b>remake</b> that are not enabled by default.
191
192 - <tt>variable-propagation</tt>: When a variable is set in the prerequisite
193   part of a rule, it is propagated to the rules of all the targets this rule
194   depends on. This option also enables variables to be set on the command
195   line. Note that, as in <b>make</b>, this features introduces non-determinism:
196   the content of some variables will depend on the build order.
197
198 \section sec-semantics Semantics
199
200 \subsection src-obsolete When are targets obsolete?
201
202 A target is obsolete:
203
204 - if there is no file corresponding to the target, or to one of its siblings
205   in a multi-target rule,
206 - if any of its dynamic prerequisites from a previous run or any of its static
207   prerequisites is obsolete,
208 - if the latest file corresponding to its siblings or itself is older than any
209   of its dynamic prerequisites or static prerequisites.
210
211 In all the other cases, it is assumed to be up-to-date (and so are all its
212 siblings). Note that the last rule above says "latest" and not "earliest". While
213 it might cause some obsolete targets to go unnoticed in corner cases, it allows
214 for the following kind of rules:
215
216 @verbatim
217 config.h stamp-config_h: config.h.in config.status
218         ./config.status config.h
219         touch stamp-config_h
220 @endverbatim
221
222 A <tt>config.status</tt> file generally does not update header files (here
223 <tt>config.h</tt>) if they would not change. As a consequence, if not for the
224 <tt>stamp-config_h</tt> file above, a header would always be considered obsolete
225 once one of its prerequisites is modified. Note that touching <tt>config.h</tt>
226 rather than <tt>stamp-config_h</tt> would defeat the point of not updating it
227 in the first place, since the program files would need to be rebuilt.
228
229 Once all the static prerequisites of a target have been rebuilt, <b>remake</b>
230 checks whether the target still needs to be built. If it was obsolete only
231 because its prerequisites needed to be rebuilt and none of them changed, the
232 target is assumed to be up-to-date.
233
234 \subsection sec-rules How are targets (re)built?
235
236 There are two kinds of rules. If any of the targets or prerequisites contains
237 a <tt>%</tt> character, the rule is said to be <em>generic</em>. All the
238 targets of the rule shall then contain a single <tt>%</tt> character. All the
239 other rules are said to be <em>specific</em>.
240
241 A rule is said to <em>match</em> a given target:
242
243 - if it is specific and the target appears inside its target list,
244 - if it is generic and there is a way to replace the <tt>%</tt> character
245   from one of its targets so that it matches the given target.
246
247 When <b>remake</b> tries to build a given target, it looks for a specific rule
248 that matches it. If there is one and its script is nonempty, it uses it to
249 rebuild the target.
250
251 Otherwise, it looks for a generic rule that matches the target. If there are
252 several matching rules, it chooses the one with the shortest pattern (and if
253 there are several ones, the earliest one). <b>remake</b> then looks for
254 specific rules that match each target of the generic rule. All the
255 prerequisites of these specific rules are added to those of the generic rule.
256 The script of the generic rule is used to build the target.
257
258 Example:
259
260 @verbatim
261 t%1 t2%: p1 p%2
262         commands building t%1 and t2%
263
264 t2z: p4
265         commands building t2z
266
267 ty1: p3
268
269 # t2x is built by the first rule (which also builds tx1) and its prerequisites are p1, px2
270 # t2y is built by the first rule (which also builds ty1) and its prerequisites are p1, py2, p3
271 # t2z is built by the second rule and its prerequisite is p4
272 @endverbatim
273
274 The set of rules from <b>Remakefile</b> is ill-formed:
275
276 - if any specific rule matching a target of the generic rule has a nonempty script,
277 - if any target of the generic rule is matched by a generic rule with a shorter pattern.
278
279 \section sec-compilation Compilation
280
281 - On Linux, MacOSX, and BSD: <tt>g++ -o remake remake.cpp</tt>
282 - On Windows: <tt>g++ -o remake.exe remake.cpp -lws2_32</tt>
283
284 Installing <b>remake</b> is needed only if <b>Remakefile</b> does not
285 specify the path to the executable for its recursive calls. Thanks to its
286 single source file, <b>remake</b> can be shipped inside other packages and
287 built at configuration time.
288
289 \section sec-differences Differences with other build systems
290
291 Differences with <b>make</b>:
292
293 - Dynamic dependencies are supported.
294 - For rules with multiple targets, the shell script is executed only once
295   and is assumed to build all the targets. There is no need for
296   convoluted rules that are robust enough for parallel builds. For generic
297   rules, this is similar to the behavior of pattern rules from <b>gmake</b>.
298 - As with <b>redo</b>, only one shell is run when executing a script,
299   rather than one per script line. Note that the shells are run with
300   option <tt>-e</tt>, thus causing them to exit as soon as an error is
301   encountered.
302 - The prerequisites of generic rules (known as implicit rules in make lingo)
303   are not used to decide between several of them. <b>remake</b> does not
304   select one for which it could satisfy the dependencies.
305 - Variables and built-in functions are expanded as they are encountered
306   during <b>Remakefile</b> parsing.
307 - Target-specific variables are not propagated, unless specifically enabled,
308   since this causes non-deterministic builds. This is the same for variables
309   set on the command line.
310
311 Differences with <b>redo</b>:
312
313 - As with <b>make</b>, it is possible to write the following kind of rules
314   in <b>remake</b>.
315 @verbatim
316 Remakefile: Remakefile.in ./config.status
317         ./config.status Remakefile
318 @endverbatim
319 - If a target is already built the first time <b>remake</b> runs, it still
320   uses the static prerequisites of rules mentioning it to check whether it
321   needs to be rebuilt. It does not assume it to be up-to-date. As with
322   <b>redo</b> though, if its obsolete status would be due to a dynamic
323   prerequisite, it will go unnoticed; it should be removed beforehand.
324 - Multiple targets are supported.
325 - <b>remake</b> has almost no features: no checksum-based dependencies, no
326   compatibility with job servers, etc.
327
328 \section sec-limitations Limitations
329
330 - If a rule script calls <b>remake</b>, the current working directory should
331   be the directory containing <b>Remakefile</b> (or the working directory
332   from the original <b>remake</b> if it was called with option <b>-f</b>).
333 - As with <b>make</b>, variables passed on the command line should keep
334   the same values, to ensure deterministic builds.
335 - Some cases of ill-formed rules are not caught by <b>remake</b> and can
336   thus lead to unpredictable behaviors.
337
338 \section sec-links Links
339
340 @see http://cr.yp.to/redo.html for the philosophy of <b>redo</b> and
341 https://github.com/apenwarr/redo for an implementation and some comprehensive documentation.
342
343 \section sec-licensing Licensing
344
345 @author Guillaume Melquiond
346 @version 0.10
347 @date 2012-2013
348 @copyright
349 This program is free software: you can redistribute it and/or modify
350 it under the terms of the GNU General Public License as published by
351 the Free Software Foundation, either version 3 of the License, or
352 (at your option) any later version.
353 \n
354 This program is distributed in the hope that it will be useful,
355 but WITHOUT ANY WARRANTY; without even the implied warranty of
356 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
357 GNU General Public License for more details.
358
359 \section sec-internals Internals
360
361 The parent <b>remake</b> process acts as a server. The other ones have a
362 REMAKE_SOCKET environment variable that tells them how to contact the
363 server. They send the content of the REMAKE_JOB_ID environment variable,
364 so that the server can associate the child targets to the jobs that
365 spawned them. They then wait for completion and exit with the status
366 returned by the server. This is handled by #client_mode.
367
368 The server calls #load_dependencies and #save_dependencies to serialize
369 dynamic dependencies from <b>.remake</b>. It loads <b>Remakefile</b> with
370 #load_rules. It then runs #server_mode, which calls #server_loop.
371
372 When building a target, the following sequence of events happens:
373
374 - #start calls #find_rule (and #find_generic_rule) to get the rule.
375 - It then creates a pseudo-client if the rule has static dependencies, or
376   calls #run_script otherwise. In both cases, a new job is created; the
377   rule and the variables are stored into #jobs.
378 - #run_script creates a shell process and stores it in #job_pids. It
379   increases #running_jobs.
380 - The child process possibly calls <b>remake</b> with a list of targets.
381 - #accept_client receives a build request from a child process and adds
382   it to #clients. It also records the new dependencies of the job into
383   #dependencies. It increases #waiting_jobs.
384 - #handle_clients uses #get_status to look up the obsoleteness of the
385   targets.
386 - Once the targets of a request have been built or one of them has failed,
387   #handle_clients calls #complete_request and removes the request from
388   #clients.
389 - If the build targets come from a pseudo-client, #complete_request calls
390   #run_script. Otherwise it sends the reply to the corresponding child
391   process and decreases #waiting_jobs.
392 - When a child process ends, #server_loop calls #finalize_job, which
393   removes the process from #job_pids, decreases #running_jobs, and calls
394   #complete_job.
395 - #complete_job removes the job from #jobs and calls #update_status
396   to change the status of the targets. It also removes the target files in
397   case of failure.
398 */
399
400 #ifdef _WIN32
401 #define WIN32_LEAN_AND_MEAN
402 #define WINDOWS
403 #endif
404
405 #include <fstream>
406 #include <iostream>
407 #include <list>
408 #include <map>
409 #include <set>
410 #include <sstream>
411 #include <string>
412 #include <vector>
413 #include <cassert>
414 #include <cstdlib>
415 #include <cstring>
416 #include <ctime>
417 #include <errno.h>
418 #include <fcntl.h>
419 #include <signal.h>
420 #include <unistd.h>
421 #include <sys/stat.h>
422 #include <sys/types.h>
423
424 #ifdef __APPLE__
425 #define MACOSX
426 #endif
427
428 #ifdef __linux__
429 #define LINUX
430 #endif
431
432 #ifdef WINDOWS
433 #include <windows.h>
434 #include <winbase.h>
435 #include <winsock2.h>
436 #define pid_t HANDLE
437 typedef SOCKET socket_t;
438 #else
439 #include <sys/socket.h>
440 #include <sys/un.h>
441 #include <sys/wait.h>
442 typedef int socket_t;
443 enum { INVALID_SOCKET = -1 };
444 extern char **environ;
445 #endif
446
447 #if defined(WINDOWS) || defined(MACOSX)
448 enum { MSG_NOSIGNAL = 0 };
449 #endif
450
451 typedef std::list<std::string> string_list;
452
453 typedef std::set<std::string> string_set;
454
455 /**
456  * Reference-counted shared object.
457  * @note The default constructor delays the creation of the object until it
458  *       is first dereferenced.
459  */
460 template<class T>
461 struct ref_ptr
462 {
463         struct content
464         {
465                 size_t cnt;
466                 T val;
467                 content(): cnt(1) {}
468                 content(T const &t): cnt(1), val(t) {}
469         };
470         mutable content *ptr;
471         ref_ptr(): ptr(NULL) {}
472         ref_ptr(T const &t): ptr(new content(t)) {}
473         ref_ptr(ref_ptr const &p): ptr(p.ptr) { if (ptr) ++ptr->cnt; }
474         ~ref_ptr() { if (ptr && --ptr->cnt == 0) delete ptr; }
475         ref_ptr &operator=(ref_ptr const &p)
476         {
477                 if (ptr == p.ptr) return *this;
478                 if (ptr && --ptr->cnt == 0) delete ptr;
479                 ptr = p.ptr;
480                 if (ptr) ++ptr->cnt;
481                 return *this;
482         }
483         T &operator*() const
484         {
485                 if (!ptr) ptr = new content;
486                 return ptr->val;
487         }
488         T *operator->() const { return &**this; }
489 };
490
491 struct dependency_t
492 {
493         string_list targets;
494         string_set deps;
495 };
496
497 typedef std::map<std::string, ref_ptr<dependency_t> > dependency_map;
498
499 typedef std::map<std::string, string_list> variable_map;
500
501 /**
502  * Build status of a target.
503  */
504 enum status_e
505 {
506         Uptodate, ///< Target is up-to-date.
507         Todo,     ///< Target is missing or obsolete.
508         Recheck,  ///< Target has an obsolete dependency.
509         Running,  ///< Target is being rebuilt.
510         Remade,   ///< Target was successfully rebuilt.
511         Failed    ///< Build failed for target.
512 };
513
514 /**
515  * Build status of a target.
516  */
517 struct status_t
518 {
519         status_e status; ///< Actual status.
520         time_t last;     ///< Last-modified date.
521 };
522
523 typedef std::map<std::string, status_t> status_map;
524
525 /**
526  * Delayed assignment to a variable.
527  */
528 struct assign_t
529 {
530         bool append;
531         string_list value;
532 };
533
534 typedef std::map<std::string, assign_t> assign_map;
535
536 /**
537  * A rule loaded from Remakefile.
538  */
539 struct rule_t
540 {
541         string_list targets; ///< Files produced by this rule.
542         string_list deps;    ///< Dependencies used for an implicit call to remake at the start of the script.
543         string_list wdeps;   ///< Like #deps, except that they are not registered as dependencies.
544         assign_map assigns;  ///< Assignment of variables.
545         std::string script;  ///< Shell script for building the targets.
546 };
547
548 typedef std::list<rule_t> rule_list;
549
550 typedef std::map<std::string, ref_ptr<rule_t> > rule_map;
551
552 /**
553  * A job created from a set of rules.
554  */
555
556 struct job_t
557 {
558         rule_t rule;       ///< Original rule.
559         std::string stem;  ///< Pattern used to instantiate the generic rule, if any.
560         variable_map vars; ///< Values of local variables.
561 };
562
563 typedef std::map<int, job_t> job_map;
564
565 typedef std::map<pid_t, int> pid_job_map;
566
567 /**
568  * Client waiting for a request to complete.
569  *
570  * There are two kinds of clients:
571  * - real clients, which are instances of remake created by built scripts,
572  * - pseudo clients, which are created by the server to build specific targets.
573  *
574  * Among pseudo clients, there are two categories:
575  * - original clients, which are created for the targets passed on the
576  *   command line by the user or for the initial regeneration of the rule file,
577  * - dependency clients, which are created to handle rules that have
578  *   explicit dependencies and thus to emulate a call to remake.
579  */
580 struct client_t
581 {
582         socket_t socket;     ///< Socket used to reply to the client (invalid for pseudo clients).
583         int job_id;          ///< Job for which the built script called remake and spawned the client (negative for original clients).
584         bool failed;         ///< Whether some targets failed in mode -k.
585         string_list pending; ///< Targets not yet started.
586         string_set running;  ///< Targets being built.
587         variable_map vars;   ///< Variables set on request.
588         bool delayed;        ///< Whether it is a dependency client and a script has to be started on request completion.
589         client_t(): socket(INVALID_SOCKET), job_id(-1), failed(false), delayed(false) {}
590 };
591
592 typedef std::list<client_t> client_list;
593
594 /**
595  * Map from variable names to their content.
596  * Initialized with the values passed on the command line.
597  */
598 static variable_map variables;
599
600 /**
601  * Map from targets to their known dependencies.
602  */
603 static dependency_map dependencies;
604
605 /**
606  * Map from targets to their build status.
607  */
608 static status_map status;
609
610 /**
611  * Set of generic rules loaded from Remakefile.
612  */
613 static rule_list generic_rules;
614
615 /**
616  * Map from targets to specific rules loaded from Remakefile.
617  */
618 static rule_map specific_rules;
619
620 /**
621  * Map of jobs being built.
622  */
623 static job_map jobs;
624
625 /**
626  * Map from jobs to shell pids.
627  */
628 static pid_job_map job_pids;
629
630 /**
631  * List of clients waiting for a request to complete.
632  * New clients are put to front, so that the build process is depth-first.
633  */
634 static client_list clients;
635
636 /**
637  * Maximum number of parallel jobs (non-positive if unbounded).
638  * Can be modified by the -j option.
639  */
640 static int max_active_jobs = 1;
641
642 /**
643  * Whether to keep building targets in case of failure.
644  * Can be modified by the -k option.
645  */
646 static bool keep_going = false;
647
648 /**
649  * Number of jobs currently running:
650  * - it increases when a process is created in #run_script,
651  * - it decreases when a completion message is received in #finalize_job.
652  *
653  * @note There might be some jobs running while #clients is empty.
654  *       Indeed, if a client requested two targets to be rebuilt, if they
655  *       are running concurrently, if one of them fails, the client will
656  *       get a failure notice and might terminate before the other target
657  *       finishes.
658  */
659 static int running_jobs = 0;
660
661 /**
662  * Number of jobs currently waiting for a build request to finish:
663  * - it increases when a build request is received in #accept_client
664  *   (since the client is presumably waiting for the reply),
665  * - it decreases when a reply is sent in #complete_request.
666  */
667 static int waiting_jobs = 0;
668
669 /**
670  * Global counter used to produce increasing job numbers.
671  * @see jobs
672  */
673 static int job_counter = 0;
674
675 /**
676  * Socket on which the server listens for client request.
677  */
678 static socket_t socket_fd;
679
680 /**
681  * Whether the request of an original client failed.
682  */
683 static bool build_failure;
684
685 #ifndef WINDOWS
686 /**
687  * Name of the server socket in the file system.
688  */
689 static char *socket_name;
690 #endif
691
692 /**
693  * Name of the first target of the first specific rule, used for default run.
694  */
695 static std::string first_target;
696
697 /**
698  * Whether a short message should be displayed for each target.
699  */
700 static bool show_targets = true;
701
702 /**
703  * Whether script commands are echoed.
704  */
705 static bool echo_scripts = false;
706
707 /**
708  * Time at the start of the program.
709  */
710 static time_t now = time(NULL);
711
712 /**
713  * Directory with respect to which command-line names are relative.
714  */
715 static std::string working_dir;
716
717 /**
718  * Directory with respect to which targets are relative.
719  */
720 static std::string prefix_dir;
721
722 /**
723  * Whether the prefix directory is different from #working_dir.
724  */
725 static bool changed_prefix_dir;
726
727 /**
728  * Whether target-specific variables are propagated to prerequisites.
729  */
730 static bool propagate_vars = false;
731
732 #ifndef WINDOWS
733 static volatile sig_atomic_t got_SIGCHLD = 0;
734
735 static void sigchld_handler(int)
736 {
737         got_SIGCHLD = 1;
738 }
739
740 static void sigint_handler(int)
741 {
742         // Child processes will receive the signal too, so just prevent
743         // new jobs from starting and wait for the running jobs to fail.
744         keep_going = false;
745 }
746 #endif
747
748 struct log
749 {
750         bool active, open;
751         int depth;
752         log(): active(false), open(false), depth(0)
753         {
754         }
755         std::ostream &operator()()
756         {
757                 if (open) std::cerr << std::endl;
758                 assert(depth >= 0);
759                 std::cerr << std::string(depth * 2, ' ');
760                 open = false;
761                 return std::cerr;
762         }
763         std::ostream &operator()(bool o)
764         {
765                 if (o && open) std::cerr << std::endl;
766                 if (!o) --depth;
767                 assert(depth >= 0);
768                 if (o || !open) std::cerr << std::string(depth * 2, ' ');
769                 if (o) ++depth;
770                 open = o;
771                 return std::cerr;
772         }
773 };
774
775 log debug;
776
777 struct log_auto_close
778 {
779         bool still_open;
780         log_auto_close(): still_open(true)
781         {
782         }
783         ~log_auto_close()
784         {
785                 if (debug.active && still_open) debug(false) << "done\n";
786         }
787 };
788
789 #define DEBUG if (debug.active) debug()
790 #define DEBUG_open log_auto_close auto_close; if (debug.active) debug(true)
791 #define DEBUG_close if ((auto_close.still_open = false), debug.active) debug(false)
792
793 /**
794  * Strong typedef for strings that need escaping.
795  * @note The string is stored as a reference, so the constructed object is
796  *       meant to be immediately consumed.
797  */
798 struct escape_string
799 {
800         std::string const &input;
801         escape_string(std::string const &s): input(s) {}
802 };
803
804 /**
805  * Write the string in @a se to @a out if it does not contain any special
806  * characters, a quoted and escaped string otherwise.
807  */
808 static std::ostream &operator<<(std::ostream &out, escape_string const &se)
809 {
810         std::string const &s = se.input;
811         char const *quoted_char = ",: '";
812         char const *escaped_char = "\"\\$!";
813         bool need_quotes = false;
814         char *buf = NULL;
815         size_t len = s.length(), last = 0, j = 0;
816         for (size_t i = 0; i < len; ++i)
817         {
818                 if (strchr(escaped_char, s[i]))
819                 {
820                         need_quotes = true;
821                         if (!buf) buf = new char[len * 2];
822                         memcpy(&buf[j], &s[last], i - last);
823                         j += i - last;
824                         buf[j++] = '\\';
825                         buf[j++] = s[i];
826                         last = i + 1;
827                 }
828                 if (!need_quotes && strchr(quoted_char, s[i]))
829                         need_quotes = true;
830         }
831         if (!need_quotes) return out << s;
832         out << '"';
833         if (!buf) return out << s << '"';
834         out.write(buf, j);
835         out.write(&s[last], len - last);
836         delete[] buf;
837         return out << '"';
838 }
839
840 /**
841  * @defgroup paths Path helpers
842  *
843  * @{
844  */
845
846 /**
847  * Initialize #working_dir.
848  */
849 static void init_working_dir()
850 {
851         char buf[1024];
852         char *res = getcwd(buf, sizeof(buf));
853         if (!res)
854         {
855                 perror("Failed to get working directory");
856                 exit(EXIT_FAILURE);
857         }
858         working_dir = buf;
859 #ifdef WINDOWS
860         for (size_t i = 0, l = working_dir.size(); i != l; ++i)
861         {
862                 if (working_dir[i] == '\\') working_dir[i] = '/';
863         }
864 #endif
865         prefix_dir = working_dir;
866 }
867
868 /**
869  * Initialize #prefix_dir and switch to it.
870  */
871 static void init_prefix_dir()
872 {
873         for (;;)
874         {
875                 struct stat s;
876                 if (stat((prefix_dir + "/Remakefile").c_str(), &s) == 0)
877                 {
878                         if (!changed_prefix_dir) return;
879                         if (chdir(prefix_dir.c_str()))
880                         {
881                                 perror("Failed to change working directory");
882                                 exit(EXIT_FAILURE);
883                         }
884                         if (show_targets)
885                         {
886                                 std::cout << "remake: Entering directory `" << prefix_dir << '\'' << std::endl;
887                         }
888                         return;
889                 }
890                 size_t pos = prefix_dir.find_last_of('/');
891                 if (pos == std::string::npos)
892                 {
893                         std::cerr << "Failed to locate Remakefile in the current directory or one of its parents" << std::endl;
894                         exit(EXIT_FAILURE);
895                 }
896                 prefix_dir.erase(pos);
897                 changed_prefix_dir = true;
898         }
899 }
900
901 /**
902  * Normalize an absolute path with respect to @a p.
903  * Paths outside the subtree are left unchanged.
904  */
905 static std::string normalize_abs(std::string const &s, std::string const &p)
906 {
907         size_t l = p.length();
908         if (s.compare(0, l, p)) return s;
909         size_t ll = s.length();
910         if (ll == l) return ".";
911         if (s[l] != '/')
912         {
913                 size_t pos = s.rfind('/', l);
914                 assert(pos != std::string::npos);
915                 return s.substr(pos + 1);
916         }
917         if (ll == l + 1) return ".";
918         return s.substr(l + 1);
919 }
920
921 /**
922  * Normalize path @a s (possibly relative to @a w) with respect to @a p.
923  *
924  * - If both @a p and @a w are empty, the function just removes ".", "..", "//".
925  * - If only @a p is empty, the function returns an absolute path.
926  */
927 static std::string normalize(std::string const &s, std::string const &w, std::string const &p)
928 {
929 #ifdef WINDOWS
930         char const *delim = "/\\";
931 #else
932         char delim = '/';
933 #endif
934         size_t pos = s.find_first_of(delim);
935         if (pos == std::string::npos && w == p) return s;
936         bool absolute = pos == 0;
937         if (!absolute && w != p && !w.empty())
938                 return normalize(w + '/' + s, w, p);
939         size_t prev = 0, len = s.length();
940         string_list l;
941         for (;;)
942         {
943                 if (pos != prev)
944                 {
945                         std::string n = s.substr(prev, pos - prev);
946                         if (n == "..")
947                         {
948                                 if (!l.empty()) l.pop_back();
949                                 else if (!absolute && !w.empty())
950                                         return normalize(w + '/' + s, w, p);
951                         }
952                         else if (n != ".")
953                                 l.push_back(n);
954                 }
955                 ++pos;
956                 if (pos >= len) break;
957                 prev = pos;
958                 pos = s.find_first_of(delim, prev);
959                 if (pos == std::string::npos) pos = len;
960         }
961         string_list::const_iterator i = l.begin(), i_end = l.end();
962         if (i == i_end) return absolute ? "/" : ".";
963         std::string n;
964         if (absolute) n.push_back('/');
965         n.append(*i);
966         for (++i; i != i_end; ++i)
967         {
968                 n.push_back('/');
969                 n.append(*i);
970         }
971         if (absolute && !p.empty()) return normalize_abs(n, p);
972         return n;
973 }
974
975 /**
976  * Normalize the content of a list of targets.
977  */
978 static void normalize_list(string_list &l, std::string const &w, std::string const &p)
979 {
980         for (string_list::iterator i = l.begin(),
981              i_end = l.end(); i != i_end; ++i)
982         {
983                 *i = normalize(*i, w, p);
984         }
985 }
986
987 /** @} */
988
989 /**
990  * @defgroup lexer Lexer
991  *
992  * @{
993  */
994
995 /**
996  * Skip spaces.
997  */
998 static void skip_spaces(std::istream &in)
999 {
1000         char c;
1001         while (strchr(" \t", (c = in.get()))) {}
1002         if (in.good()) in.putback(c);
1003 }
1004
1005 /**
1006  * Skip empty lines.
1007  */
1008 static void skip_empty(std::istream &in)
1009 {
1010         char c;
1011         while (strchr("\r\n", (c = in.get()))) {}
1012         if (in.good()) in.putback(c);
1013 }
1014
1015 /**
1016  * Skip end of line. If @a multi is true, skip the following empty lines too.
1017  * @return true if there was a line to end.
1018  */
1019 static bool skip_eol(std::istream &in, bool multi = false)
1020 {
1021         char c = in.get();
1022         if (c == '\r') c = in.get();
1023         if (c != '\n' && in.good()) in.putback(c);
1024         if (c != '\n' && !in.eof()) return false;
1025         if (multi) skip_empty(in);
1026         return true;
1027 }
1028
1029 enum
1030 {
1031   Unexpected = 0,
1032   Word       = 1 << 1,
1033   Colon      = 1 << 2,
1034   Equal      = 1 << 3,
1035   Dollarpar  = 1 << 4,
1036   Rightpar   = 1 << 5,
1037   Comma      = 1 << 6,
1038   Plusequal  = 1 << 7,
1039   Pipe       = 1 << 8,
1040 };
1041
1042 /**
1043  * Skip spaces and peek at the next token.
1044  * If it is one of @a mask, skip it (if it is not Word) and return it.
1045  * @note For composite tokens allowed by @a mask, input characters might
1046  *       have been eaten even for an Unexpected result.
1047  */
1048 static int expect_token(std::istream &in, int mask)
1049 {
1050         while (true)
1051         {
1052                 skip_spaces(in);
1053                 char c = in.peek();
1054                 if (!in.good()) return Unexpected;
1055                 int tok;
1056                 switch (c)
1057                 {
1058                 case '\r':
1059                 case '\n': return Unexpected;
1060                 case ':': tok = Colon; break;
1061                 case ',': tok = Comma; break;
1062                 case '=': tok = Equal; break;
1063                 case ')': tok = Rightpar; break;
1064                 case '|': tok = Pipe; break;
1065                 case '$':
1066                         if (!(mask & Dollarpar)) return Unexpected;
1067                         in.ignore(1);
1068                         tok = Dollarpar;
1069                         if (in.peek() != '(') return Unexpected;
1070                         break;
1071                 case '+':
1072                         if (!(mask & Plusequal)) return Unexpected;
1073                         in.ignore(1);
1074                         tok = Plusequal;
1075                         if (in.peek() != '=') return Unexpected;
1076                         break;
1077                 case '\\':
1078                         in.ignore(1);
1079                         if (skip_eol(in)) continue;
1080                         in.putback('\\');
1081                         return mask & Word ? Word : Unexpected;
1082                 default:
1083                         return mask & Word ? Word : Unexpected;
1084                 }
1085                 if (!(tok & mask)) return Unexpected;
1086                 in.ignore(1);
1087                 return tok;
1088         }
1089 }
1090
1091 /**
1092  * Read a (possibly quoted) word.
1093  */
1094 static std::string read_word(std::istream &in, bool detect_equal = true)
1095 {
1096         int c = in.peek();
1097         std::string res;
1098         if (!in.good()) return res;
1099         char const *separators = " \t\r\n$(),:";
1100         bool quoted = c == '"';
1101         if (quoted) in.ignore(1);
1102         bool plus = false;
1103         while (true)
1104         {
1105                 c = in.peek();
1106                 if (!in.good()) return res;
1107                 if (quoted)
1108                 {
1109                         in.ignore(1);
1110                         if (c == '\\')
1111                                 res += in.get();
1112                         else if (c == '"')
1113                                 quoted = false;
1114                         else
1115                                 res += c;
1116                         continue;
1117                 }
1118                 if (detect_equal && c == '=')
1119                 {
1120                         if (plus) in.putback('+');
1121                         return res;
1122                 }
1123                 if (plus)
1124                 {
1125                         res += '+';
1126                         plus = false;
1127                 }
1128                 if (strchr(separators, c)) return res;
1129                 in.ignore(1);
1130                 if (detect_equal && c == '+') plus = true;
1131                 else res += c;
1132         }
1133 }
1134
1135 /** @} */
1136
1137 /**
1138  * @defgroup stream Token streams
1139  *
1140  * @{
1141  */
1142
1143 /**
1144  * Possible results from word producers.
1145  */
1146 enum input_status
1147 {
1148         Success,
1149         SyntaxError,
1150         Eof
1151 };
1152
1153 /**
1154  * Interface for word producers.
1155  */
1156 struct generator
1157 {
1158         virtual ~generator() {}
1159         virtual input_status next(std::string &) = 0;
1160 };
1161
1162 /**
1163  * Generator for the words of a variable.
1164  */
1165 struct variable_generator: generator
1166 {
1167         std::string name;
1168         string_list::const_iterator vcur, vend;
1169         variable_generator(std::string const &, variable_map const *);
1170         input_status next(std::string &);
1171 };
1172
1173 variable_generator::variable_generator(std::string const &n,
1174         variable_map const *local_variables): name(n)
1175 {
1176         if (local_variables)
1177         {
1178                 variable_map::const_iterator i = local_variables->find(name);
1179                 if (i != local_variables->end())
1180                 {
1181                         vcur = i->second.begin();
1182                         vend = i->second.end();
1183                         return;
1184                 }
1185         }
1186         variable_map::const_iterator i = variables.find(name);
1187         if (i == variables.end()) return;
1188         vcur = i->second.begin();
1189         vend = i->second.end();
1190 }
1191
1192 input_status variable_generator::next(std::string &res)
1193 {
1194         if (vcur != vend)
1195         {
1196                 res = *vcur;
1197                 ++vcur;
1198                 return Success;
1199         }
1200         return Eof;
1201 }
1202
1203 /**
1204  * Generator for the words of an input stream.
1205  */
1206 struct input_generator
1207 {
1208         std::istream &in;
1209         generator *nested;
1210         variable_map const *local_variables;
1211         bool earliest_exit, done;
1212         input_generator(std::istream &i, variable_map const *lv, bool e = false)
1213                 : in(i), nested(NULL), local_variables(lv), earliest_exit(e), done(false) {}
1214         input_status next(std::string &);
1215         ~input_generator() { assert(!nested); }
1216 };
1217
1218 static generator *get_function(input_generator const &, std::string const &);
1219
1220 input_status input_generator::next(std::string &res)
1221 {
1222         if (nested)
1223         {
1224                 restart:
1225                 input_status s = nested->next(res);
1226                 if (s == Success) return Success;
1227                 delete nested;
1228                 nested = NULL;
1229                 if (s == SyntaxError) return SyntaxError;
1230         }
1231         if (done) return Eof;
1232         if (earliest_exit) done = true;
1233         switch (expect_token(in, Word | Dollarpar))
1234         {
1235         case Word:
1236                 res = read_word(in, false);
1237                 return Success;
1238         case Dollarpar:
1239         {
1240                 std::string name = read_word(in, false);
1241                 if (name.empty()) return SyntaxError;
1242                 if (expect_token(in, Rightpar))
1243                         nested = new variable_generator(name, local_variables);
1244                 else
1245                 {
1246                         nested = get_function(*this, name);
1247                         if (!nested) return SyntaxError;
1248                 }
1249                 goto restart;
1250         }
1251         default:
1252                 return Eof;
1253         }
1254 }
1255
1256 /**
1257  * Read a list of words from an input generator.
1258  * @return false if a syntax error was encountered.
1259  */
1260 static bool read_words(input_generator &in, string_list &res)
1261 {
1262         while (true)
1263         {
1264                 res.push_back(std::string());
1265                 input_status s = in.next(res.back());
1266                 if (s == Success) continue;
1267                 res.pop_back();
1268                 return s == Eof;
1269         }
1270 }
1271
1272 static bool read_words(std::istream &in, string_list &res)
1273 {
1274         input_generator gen(in, NULL);
1275         return read_words(gen, res);
1276 }
1277
1278 /**
1279  * Generator for the result of function addprefix.
1280  */
1281 struct addprefix_generator: generator
1282 {
1283         input_generator gen;
1284         string_list pre;
1285         string_list::const_iterator prei;
1286         size_t prej, prel;
1287         std::string suf;
1288         addprefix_generator(input_generator const &, bool &);
1289         input_status next(std::string &);
1290 };
1291
1292 addprefix_generator::addprefix_generator(input_generator const &top, bool &ok)
1293         : gen(top.in, top.local_variables)
1294 {
1295         if (!read_words(gen, pre)) return;
1296         if (!expect_token(gen.in, Comma)) return;
1297         prej = 0;
1298         prel = pre.size();
1299         ok = true;
1300 }
1301
1302 input_status addprefix_generator::next(std::string &res)
1303 {
1304         if (prej)
1305         {
1306                 produce:
1307                 if (prej == prel)
1308                 {
1309                         res = *prei + suf;
1310                         prej = 0;
1311                 }
1312                 else
1313                 {
1314                         res = *prei++;
1315                         ++prej;
1316                 }
1317                 return Success;
1318         }
1319         switch (gen.next(res))
1320         {
1321         case Success:
1322                 if (!prel) return Success;
1323                 prei = pre.begin();
1324                 prej = 1;
1325                 suf = res;
1326                 goto produce;
1327         case Eof:
1328                 return expect_token(gen.in, Rightpar) ? Eof : SyntaxError;
1329         default:
1330                 return SyntaxError;
1331         }
1332 }
1333
1334 /**
1335  * Generator for the result of function addsuffix.
1336  */
1337 struct addsuffix_generator: generator
1338 {
1339         input_generator gen;
1340         string_list suf;
1341         string_list::const_iterator sufi;
1342         size_t sufj, sufl;
1343         std::string pre;
1344         addsuffix_generator(input_generator const &, bool &);
1345         input_status next(std::string &);
1346 };
1347
1348 addsuffix_generator::addsuffix_generator(input_generator const &top, bool &ok)
1349         : gen(top.in, top.local_variables)
1350 {
1351         if (!read_words(gen, suf)) return;
1352         if (!expect_token(gen.in, Comma)) return;
1353         sufj = 0;
1354         sufl = suf.size();
1355         ok = true;
1356 }
1357
1358 input_status addsuffix_generator::next(std::string &res)
1359 {
1360         if (sufj)
1361         {
1362                 if (sufj != sufl)
1363                 {
1364                         res = *sufi++;
1365                         ++sufj;
1366                         return Success;
1367                 }
1368                 sufj = 0;
1369         }
1370         switch (gen.next(res))
1371         {
1372         case Success:
1373                 if (!sufl) return Success;
1374                 sufi = suf.begin();
1375                 sufj = 1;
1376                 res += *sufi++;
1377                 return Success;
1378         case Eof:
1379                 return expect_token(gen.in, Rightpar) ? Eof : SyntaxError;
1380         default:
1381                 return SyntaxError;
1382         }
1383 }
1384
1385 /**
1386  * Return a generator for function @a name.
1387  */
1388 static generator *get_function(input_generator const &in, std::string const &name)
1389 {
1390         skip_spaces(in.in);
1391         generator *g = NULL;
1392         bool ok = false;
1393         if (name == "addprefix") g = new addprefix_generator(in, ok);
1394         else if (name == "addsuffix") g = new addsuffix_generator(in, ok);
1395         if (!g || ok) return g;
1396         delete g;
1397         return NULL;
1398 }
1399
1400 /** @} */
1401
1402 /**
1403  * @defgroup database Dependency database
1404  *
1405  * @{
1406  */
1407
1408 /**
1409  * Load dependencies from @a in.
1410  */
1411 static void load_dependencies(std::istream &in)
1412 {
1413         if (false)
1414         {
1415                 error:
1416                 std::cerr << "Failed to load database" << std::endl;
1417                 exit(EXIT_FAILURE);
1418         }
1419
1420         while (!in.eof())
1421         {
1422                 string_list targets;
1423                 if (!read_words(in, targets)) goto error;
1424                 if (in.eof()) return;
1425                 if (targets.empty()) goto error;
1426                 DEBUG << "reading dependencies of target " << targets.front() << std::endl;
1427                 if (in.get() != ':') goto error;
1428                 ref_ptr<dependency_t> dep;
1429                 dep->targets = targets;
1430                 string_list deps;
1431                 if (!read_words(in, deps)) goto error;
1432                 dep->deps.insert(deps.begin(), deps.end());
1433                 for (string_list::const_iterator i = targets.begin(),
1434                      i_end = targets.end(); i != i_end; ++i)
1435                 {
1436                         dependencies[*i] = dep;
1437                 }
1438                 skip_empty(in);
1439         }
1440 }
1441
1442 /**
1443  * Load known dependencies from file <tt>.remake</tt>.
1444  */
1445 static void load_dependencies()
1446 {
1447         DEBUG_open << "Loading database... ";
1448         std::ifstream in(".remake");
1449         if (!in.good())
1450         {
1451                 DEBUG_close << "not found\n";
1452                 return;
1453         }
1454         load_dependencies(in);
1455 }
1456
1457
1458 /**
1459  * Save all the dependencies in file <tt>.remake</tt>.
1460  */
1461 static void save_dependencies()
1462 {
1463         DEBUG_open << "Saving database... ";
1464         std::ofstream db(".remake");
1465         while (!dependencies.empty())
1466         {
1467                 ref_ptr<dependency_t> dep = dependencies.begin()->second;
1468                 for (string_list::const_iterator i = dep->targets.begin(),
1469                      i_end = dep->targets.end(); i != i_end; ++i)
1470                 {
1471                         db << escape_string(*i) << ' ';
1472                         dependencies.erase(*i);
1473                 }
1474                 db << ':';
1475                 for (string_set::const_iterator i = dep->deps.begin(),
1476                      i_end = dep->deps.end(); i != i_end; ++i)
1477                 {
1478                         db << ' ' << escape_string(*i);
1479                 }
1480                 db << std::endl;
1481         }
1482 }
1483
1484 /** @} */
1485
1486 static void merge_rule(rule_t &dest, rule_t const &src);
1487
1488 /**
1489  * @defgroup parser Rule parser
1490  *
1491  * @{
1492  */
1493
1494 /**
1495  * Register a specific rule with an empty script:
1496  *
1497  * - Check that none of the targets already has an associated rule with a
1498  *   nonempty script.
1499  * - Create a new rule with a single target for each target, if needed.
1500  * - Add the prerequisites of @a rule to all these associated rules.
1501  */
1502 static void register_transparent_rule(rule_t const &rule, string_list const &targets)
1503 {
1504         assert(rule.script.empty());
1505         for (string_list::const_iterator i = targets.begin(),
1506              i_end = targets.end(); i != i_end; ++i)
1507         {
1508                 std::pair<rule_map::iterator, bool> j =
1509                         specific_rules.insert(std::make_pair(*i, ref_ptr<rule_t>()));
1510                 ref_ptr<rule_t> &r = j.first->second;
1511                 if (j.second)
1512                 {
1513                         r = ref_ptr<rule_t>(rule);
1514                         r->targets = string_list(1, *i);
1515                         continue;
1516                 }
1517                 if (!r->script.empty())
1518                 {
1519                         std::cerr << "Failed to load rules: " << *i
1520                                 << " cannot be the target of several rules" << std::endl;
1521                         exit(EXIT_FAILURE);
1522                 }
1523                 assert(r->targets.size() == 1 && r->targets.front() == *i);
1524                 merge_rule(*r, rule);
1525         }
1526
1527         for (string_list::const_iterator i = targets.begin(),
1528              i_end = targets.end(); i != i_end; ++i)
1529         {
1530                 ref_ptr<dependency_t> &dep = dependencies[*i];
1531                 if (dep->targets.empty()) dep->targets.push_back(*i);
1532                 dep->deps.insert(rule.deps.begin(), rule.deps.end());
1533         }
1534 }
1535
1536 /**
1537  * Register a specific rule with a nonempty script:
1538  *
1539  * - Check that none of the targets already has an associated rule.
1540  * - Create a single shared rule and associate it to all the targets.
1541  * - Merge the prerequisites of all the targets into a single set and
1542  *   add the prerequisites of the rule to it. (The preexisting
1543  *   prerequisites, if any, come from a previous run.)
1544  */
1545 static void register_scripted_rule(rule_t const &rule)
1546 {
1547         ref_ptr<rule_t> r(rule);
1548         for (string_list::const_iterator i = rule.targets.begin(),
1549              i_end = rule.targets.end(); i != i_end; ++i)
1550         {
1551                 std::pair<rule_map::iterator, bool> j =
1552                         specific_rules.insert(std::make_pair(*i, r));
1553                 if (j.second) continue;
1554                 std::cerr << "Failed to load rules: " << *i
1555                         << " cannot be the target of several rules" << std::endl;
1556                 exit(EXIT_FAILURE);
1557         }
1558
1559         ref_ptr<dependency_t> dep;
1560         dep->targets = rule.targets;
1561         dep->deps.insert(rule.deps.begin(), rule.deps.end());
1562         for (string_list::const_iterator i = rule.targets.begin(),
1563              i_end = rule.targets.end(); i != i_end; ++i)
1564         {
1565                 ref_ptr<dependency_t> &d = dependencies[*i];
1566                 dep->deps.insert(d->deps.begin(), d->deps.end());
1567                 d = dep;
1568         }
1569 }
1570
1571 /**
1572  * Read a rule starting with target @a first, if nonempty.
1573  * Store into #generic_rules or #specific_rules depending on its genericity.
1574  */
1575 static void load_rule(std::istream &in, std::string const &first)
1576 {
1577         DEBUG_open << "Reading rule for target " << first << "... ";
1578         if (false)
1579         {
1580                 error:
1581                 DEBUG_close << "failed\n";
1582                 std::cerr << "Failed to load rules: syntax error" << std::endl;
1583                 exit(EXIT_FAILURE);
1584         }
1585         rule_t rule;
1586
1587         // Read targets and check genericity.
1588         string_list targets;
1589         if (!read_words(in, targets)) goto error;
1590         if (!first.empty()) targets.push_front(first);
1591         else if (targets.empty()) goto error;
1592         else DEBUG << "actual target: " << targets.front() << std::endl;
1593         bool generic = false;
1594         normalize_list(targets, "", "");
1595         for (string_list::const_iterator i = targets.begin(),
1596              i_end = targets.end(); i != i_end; ++i)
1597         {
1598                 if (i->empty()) goto error;
1599                 if ((i->find('%') != std::string::npos) != generic)
1600                 {
1601                         if (i == targets.begin()) generic = true;
1602                         else goto error;
1603                 }
1604         }
1605         std::swap(rule.targets, targets);
1606         skip_spaces(in);
1607         if (in.get() != ':') goto error;
1608
1609         bool assignment = false;
1610
1611         // Read dependencies.
1612         {
1613                 string_list v;
1614                 if (expect_token(in, Word))
1615                 {
1616                         std::string d = read_word(in);
1617                         if (int tok = expect_token(in, Equal | Plusequal))
1618                         {
1619                                 if (!read_words(in, v)) goto error;
1620                                 assign_t &a = rule.assigns[d];
1621                                 a.append = tok == Plusequal;
1622                                 a.value.swap(v);
1623                                 assignment = true;
1624                                 goto end_line;
1625                         }
1626                         v.push_back(d);
1627                 }
1628
1629                 if (!read_words(in, v)) goto error;
1630                 normalize_list(v, "", "");
1631                 rule.deps.swap(v);
1632
1633                 if (expect_token(in, Pipe))
1634                 {
1635                         if (!read_words(in, v)) goto error;
1636                         normalize_list(v, "", "");
1637                         rule.wdeps.swap(v);
1638                 }
1639         }
1640
1641         end_line:
1642         skip_spaces(in);
1643         if (!skip_eol(in, true)) goto error;
1644
1645         // Read script.
1646         std::ostringstream buf;
1647         while (true)
1648         {
1649                 char c = in.get();
1650                 if (!in.good()) break;
1651                 if (c == '\t' || c == ' ')
1652                 {
1653                         in.get(*buf.rdbuf());
1654                         if (in.fail() && !in.eof()) in.clear();
1655                 }
1656                 else if (c == '\r' || c == '\n')
1657                         buf << c;
1658                 else
1659                 {
1660                         in.putback(c);
1661                         break;
1662                 }
1663         }
1664         rule.script = buf.str();
1665
1666         // Add generic rules to the correct set.
1667         if (generic)
1668         {
1669                 if (assignment) goto error;
1670                 generic_rules.push_back(rule);
1671                 return;
1672         }
1673
1674         if (!rule.script.empty())
1675         {
1676                 if (assignment) goto error;
1677                 register_scripted_rule(rule);
1678         }
1679         else
1680         {
1681                 // Swap away the targets to avoid costly copies when registering.
1682                 string_list targets;
1683                 std::swap(rule.targets, targets);
1684                 register_transparent_rule(rule, targets);
1685                 std::swap(rule.targets, targets);
1686         }
1687
1688         // If there is no default target yet, mark it as such.
1689         if (first_target.empty())
1690                 first_target = rule.targets.front();
1691 }
1692
1693 /**
1694  * Load rules from @a remakefile.
1695  * If some rules have dependencies and non-generic targets, add these
1696  * dependencies to the targets.
1697  */
1698 static void load_rules(std::string const &remakefile)
1699 {
1700         DEBUG_open << "Loading rules... ";
1701         if (false)
1702         {
1703                 error:
1704                 std::cerr << "Failed to load rules: syntax error" << std::endl;
1705                 exit(EXIT_FAILURE);
1706         }
1707         std::ifstream in(remakefile.c_str());
1708         if (!in.good())
1709         {
1710                 std::cerr << "Failed to load rules: no Remakefile found" << std::endl;
1711                 exit(EXIT_FAILURE);
1712         }
1713         skip_empty(in);
1714
1715         string_list options;
1716
1717         // Read rules
1718         while (in.good())
1719         {
1720                 char c = in.peek();
1721                 if (c == '#')
1722                 {
1723                         while (in.get() != '\n') {}
1724                         skip_empty(in);
1725                         continue;
1726                 }
1727                 if (c == ' ' || c == '\t') goto error;
1728                 if (expect_token(in, Word))
1729                 {
1730                         std::string name = read_word(in);
1731                         if (name.empty()) goto error;
1732                         if (int tok = expect_token(in, Equal | Plusequal))
1733                         {
1734                                 DEBUG << "Assignment to variable " << name << std::endl;
1735                                 string_list value;
1736                                 if (!read_words(in, value)) goto error;
1737                                 string_list &dest =
1738                                         *(name == ".OPTIONS" ? &options : &variables[name]);
1739                                 if (tok == Equal) dest.swap(value);
1740                                 else dest.splice(dest.end(), value);
1741                                 if (!skip_eol(in, true)) goto error;
1742                         }
1743                         else load_rule(in, name);
1744                 }
1745                 else load_rule(in, std::string());
1746         }
1747
1748         // Set actual options.
1749         for (string_list::const_iterator i = options.begin(),
1750              i_end = options.end(); i != i_end; ++i)
1751         {
1752                 if (*i == "variable-propagation") propagate_vars = true;
1753                 else
1754                 {
1755                         std::cerr << "Failed to load rules: unrecognized option" << std::endl;
1756                         exit(EXIT_FAILURE);
1757                 }
1758         }
1759 }
1760
1761 /** @} */
1762
1763 /**
1764  * @defgroup rules Rule resolution
1765  *
1766  * @{
1767  */
1768
1769 static void merge_rule(rule_t &dest, rule_t const &src)
1770 {
1771         dest.deps.insert(dest.deps.end(), src.deps.begin(), src.deps.end());
1772         dest.wdeps.insert(dest.wdeps.end(), src.wdeps.begin(), src.wdeps.end());
1773         for (assign_map::const_iterator i = src.assigns.begin(),
1774              i_end = src.assigns.end(); i != i_end; ++i)
1775         {
1776                 if (!i->second.append)
1777                 {
1778                         new_assign:
1779                         dest.assigns[i->first] = i->second;
1780                         continue;
1781                 }
1782                 assign_map::iterator j = dest.assigns.find(i->first);
1783                 if (j == dest.assigns.end()) goto new_assign;
1784                 j->second.value.insert(j->second.value.end(),
1785                         i->second.value.begin(), i->second.value.end());
1786         }
1787 }
1788
1789 /**
1790  * Substitute a pattern into a list of strings.
1791  */
1792 static void substitute_pattern(std::string const &pat, string_list const &src, string_list &dst)
1793 {
1794         for (string_list::const_iterator i = src.begin(),
1795              i_end = src.end(); i != i_end; ++i)
1796         {
1797                 size_t pos = i->find('%');
1798                 if (pos == std::string::npos) dst.push_back(*i);
1799                 else dst.push_back(i->substr(0, pos) + pat + i->substr(pos + 1));
1800         }
1801 }
1802
1803 /**
1804  * Find a generic rule matching @a target:
1805  * - the one leading to shorter matches has priority,
1806  * - among equivalent rules, the earliest one has priority.
1807  */
1808 static void find_generic_rule(job_t &job, std::string const &target)
1809 {
1810         size_t tlen = target.length(), plen = tlen + 1;
1811         for (rule_list::const_iterator i = generic_rules.begin(),
1812              i_end = generic_rules.end(); i != i_end; ++i)
1813         {
1814                 for (string_list::const_iterator j = i->targets.begin(),
1815                      j_end = i->targets.end(); j != j_end; ++j)
1816                 {
1817                         size_t len = j->length();
1818                         if (tlen < len) continue;
1819                         if (plen <= tlen - (len - 1)) continue;
1820                         size_t pos = j->find('%');
1821                         if (pos == std::string::npos) continue;
1822                         size_t len2 = len - (pos + 1);
1823                         if (j->compare(0, pos, target, 0, pos) ||
1824                             j->compare(pos + 1, len2, target, tlen - len2, len2))
1825                                 continue;
1826                         plen = tlen - (len - 1);
1827                         job.stem = target.substr(pos, plen);
1828                         job.rule = rule_t();
1829                         job.rule.script = i->script;
1830                         substitute_pattern(job.stem, i->targets, job.rule.targets);
1831                         substitute_pattern(job.stem, i->deps, job.rule.deps);
1832                         substitute_pattern(job.stem, i->wdeps, job.rule.wdeps);
1833                         break;
1834                 }
1835         }
1836 }
1837
1838 /**
1839  * Find a specific rule matching @a target. Return a generic one otherwise.
1840  * If there is both a specific rule with an empty script and a generic rule, the
1841  * generic one is returned after adding the dependencies of the specific one.
1842  */
1843 static void find_rule(job_t &job, std::string const &target)
1844 {
1845         rule_map::const_iterator i = specific_rules.find(target),
1846                 i_end = specific_rules.end();
1847         // If there is a specific rule with a script, return it.
1848         if (i != i_end && !i->second->script.empty())
1849         {
1850                 job.rule = *i->second;
1851                 return;
1852         }
1853         find_generic_rule(job, target);
1854         // If there is no generic rule, return the specific rule (no script), if any.
1855         if (job.rule.targets.empty())
1856         {
1857                 if (i != i_end)
1858                 {
1859                         job.rule = *i->second;
1860                         return;
1861                 }
1862         }
1863         // Optimize the lookup when there is only one target (already looked up).
1864         if (job.rule.targets.size() == 1)
1865         {
1866                 if (i == i_end) return;
1867                 merge_rule(job.rule, *i->second);
1868                 return;
1869         }
1870         // Add the dependencies of the specific rules of every target to the
1871         // generic rule. If any of those rules has a nonempty script, error out.
1872         for (string_list::const_iterator j = job.rule.targets.begin(),
1873              j_end = job.rule.targets.end(); j != j_end; ++j)
1874         {
1875                 i = specific_rules.find(*j);
1876                 if (i == i_end) continue;
1877                 if (!i->second->script.empty()) return;
1878                 merge_rule(job.rule, *i->second);
1879         }
1880 }
1881
1882 /** @} */
1883
1884 /**
1885  * @defgroup status Target status
1886  *
1887  * @{
1888  */
1889
1890 /**
1891  * Compute and memoize the status of @a target:
1892  * - if the file does not exist, the target is obsolete,
1893  * - if any dependency is obsolete or younger than the file, it is obsolete,
1894  * - otherwise it is up-to-date.
1895  *
1896  * @note For rules with multiple targets, all the targets share the same
1897  *       status. (If one is obsolete, they all are.) The second rule above
1898  *       is modified in that case: the latest target is chosen, not the oldest!
1899  */
1900 static status_t const &get_status(std::string const &target)
1901 {
1902         std::pair<status_map::iterator,bool> i =
1903                 status.insert(std::make_pair(target, status_t()));
1904         status_t &ts = i.first->second;
1905         if (!i.second) return ts;
1906         DEBUG_open << "Checking status of " << target << "... ";
1907         dependency_map::const_iterator j = dependencies.find(target);
1908         if (j == dependencies.end())
1909         {
1910                 struct stat s;
1911                 if (stat(target.c_str(), &s) != 0)
1912                 {
1913                         DEBUG_close << "missing\n";
1914                         ts.status = Todo;
1915                         ts.last = 0;
1916                         return ts;
1917                 }
1918                 DEBUG_close << "up-to-date\n";
1919                 ts.status = Uptodate;
1920                 ts.last = s.st_mtime;
1921                 return ts;
1922         }
1923         dependency_t const &dep = *j->second;
1924         status_e st = Uptodate;
1925         time_t latest = 0;
1926         for (string_list::const_iterator k = dep.targets.begin(),
1927              k_end = dep.targets.end(); k != k_end; ++k)
1928         {
1929                 struct stat s;
1930                 if (stat(k->c_str(), &s) != 0)
1931                 {
1932                         if (st == Uptodate) DEBUG_close << *k << " missing\n";
1933                         s.st_mtime = 0;
1934                         st = Todo;
1935                 }
1936                 status[*k].last = s.st_mtime;
1937                 if (s.st_mtime > latest) latest = s.st_mtime;
1938         }
1939         if (st != Uptodate) goto update;
1940         for (string_set::const_iterator k = dep.deps.begin(),
1941              k_end = dep.deps.end(); k != k_end; ++k)
1942         {
1943                 status_t const &ts_ = get_status(*k);
1944                 if (latest < ts_.last)
1945                 {
1946                         DEBUG_close << "older than " << *k << std::endl;
1947                         st = Todo;
1948                         goto update;
1949                 }
1950                 if (ts_.status != Uptodate && st != Recheck)
1951                 {
1952                         DEBUG << "obsolete dependency " << *k << std::endl;
1953                         st = Recheck;
1954                 }
1955         }
1956         if (st == Uptodate) DEBUG_close << "all siblings up-to-date\n";
1957         update:
1958         for (string_list::const_iterator k = dep.targets.begin(),
1959              k_end = dep.targets.end(); k != k_end; ++k)
1960         {
1961                 status[*k].status = st;
1962         }
1963         return ts;
1964 }
1965
1966 /**
1967  * Change the status of @a target to #Remade or #Uptodate depending on whether
1968  * its modification time changed.
1969  */
1970 static void update_status(std::string const &target)
1971 {
1972         DEBUG_open << "Rechecking status of " << target << "... ";
1973         status_map::iterator i = status.find(target);
1974         assert(i != status.end());
1975         status_t &ts = i->second;
1976         ts.status = Remade;
1977         if (ts.last >= now)
1978         {
1979                 DEBUG_close << "possibly remade\n";
1980                 return;
1981         }
1982         struct stat s;
1983         if (stat(target.c_str(), &s) != 0)
1984         {
1985                 DEBUG_close << "missing\n";
1986                 ts.last = 0;
1987         }
1988         else if (s.st_mtime != ts.last)
1989         {
1990                 DEBUG_close << "remade\n";
1991                 ts.last = s.st_mtime;
1992         }
1993         else
1994         {
1995                 DEBUG_close << "unchanged\n";
1996                 ts.status = Uptodate;
1997         }
1998 }
1999
2000 /**
2001  * Check whether all the prerequisites of @a target ended being up-to-date.
2002  */
2003 static bool still_need_rebuild(std::string const &target)
2004 {
2005         DEBUG_open << "Rechecking obsoleteness of " << target << "... ";
2006         status_map::const_iterator i = status.find(target);
2007         assert(i != status.end());
2008         if (i->second.status != Recheck) return true;
2009         dependency_map::const_iterator j = dependencies.find(target);
2010         assert(j != dependencies.end());
2011         dependency_t const &dep = *j->second;
2012         for (string_set::const_iterator k = dep.deps.begin(),
2013              k_end = dep.deps.end(); k != k_end; ++k)
2014         {
2015                 if (status[*k].status != Uptodate) return true;
2016         }
2017         for (string_list::const_iterator k = dep.targets.begin(),
2018              k_end = dep.targets.end(); k != k_end; ++k)
2019         {
2020                 status[*k].status = Uptodate;
2021         }
2022         DEBUG_close << "no longer obsolete\n";
2023         return false;
2024 }
2025
2026 /** @} */
2027
2028 /**
2029  * @defgroup server Server
2030  *
2031  * @{
2032  */
2033
2034 /**
2035  * Handle job completion.
2036  */
2037 static void complete_job(int job_id, bool success)
2038 {
2039         DEBUG << "Completing job " << job_id << '\n';
2040         job_map::iterator i = jobs.find(job_id);
2041         assert(i != jobs.end());
2042         string_list const &targets = i->second.rule.targets;
2043         if (success)
2044         {
2045                 if (show_targets) std::cout << "Finished";
2046                 for (string_list::const_iterator j = targets.begin(),
2047                      j_end = targets.end(); j != j_end; ++j)
2048                 {
2049                         update_status(*j);
2050                         if (show_targets) std::cout << ' ' << *j;
2051                 }
2052                 if (show_targets) std::cout << std::endl;
2053         }
2054         else
2055         {
2056                 std::cerr << "Failed to build";
2057                 for (string_list::const_iterator j = targets.begin(),
2058                      j_end = targets.end(); j != j_end; ++j)
2059                 {
2060                         status[*j].status = Failed;
2061                         std::cerr << ' ' << *j;
2062                         remove(j->c_str());
2063                 }
2064                 std::cerr << std::endl;
2065         }
2066         jobs.erase(i);
2067 }
2068
2069 /**
2070  * Return the script obtained by substituting variables.
2071  */
2072 static std::string prepare_script(job_t const &job)
2073 {
2074         std::string const &s = job.rule.script;
2075         std::istringstream in(s);
2076         std::ostringstream out;
2077         size_t len = s.size();
2078
2079         while (!in.eof())
2080         {
2081                 size_t pos = in.tellg(), p = s.find('$', pos);
2082                 if (p == std::string::npos || p == len - 1) p = len;
2083                 out.write(&s[pos], p - pos);
2084                 if (p == len) break;
2085                 ++p;
2086                 switch (s[p])
2087                 {
2088                 case '$':
2089                         out << '$';
2090                         in.seekg(p + 1);
2091                         break;
2092                 case '<':
2093                         if (!job.rule.deps.empty())
2094                                 out << job.rule.deps.front();
2095                         in.seekg(p + 1);
2096                         break;
2097                 case '^':
2098                 {
2099                         bool first = true;
2100                         for (string_list::const_iterator i = job.rule.deps.begin(),
2101                              i_end = job.rule.deps.end(); i != i_end; ++i)
2102                         {
2103                                 if (first) first = false;
2104                                 else out << ' ';
2105                                 out << *i;
2106                         }
2107                         in.seekg(p + 1);
2108                         break;
2109                 }
2110                 case '@':
2111                         assert(!job.rule.targets.empty());
2112                         out << job.rule.targets.front();
2113                         in.seekg(p + 1);
2114                         break;
2115                 case '*':
2116                         out << job.stem;
2117                         in.seekg(p + 1);
2118                         break;
2119                 case '(':
2120                 {
2121                         in.seekg(p - 1);
2122                         bool first = true;
2123                         input_generator gen(in, &job.vars, true);
2124                         while (true)
2125                         {
2126                                 std::string w;
2127                                 input_status s = gen.next(w);
2128                                 if (s == SyntaxError)
2129                                 {
2130                                         // TODO
2131                                         return "false";
2132                                 }
2133                                 if (s == Eof) break;
2134                                 if (first) first = false;
2135                                 else out << ' ';
2136                                 out << w;
2137                         }
2138                         break;
2139                 }
2140                 default:
2141                         // Let dollars followed by an unrecognized character
2142                         // go through. This differs from Make, which would
2143                         // use a one-letter variable.
2144                         out << '$';
2145                         in.seekg(p);
2146                 }
2147         }
2148
2149         return out.str();
2150 }
2151
2152 /**
2153  * Execute the script from @a rule.
2154  */
2155 static status_e run_script(int job_id, job_t const &job)
2156 {
2157         ref_ptr<dependency_t> dep;
2158         dep->targets = job.rule.targets;
2159         dep->deps.insert(job.rule.deps.begin(), job.rule.deps.end());
2160         if (show_targets) std::cout << "Building";
2161         for (string_list::const_iterator i = job.rule.targets.begin(),
2162              i_end = job.rule.targets.end(); i != i_end; ++i)
2163         {
2164                 dependencies[*i] = dep;
2165                 if (show_targets) std::cout << ' ' << *i;
2166         }
2167         if (show_targets) std::cout << std::endl;
2168
2169         std::string script = prepare_script(job);
2170
2171         std::ostringstream job_id_buf;
2172         job_id_buf << job_id;
2173         std::string job_id_ = job_id_buf.str();
2174
2175         DEBUG_open << "Starting script for job " << job_id << "... ";
2176         if (script.empty())
2177         {
2178                 DEBUG_close << "no script\n";
2179                 complete_job(job_id, true);
2180                 return Remade;
2181         }
2182
2183         if (false)
2184         {
2185                 error:
2186                 DEBUG_close << "failed\n";
2187                 complete_job(job_id, false);
2188                 return Failed;
2189         }
2190
2191 #ifdef WINDOWS
2192         HANDLE pfd[2];
2193         if (false)
2194         {
2195                 error2:
2196                 CloseHandle(pfd[0]);
2197                 CloseHandle(pfd[1]);
2198                 goto error;
2199         }
2200         if (!CreatePipe(&pfd[0], &pfd[1], NULL, 0))
2201                 goto error;
2202         if (!SetHandleInformation(pfd[0], HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT))
2203                 goto error2;
2204         STARTUPINFO si;
2205         ZeroMemory(&si, sizeof(STARTUPINFO));
2206         si.cb = sizeof(STARTUPINFO);
2207         si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
2208         si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
2209         si.hStdInput = pfd[0];
2210         si.dwFlags |= STARTF_USESTDHANDLES;
2211         PROCESS_INFORMATION pi;
2212         ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
2213         if (!SetEnvironmentVariable("REMAKE_JOB_ID", job_id_.c_str()))
2214                 goto error2;
2215         char const *argv = echo_scripts ? "SH.EXE -e -s -v" : "SH.EXE -e -s";
2216         if (!CreateProcess(NULL, (char *)argv, NULL, NULL,
2217             true, 0, NULL, NULL, &si, &pi))
2218         {
2219                 goto error2;
2220         }
2221         CloseHandle(pi.hThread);
2222         DWORD len = script.length(), wlen;
2223         if (!WriteFile(pfd[1], script.c_str(), len, &wlen, NULL) || wlen < len)
2224                 std::cerr << "Unexpected failure while sending script to shell" << std::endl;
2225         CloseHandle(pfd[0]);
2226         CloseHandle(pfd[1]);
2227         ++running_jobs;
2228         job_pids[pi.hProcess] = job_id;
2229         return Running;
2230 #else
2231         int pfd[2];
2232         if (false)
2233         {
2234                 error2:
2235                 close(pfd[0]);
2236                 close(pfd[1]);
2237                 goto error;
2238         }
2239         if (pipe(pfd) == -1)
2240                 goto error;
2241         if (setenv("REMAKE_JOB_ID", job_id_.c_str(), 1))
2242                 goto error2;
2243         if (pid_t pid = vfork())
2244         {
2245                 if (pid == -1) goto error2;
2246                 ssize_t len = script.length();
2247                 if (write(pfd[1], script.c_str(), len) < len)
2248                         std::cerr << "Unexpected failure while sending script to shell" << std::endl;
2249                 close(pfd[0]);
2250                 close(pfd[1]);
2251                 ++running_jobs;
2252                 job_pids[pid] = job_id;
2253                 return Running;
2254         }
2255         // Child process starts here. Notice the use of vfork above.
2256         char const *argv[5] = { "sh", "-e", "-s", NULL, NULL };
2257         if (echo_scripts) argv[3] = "-v";
2258         close(pfd[1]);
2259         if (pfd[0] != 0)
2260         {
2261                 dup2(pfd[0], 0);
2262                 close(pfd[0]);
2263         }
2264         execve("/bin/sh", (char **)argv, environ);
2265         _exit(EXIT_FAILURE);
2266 #endif
2267 }
2268
2269 /**
2270  * Create a job for @a target according to the loaded rules.
2271  * Mark all the targets from the rule as running and reset their dependencies.
2272  * Inherit variables from @a current, if enabled.
2273  * If the rule has dependencies, create a new client to build them just
2274  * before @a current, and change @a current so that it points to it.
2275  */
2276 static status_e start(std::string const &target, client_list::iterator &current)
2277 {
2278         int job_id = job_counter++;
2279         DEBUG_open << "Starting job " << job_id << " for " << target << "... ";
2280         job_t &job = jobs[job_id];
2281         find_rule(job, target);
2282         if (job.rule.targets.empty())
2283         {
2284                 status[target].status = Failed;
2285                 DEBUG_close << "failed\n";
2286                 std::cerr << "No rule for building " << target << std::endl;
2287                 return Failed;
2288         }
2289         for (string_list::const_iterator i = job.rule.targets.begin(),
2290              i_end = job.rule.targets.end(); i != i_end; ++i)
2291         {
2292                 status[*i].status = Running;
2293         }
2294         if (propagate_vars) job.vars = current->vars;
2295         for (assign_map::const_iterator i = job.rule.assigns.begin(),
2296              i_end = job.rule.assigns.end(); i != i_end; ++i)
2297         {
2298                 std::pair<variable_map::iterator, bool> k =
2299                         job.vars.insert(std::make_pair(i->first, string_list()));
2300                 string_list &v = k.first->second;
2301                 if (i->second.append)
2302                 {
2303                         if (k.second)
2304                         {
2305                                 variable_map::const_iterator j = variables.find(i->first);
2306                                 if (j != variables.end()) v = j->second;
2307                         }
2308                 }
2309                 else if (!k.second) v.clear();
2310                 v.insert(v.end(), i->second.value.begin(), i->second.value.end());
2311         }
2312         if (!job.rule.deps.empty() || !job.rule.wdeps.empty())
2313         {
2314                 current = clients.insert(current, client_t());
2315                 current->job_id = job_id;
2316                 current->pending = job.rule.deps;
2317                 current->pending.insert(current->pending.end(),
2318                         job.rule.wdeps.begin(), job.rule.wdeps.end());
2319                 if (propagate_vars) current->vars = job.vars;
2320                 current->delayed = true;
2321                 return Recheck;
2322         }
2323         return run_script(job_id, job);
2324 }
2325
2326 /**
2327  * Send a reply to a client then remove it.
2328  * If the client was a dependency client, start the actual script.
2329  */
2330 static void complete_request(client_t &client, bool success)
2331 {
2332         DEBUG_open << "Completing request from client of job " << client.job_id << "... ";
2333         if (client.delayed)
2334         {
2335                 assert(client.socket == INVALID_SOCKET);
2336                 if (success)
2337                 {
2338                         job_map::const_iterator i = jobs.find(client.job_id);
2339                         assert(i != jobs.end());
2340                         if (still_need_rebuild(i->second.rule.targets.front()))
2341                                 run_script(client.job_id, i->second);
2342                         else complete_job(client.job_id, true);
2343                 }
2344                 else complete_job(client.job_id, false);
2345         }
2346         else if (client.socket != INVALID_SOCKET)
2347         {
2348                 char res = success ? 1 : 0;
2349                 send(client.socket, &res, 1, MSG_NOSIGNAL);
2350         #ifdef WINDOWS
2351                 closesocket(client.socket);
2352         #else
2353                 close(client.socket);
2354         #endif
2355                 --waiting_jobs;
2356         }
2357
2358         if (client.job_id < 0 && !success) build_failure = true;
2359 }
2360
2361 /**
2362  * Return whether there are slots for starting new jobs.
2363  */
2364 static bool has_free_slots()
2365 {
2366         if (max_active_jobs <= 0) return true;
2367         return running_jobs - waiting_jobs < max_active_jobs;
2368 }
2369
2370 /**
2371  * Handle client requests:
2372  * - check for running targets that have finished,
2373  * - start as many pending targets as allowed,
2374  * - complete the request if there are neither running nor pending targets
2375  *   left or if any of them failed.
2376  *
2377  * @return true if some child processes are still running.
2378  *
2379  * @post If there are pending requests, at least one child process is running.
2380  *
2381  * @invariant New free slots cannot appear during a run, since the only way to
2382  *            decrease #running_jobs is #finalize_job and the only way to
2383  *            increase #waiting_jobs is #accept_client. None of these functions
2384  *            are called during a run. So breaking out as soon as there no free
2385  *            slots left is fine.
2386  */
2387 static bool handle_clients()
2388 {
2389         DEBUG_open << "Handling client requests... ";
2390         restart:
2391         bool need_restart = false;
2392
2393         for (client_list::iterator i = clients.begin(), i_next = i,
2394              i_end = clients.end(); i != i_end && has_free_slots(); i = i_next)
2395         {
2396                 ++i_next;
2397                 DEBUG_open << "Handling client from job " << i->job_id << "... ";
2398
2399                 // Remove running targets that have finished.
2400                 for (string_set::iterator j = i->running.begin(), j_next = j,
2401                      j_end = i->running.end(); j != j_end; j = j_next)
2402                 {
2403                         ++j_next;
2404                         status_map::const_iterator k = status.find(*j);
2405                         assert(k != status.end());
2406                         switch (k->second.status)
2407                         {
2408                         case Running:
2409                                 break;
2410                         case Failed:
2411                                 i->failed = true;
2412                                 if (!keep_going) goto complete;
2413                                 // no break
2414                         case Uptodate:
2415                         case Remade:
2416                                 i->running.erase(j);
2417                                 break;
2418                         case Recheck:
2419                         case Todo:
2420                                 assert(false);
2421                         }
2422                 }
2423
2424                 // Start pending targets.
2425                 while (!i->pending.empty())
2426                 {
2427                         std::string target = i->pending.front();
2428                         i->pending.pop_front();
2429                         switch (get_status(target).status)
2430                         {
2431                         case Running:
2432                                 i->running.insert(target);
2433                                 break;
2434                         case Failed:
2435                                 pending_failed:
2436                                 i->failed = true;
2437                                 if (!keep_going) goto complete;
2438                                 // no break
2439                         case Uptodate:
2440                         case Remade:
2441                                 break;
2442                         case Recheck:
2443                         case Todo:
2444                                 client_list::iterator j = i;
2445                                 switch (start(target, i))
2446                                 {
2447                                 case Failed:
2448                                         goto pending_failed;
2449                                 case Running:
2450                                         // A shell was started, check for free slots.
2451                                         j->running.insert(target);
2452                                         if (!has_free_slots()) return true;
2453                                         break;
2454                                 case Recheck:
2455                                         // Switch to the dependency client that was inserted.
2456                                         j->running.insert(target);
2457                                         i_next = j;
2458                                         break;
2459                                 case Remade:
2460                                         // Nothing to run.
2461                                         need_restart = true;
2462                                         break;
2463                                 default:
2464                                         assert(false);
2465                                 }
2466                         }
2467                 }
2468
2469                 // Try to complete the request.
2470                 // (This might start a new job if it was a dependency client.)
2471                 if (i->running.empty() || i->failed)
2472                 {
2473                         complete:
2474                         complete_request(*i, !i->failed);
2475                         DEBUG_close << (i->failed ? "failed\n" : "finished\n");
2476                         clients.erase(i);
2477                         need_restart = true;
2478                 }
2479         }
2480
2481         if (running_jobs != waiting_jobs) return true;
2482         if (running_jobs == 0 && clients.empty()) return false;
2483         if (need_restart) goto restart;
2484
2485         // There is a circular dependency.
2486         // Try to break it by completing one of the requests.
2487         assert(!clients.empty());
2488         std::cerr << "Circular dependency detected" << std::endl;
2489         client_list::iterator i = clients.begin();
2490         complete_request(*i, false);
2491         clients.erase(i);
2492         goto restart;
2493 }
2494
2495 /**
2496  * Create a named unix socket that listens for build requests. Also set
2497  * the REMAKE_SOCKET environment variable that will be inherited by all
2498  * the job scripts.
2499  */
2500 static void create_server()
2501 {
2502         if (false)
2503         {
2504                 error:
2505                 perror("Failed to create server");
2506 #ifndef WINDOWS
2507                 error2:
2508 #endif
2509                 exit(EXIT_FAILURE);
2510         }
2511         DEBUG_open << "Creating server... ";
2512
2513 #ifdef WINDOWS
2514         // Prepare a windows socket.
2515         struct sockaddr_in socket_addr;
2516         socket_addr.sin_family = AF_INET;
2517         socket_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2518         socket_addr.sin_port = 0;
2519
2520         // Create and listen to the socket.
2521         socket_fd = socket(AF_INET, SOCK_STREAM, 0);
2522         if (socket_fd == INVALID_SOCKET) goto error;
2523         if (!SetHandleInformation((HANDLE)socket_fd, HANDLE_FLAG_INHERIT, 0))
2524                 goto error;
2525         if (bind(socket_fd, (struct sockaddr *)&socket_addr, sizeof(sockaddr_in)))
2526                 goto error;
2527         int len = sizeof(sockaddr_in);
2528         if (getsockname(socket_fd, (struct sockaddr *)&socket_addr, &len))
2529                 goto error;
2530         std::ostringstream buf;
2531         buf << socket_addr.sin_port;
2532         if (!SetEnvironmentVariable("REMAKE_SOCKET", buf.str().c_str()))
2533                 goto error;
2534         if (listen(socket_fd, 1000)) goto error;
2535 #else
2536         // Set signal handlers for SIGCHLD and SIGINT.
2537         // Block SIGCHLD (unblocked during select).
2538         sigset_t sigmask;
2539         sigemptyset(&sigmask);
2540         sigaddset(&sigmask, SIGCHLD);
2541         if (sigprocmask(SIG_BLOCK, &sigmask, NULL) == -1) goto error;
2542         struct sigaction sa;
2543         sa.sa_flags = 0;
2544         sigemptyset(&sa.sa_mask);
2545         sa.sa_handler = &sigchld_handler;
2546         if (sigaction(SIGCHLD, &sa, NULL) == -1) goto error;
2547         sa.sa_handler = &sigint_handler;
2548         if (sigaction(SIGINT, &sa, NULL) == -1) goto error;
2549
2550         // Prepare a named unix socket in temporary directory.
2551         socket_name = tempnam(NULL, "rmk-");
2552         if (!socket_name) goto error2;
2553         struct sockaddr_un socket_addr;
2554         size_t len = strlen(socket_name);
2555         if (len >= sizeof(socket_addr.sun_path) - 1) goto error2;
2556         socket_addr.sun_family = AF_UNIX;
2557         strcpy(socket_addr.sun_path, socket_name);
2558         len += sizeof(socket_addr.sun_family);
2559         if (setenv("REMAKE_SOCKET", socket_name, 1)) goto error;
2560
2561         // Create and listen to the socket.
2562 #ifdef LINUX
2563         socket_fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
2564         if (socket_fd == INVALID_SOCKET) goto error;
2565 #else
2566         socket_fd = socket(AF_UNIX, SOCK_STREAM, 0);
2567         if (socket_fd == INVALID_SOCKET) goto error;
2568         if (fcntl(socket_fd, F_SETFD, FD_CLOEXEC) < 0) goto error;
2569 #endif
2570         if (bind(socket_fd, (struct sockaddr *)&socket_addr, len))
2571                 goto error;
2572         if (listen(socket_fd, 1000)) goto error;
2573 #endif
2574 }
2575
2576 /**
2577  * Accept a connection from a client, get the job it spawned from,
2578  * get the targets, and mark them as dependencies of the job targets.
2579  */
2580 static void accept_client()
2581 {
2582         DEBUG_open << "Handling client request... ";
2583
2584         // Accept connection.
2585 #ifdef WINDOWS
2586         socket_t fd = accept(socket_fd, NULL, NULL);
2587         if (fd == INVALID_SOCKET) return;
2588         if (!SetHandleInformation((HANDLE)fd, HANDLE_FLAG_INHERIT, 0))
2589         {
2590                 error2:
2591                 std::cerr << "Unexpected failure while setting connection with client" << std::endl;
2592                 closesocket(fd);
2593                 return;
2594         }
2595         // WSAEventSelect puts sockets into nonblocking mode, so disable it here.
2596         u_long nbio = 0;
2597         if (ioctlsocket(fd, FIONBIO, &nbio)) goto error2;
2598 #elif defined(LINUX)
2599         int fd = accept4(socket_fd, NULL, NULL, SOCK_CLOEXEC);
2600         if (fd < 0) return;
2601 #else
2602         int fd = accept(socket_fd, NULL, NULL);
2603         if (fd < 0) return;
2604         if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) return;
2605 #endif
2606         clients.push_front(client_t());
2607         client_list::iterator proc = clients.begin();
2608
2609         if (false)
2610         {
2611                 error:
2612                 DEBUG_close << "failed\n";
2613                 std::cerr << "Received an ill-formed client message" << std::endl;
2614         #ifdef WINDOWS
2615                 closesocket(fd);
2616         #else
2617                 close(fd);
2618         #endif
2619                 clients.erase(proc);
2620                 return;
2621         }
2622
2623         // Receive message. Stop when encountering two nuls in a row.
2624         std::vector<char> buf;
2625         size_t len = 0;
2626         while (len < sizeof(int) + 2 || buf[len - 1] || buf[len - 2])
2627         {
2628                 buf.resize(len + 1024);
2629                 ssize_t l = recv(fd, &buf[0] + len, 1024, 0);
2630                 if (l <= 0) goto error;
2631                 len += l;
2632         }
2633
2634         // Parse job that spawned the client.
2635         int job_id;
2636         memcpy(&job_id, &buf[0], sizeof(int));
2637         proc->socket = fd;
2638         proc->job_id = job_id;
2639         job_map::const_iterator i = jobs.find(job_id);
2640         if (i == jobs.end()) goto error;
2641         DEBUG << "receiving request from job " << job_id << std::endl;
2642         if (propagate_vars) proc->vars = i->second.vars;
2643
2644         // Parse the targets and the variable assignments.
2645         // Mark the targets as dependencies of the job targets.
2646         dependency_t &dep = *dependencies[i->second.rule.targets.front()];
2647         string_list *last_var = NULL;
2648         char const *p = &buf[0] + sizeof(int);
2649         while (true)
2650         {
2651                 len = strlen(p);
2652                 if (len == 0)
2653                 {
2654                         ++waiting_jobs;
2655                         break;
2656                 }
2657                 switch (*p)
2658                 {
2659                 case 'T':
2660                 {
2661                         if (len == 1) goto error;
2662                         std::string target(p + 1, p + len);
2663                         DEBUG << "adding dependency " << target << " to job\n";
2664                         proc->pending.push_back(target);
2665                         dep.deps.insert(target);
2666                         break;
2667                 }
2668                 case 'V':
2669                 {
2670                         if (len == 1) goto error;
2671                         std::string var(p + 1, p + len);
2672                         DEBUG << "adding variable " << var << " to job\n";
2673                         last_var = &proc->vars[var];
2674                         last_var->clear();
2675                         break;
2676                 }
2677                 case 'W':
2678                 {
2679                         if (!last_var) goto error;
2680                         last_var->push_back(std::string(p + 1, p + len));
2681                         break;
2682                 }
2683                 default:
2684                         goto error;
2685                 }
2686                 p += len + 1;
2687         }
2688
2689         if (!propagate_vars && !proc->vars.empty())
2690         {
2691                 std::cerr << "Assignments are ignored unless 'variable-propagation' is enabled" << std::endl;
2692                 proc->vars.clear();
2693         }
2694 }
2695
2696 /**
2697  * Handle child process exit status.
2698  */
2699 static void finalize_job(pid_t pid, bool res)
2700 {
2701         pid_job_map::iterator i = job_pids.find(pid);
2702         assert(i != job_pids.end());
2703         int job_id = i->second;
2704         job_pids.erase(i);
2705         --running_jobs;
2706         complete_job(job_id, res);
2707 }
2708
2709 /**
2710  * Loop until all the jobs have finished.
2711  *
2712  * @post There are no client requests left, not even virtual ones.
2713  */
2714 static void server_loop()
2715 {
2716         while (handle_clients())
2717         {
2718                 DEBUG_open << "Handling events... ";
2719         #ifdef WINDOWS
2720                 size_t len = job_pids.size() + 1;
2721                 HANDLE h[len];
2722                 int num = 0;
2723                 for (pid_job_map::const_iterator i = job_pids.begin(),
2724                      i_end = job_pids.end(); i != i_end; ++i, ++num)
2725                 {
2726                         h[num] = i->first;
2727                 }
2728                 WSAEVENT aev = WSACreateEvent();
2729                 h[num] = aev;
2730                 WSAEventSelect(socket_fd, aev, FD_ACCEPT);
2731                 DWORD w = WaitForMultipleObjects(len, h, false, INFINITE);
2732                 WSAEventSelect(socket_fd, aev, 0);
2733                 WSACloseEvent(aev);
2734                 if (len <= w)
2735                         continue;
2736                 if (w == len - 1)
2737                 {
2738                         accept_client();
2739                         continue;
2740                 }
2741                 pid_t pid = h[w];
2742                 DWORD s = 0;
2743                 bool res = GetExitCodeProcess(pid, &s) && s == 0;
2744                 CloseHandle(pid);
2745                 finalize_job(pid, res);
2746         #else
2747                 sigset_t emptymask;
2748                 sigemptyset(&emptymask);
2749                 fd_set fdset;
2750                 FD_ZERO(&fdset);
2751                 FD_SET(socket_fd, &fdset);
2752                 int ret = pselect(socket_fd + 1, &fdset, NULL, NULL, NULL, &emptymask);
2753                 if (ret > 0 /* && FD_ISSET(socket_fd, &fdset)*/) accept_client();
2754                 if (!got_SIGCHLD) continue;
2755                 got_SIGCHLD = 0;
2756                 pid_t pid;
2757                 int status;
2758                 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
2759                 {
2760                         bool res = WIFEXITED(status) && WEXITSTATUS(status) == 0;
2761                         finalize_job(pid, res);
2762                 }
2763         #endif
2764         }
2765
2766         assert(clients.empty());
2767 }
2768
2769 /**
2770  * Load dependencies and rules, listen to client requests, and loop until
2771  * all the requests have completed.
2772  * If Remakefile is obsolete, perform a first run with it only, then reload
2773  * the rules, and perform a second with the original clients.
2774  */
2775 static void server_mode(std::string const &remakefile, string_list const &targets)
2776 {
2777         load_dependencies();
2778         load_rules(remakefile);
2779         create_server();
2780         if (get_status(remakefile).status != Uptodate)
2781         {
2782                 clients.push_back(client_t());
2783                 clients.back().pending.push_back(remakefile);
2784                 server_loop();
2785                 if (build_failure) goto early_exit;
2786                 variables.clear();
2787                 specific_rules.clear();
2788                 generic_rules.clear();
2789                 first_target.clear();
2790                 load_rules(remakefile);
2791         }
2792         clients.push_back(client_t());
2793         if (!targets.empty()) clients.back().pending = targets;
2794         else if (!first_target.empty())
2795                 clients.back().pending.push_back(first_target);
2796         server_loop();
2797         early_exit:
2798         close(socket_fd);
2799 #ifndef WINDOWS
2800         remove(socket_name);
2801         free(socket_name);
2802 #endif
2803         save_dependencies();
2804         if (show_targets && changed_prefix_dir)
2805         {
2806                 std::cout << "remake: Leaving directory `" << prefix_dir << '\'' << std::endl;
2807         }
2808         exit(build_failure ? EXIT_FAILURE : EXIT_SUCCESS);
2809 }
2810
2811 /** @} */
2812
2813 /**
2814  * @defgroup client Client
2815  *
2816  * @{
2817  */
2818
2819 /**
2820  * Connect to the server @a socket_name, send a request for building @a targets
2821  * with some @a variables, and exit with the status returned by the server.
2822  */
2823 static void client_mode(char *socket_name, string_list const &targets)
2824 {
2825         if (false)
2826         {
2827                 error:
2828                 perror("Failed to send targets to server");
2829                 exit(EXIT_FAILURE);
2830         }
2831         if (targets.empty()) exit(EXIT_SUCCESS);
2832         DEBUG_open << "Connecting to server... ";
2833
2834         // Connect to server.
2835 #ifdef WINDOWS
2836         struct sockaddr_in socket_addr;
2837         socket_fd = socket(AF_INET, SOCK_STREAM, 0);
2838         if (socket_fd == INVALID_SOCKET) goto error;
2839         socket_addr.sin_family = AF_INET;
2840         socket_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2841         socket_addr.sin_port = atoi(socket_name);
2842         if (connect(socket_fd, (struct sockaddr *)&socket_addr, sizeof(sockaddr_in)))
2843                 goto error;
2844 #else
2845         struct sockaddr_un socket_addr;
2846         size_t len = strlen(socket_name);
2847         if (len >= sizeof(socket_addr.sun_path) - 1) exit(EXIT_FAILURE);
2848         socket_fd = socket(AF_UNIX, SOCK_STREAM, 0);
2849         if (socket_fd == INVALID_SOCKET) goto error;
2850         socket_addr.sun_family = AF_UNIX;
2851         strcpy(socket_addr.sun_path, socket_name);
2852         if (connect(socket_fd, (struct sockaddr *)&socket_addr, sizeof(socket_addr.sun_family) + len))
2853                 goto error;
2854 #ifdef MACOSX
2855         int set_option = 1;
2856         if (setsockopt(socket_fd, SOL_SOCKET, SO_NOSIGPIPE, &set_option, sizeof(set_option)))
2857                 goto error;
2858 #endif
2859 #endif
2860
2861         // Send current job id.
2862         char *id = getenv("REMAKE_JOB_ID");
2863         int job_id = id ? atoi(id) : -1;
2864         if (send(socket_fd, (char *)&job_id, sizeof(job_id), MSG_NOSIGNAL) != sizeof(job_id))
2865                 goto error;
2866
2867         // Send targets.
2868         for (string_list::const_iterator i = targets.begin(),
2869              i_end = targets.end(); i != i_end; ++i)
2870         {
2871                 DEBUG_open << "Sending target " << *i << "... ";
2872                 std::string s = 'T' + *i;
2873                 ssize_t len = s.length() + 1;
2874                 if (send(socket_fd, s.c_str(), len, MSG_NOSIGNAL) != len)
2875                         goto error;
2876         }
2877
2878         // Send variables.
2879         for (variable_map::const_iterator i = variables.begin(),
2880              i_end = variables.end(); i != i_end; ++i)
2881         {
2882                 DEBUG_open << "Sending variable " << i->first << "... ";
2883                 std::string s = 'V' + i->first;
2884                 ssize_t len = s.length() + 1;
2885                 if (send(socket_fd, s.c_str(), len, MSG_NOSIGNAL) != len)
2886                         goto error;
2887                 for (string_list::const_iterator j = i->second.begin(),
2888                      j_end = i->second.end(); j != j_end; ++j)
2889                 {
2890                         std::string s = 'W' + *j;
2891                         len = s.length() + 1;
2892                         if (send(socket_fd, s.c_str(), len, MSG_NOSIGNAL) != len)
2893                                 goto error;
2894                 }
2895         }
2896
2897         // Send terminating nul and wait for reply.
2898         char result = 0;
2899         if (send(socket_fd, &result, 1, MSG_NOSIGNAL) != 1) goto error;
2900         if (recv(socket_fd, &result, 1, 0) != 1) exit(EXIT_FAILURE);
2901         exit(result ? EXIT_SUCCESS : EXIT_FAILURE);
2902 }
2903
2904 /** @} */
2905
2906 /**
2907  * @defgroup ui User interface
2908  *
2909  * @{
2910  */
2911
2912 /**
2913  * Display usage and exit with @a exit_status.
2914  */
2915 static void usage(int exit_status)
2916 {
2917         std::cerr << "Usage: remake [options] [target] ...\n"
2918                 "Options\n"
2919                 "  -d                     Echo script commands.\n"
2920                 "  -d -d                  Print lots of debugging information.\n"
2921                 "  -f FILE                Read FILE as Remakefile.\n"
2922                 "  -h, --help             Print this message and exit.\n"
2923                 "  -j[N], --jobs=[N]      Allow N jobs at once; infinite jobs with no arg.\n"
2924                 "  -k                     Keep going when some targets cannot be made.\n"
2925                 "  -r                     Look up targets from the dependencies on stdin.\n"
2926                 "  -s, --silent, --quiet  Do not echo targets.\n";
2927         exit(exit_status);
2928 }
2929
2930 /**
2931  * This program behaves in two different ways.
2932  *
2933  * - If the environment contains the REMAKE_SOCKET variable, the client
2934  *   connects to this socket and sends to the server its build targets.
2935  *   It exits once it receives the server reply.
2936  *
2937  * - Otherwise, it creates a server that waits for build requests. It
2938  *   also creates a pseudo-client that requests the targets passed on the
2939  *   command line.
2940  */
2941 int main(int argc, char *argv[])
2942 {
2943         std::string remakefile;
2944         string_list targets;
2945         bool literal_targets = false;
2946         bool indirect_targets = false;
2947
2948         // Parse command-line arguments.
2949         for (int i = 1; i < argc; ++i)
2950         {
2951                 std::string arg = argv[i];
2952                 if (arg.empty()) usage(EXIT_FAILURE);
2953                 if (literal_targets) goto new_target;
2954                 if (arg == "-h" || arg == "--help") usage(EXIT_SUCCESS);
2955                 if (arg == "-d")
2956                         if (echo_scripts) debug.active = true;
2957                         else echo_scripts = true;
2958                 else if (arg == "-k" || arg =="--keep-going")
2959                         keep_going = true;
2960                 else if (arg == "-s" || arg == "--silent" || arg == "--quiet")
2961                         show_targets = false;
2962                 else if (arg == "-r")
2963                         indirect_targets = true;
2964                 else if (arg == "-f")
2965                 {
2966                         if (++i == argc) usage(EXIT_FAILURE);
2967                         remakefile = argv[i];
2968                 }
2969                 else if (arg == "--")
2970                         literal_targets = true;
2971                 else if (arg.compare(0, 2, "-j") == 0)
2972                         max_active_jobs = atoi(arg.c_str() + 2);
2973                 else if (arg.compare(0, 7, "--jobs=") == 0)
2974                         max_active_jobs = atoi(arg.c_str() + 7);
2975                 else
2976                 {
2977                         if (arg[0] == '-') usage(EXIT_FAILURE);
2978                         if (arg.find('=') != std::string::npos)
2979                         {
2980                                 std::istringstream in(arg);
2981                                 std::string name = read_word(in);
2982                                 if (name.empty() || !expect_token(in, Equal)) usage(EXIT_FAILURE);
2983                                 read_words(in, variables[name]);
2984                                 continue;
2985                         }
2986                         new_target:
2987                         targets.push_back(arg);
2988                         DEBUG << "New target: " << arg << '\n';
2989                 }
2990         }
2991
2992         init_working_dir();
2993         normalize_list(targets, working_dir, working_dir);
2994
2995         if (indirect_targets)
2996         {
2997                 load_dependencies(std::cin);
2998                 string_list l;
2999                 targets.swap(l);
3000                 if (l.empty() && !dependencies.empty())
3001                 {
3002                         l.push_back(dependencies.begin()->second->targets.front());
3003                 }
3004                 for (string_list::const_iterator i = l.begin(),
3005                      i_end = l.end(); i != i_end; ++i)
3006                 {
3007                         dependency_map::const_iterator j = dependencies.find(*i);
3008                         if (j == dependencies.end()) continue;
3009                         dependency_t const &dep = *j->second;
3010                         for (string_set::const_iterator k = dep.deps.begin(),
3011                              k_end = dep.deps.end(); k != k_end; ++k)
3012                         {
3013                                 targets.push_back(normalize(*k, working_dir, working_dir));
3014                         }
3015                 }
3016                 dependencies.clear();
3017         }
3018
3019 #ifdef WINDOWS
3020         WSADATA wsaData;
3021         if (WSAStartup(MAKEWORD(2,2), &wsaData))
3022         {
3023                 std::cerr << "Unexpected failure while initializing Windows Socket" << std::endl;
3024                 return 1;
3025         }
3026 #endif
3027
3028         // Run as client if REMAKE_SOCKET is present in the environment.
3029         if (char *sn = getenv("REMAKE_SOCKET")) client_mode(sn, targets);
3030
3031         // Otherwise run as server.
3032         if (remakefile.empty())
3033         {
3034                 remakefile = "Remakefile";
3035                 init_prefix_dir();
3036         }
3037         normalize_list(targets, working_dir, prefix_dir);
3038         server_mode(remakefile, targets);
3039 }
3040
3041 /** @} */