Merge pull request #87 from armitasp/master
[freeradius.git] / scripts / jlibtool.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <stdio.h>
18 #include <string.h>
19 #include <stdlib.h>
20 #include <sys/stat.h>
21 #include <sys/types.h>
22 #if !defined(__MINGW32__)
23 #include <sys/wait.h>
24 #endif
25 #include <unistd.h>
26 #include <dirent.h>
27 #include <errno.h>
28 #include <assert.h>
29
30 #ifdef __EMX__
31 #  define SHELL_CMD  "sh"
32 #  define GEN_EXPORTS "emxexp"
33 #  define DEF2IMPLIB_CMD "emximp"
34 #  define SHARE_SW   "-Zdll -Zmtd"
35 #  define USE_OMF 1
36 #  define TRUNCATE_DLL_NAME
37 #  define DYNAMIC_LIB_EXT "dll"
38 #  define EXE_EXT ".exe"
39
40 #  if USE_OMF
41      /* OMF is the native format under OS/2 */
42 #    define STATIC_LIB_EXT "lib"
43 #    define OBJECT_EXT     "obj"
44 #    define LIBRARIAN      "emxomfar"
45 #    define LIBRARIAN_OPTS "cr"
46 #  else
47      /* but the alternative, a.out, can fork() which is sometimes necessary */
48 #    define STATIC_LIB_EXT "a"
49 #    define OBJECT_EXT     "o"
50 #    define LIBRARIAN      "ar"
51 #    define LIBRARIAN_OPTS "cr"
52 #  endif
53 #endif
54
55 #if defined(__APPLE__)
56 #  define SHELL_CMD  "/bin/sh"
57 #  define DYNAMIC_LIB_EXT "dylib"
58 #  define MODULE_LIB_EXT  "bundle"
59 #  define STATIC_LIB_EXT "a"
60 #  define OBJECT_EXT     "o"
61 #  define LIBRARIAN      "ar"
62 #  define LIBRARIAN_OPTS "cr"
63 /* man libtool(1) documents ranlib option of -c.  */
64 #  define RANLIB "ranlib"
65 #  define PIC_FLAG "-fPIC -fno-common"
66 #  define SHARED_OPTS "-dynamiclib"
67 #  define MODULE_OPTS "-bundle -dynamic"
68 #  define DYNAMIC_LINK_OPTS "-flat_namespace"
69 #  define DYNAMIC_LINK_UNDEFINED "-undefined suppress"
70 #  define dynamic_link_version_func darwin_dynamic_link_function
71 #  define DYNAMIC_INSTALL_NAME "-install_name"
72 #  define DYNAMIC_LINK_NO_INSTALL "-dylib_file"
73 #  define HAS_REALPATH
74 /*-install_name  /Users/jerenk/apache-2.0-cvs/lib/libapr.0.dylib -compatibility_version 1 -current_version 1.0 */
75 #  define LD_LIBRARY_PATH "DYLD_LIBRARY_PATH"
76 #  define LD_LIBRARY_PATH_LOCAL "DYLD_FALLBACK_LIBRARY_PATH"
77 #endif
78
79 #if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
80 #  define SHELL_CMD  "/bin/sh"
81 #  define DYNAMIC_LIB_EXT "so"
82 #  define MODULE_LIB_EXT  "so"
83 #  define STATIC_LIB_EXT "a"
84 #  define OBJECT_EXT     "o"
85 #  define LIBRARIAN      "ar"
86 #  define LIBRARIAN_OPTS "cr"
87 #  define RANLIB "ranlib"
88 #  define PIC_FLAG "-fPIC"
89 #  define RPATH "-rpath"
90 #  define SHARED_OPTS "-shared"
91 #  define MODULE_OPTS "-shared"
92 #  define DYNAMIC_LINK_OPTS "-export-dynamic"
93 #  define LINKER_FLAG_PREFIX "-Wl,"
94 #  define ADD_MINUS_L
95 #  define LD_RUN_PATH "LD_RUN_PATH"
96 #  define LD_LIBRARY_PATH "LD_LIBRARY_PATH"
97 #  define LD_LIBRARY_PATH_LOCAL LD_LIBRARY_PATH
98 #endif
99
100 #if defined(sun)
101 #  define SHELL_CMD  "/bin/sh"
102 #  define DYNAMIC_LIB_EXT "so"
103 #  define MODULE_LIB_EXT  "so"
104 #  define STATIC_LIB_EXT "a"
105 #  define OBJECT_EXT     "o"
106 #  define LIBRARIAN      "ar"
107 #  define LIBRARIAN_OPTS "cr"
108 #  define RANLIB "ranlib"
109 #  define PIC_FLAG "-KPIC"
110 #  define RPATH "-R"
111 #  define SHARED_OPTS "-G"
112 #  define MODULE_OPTS "-G"
113 #  define DYNAMIC_LINK_OPTS ""
114 #  define LINKER_FLAG_NO_EQUALS
115 #  define ADD_MINUS_L
116 #  define HAS_REALPATH
117 #  define LD_RUN_PATH "LD_RUN_PATH"
118 #  define LD_LIBRARY_PATH "LD_LIBRARY_PATH"
119 #  define LD_LIBRARY_PATH_LOCAL LD_LIBRARY_PATH
120 #endif
121
122 #if defined(_OSD_POSIX)
123 #  define SHELL_CMD  "/usr/bin/sh"
124 #  define DYNAMIC_LIB_EXT "so"
125 #  define MODULE_LIB_EXT  "so"
126 #  define STATIC_LIB_EXT "a"
127 #  define OBJECT_EXT     "o"
128 #  define LIBRARIAN      "ar"
129 #  define LIBRARIAN_OPTS "cr"
130 #  define SHARED_OPTS "-G"
131 #  define MODULE_OPTS "-G"
132 #  define LINKER_FLAG_PREFIX "-Wl,"
133 #  define NEED_SNPRINTF
134 #endif
135
136 #if defined(sinix) && defined(mips) && defined(__SNI_TARG_UNIX)
137 #  define SHELL_CMD  "/usr/bin/sh"
138 #  define DYNAMIC_LIB_EXT "so"
139 #  define MODULE_LIB_EXT  "so"
140 #  define STATIC_LIB_EXT "a"
141 #  define OBJECT_EXT     "o"
142 #  define LIBRARIAN      "ar"
143 #  define LIBRARIAN_OPTS "cr"
144 #  define RPATH "-Brpath"
145 #  define SHARED_OPTS "-G"
146 #  define MODULE_OPTS "-G"
147 #  define DYNAMIC_LINK_OPTS "-Wl,-Blargedynsym"
148 #  define LINKER_FLAG_PREFIX "-Wl,"
149 #  define NEED_SNPRINTF
150 #  define LD_RUN_PATH "LD_RUN_PATH"
151 #  define LD_LIBRARY_PATH "LD_LIBRARY_PATH"
152 #  define LD_LIBRARY_PATH_LOCAL LD_LIBRARY_PATH
153 #endif
154
155 #if defined(__MINGW32__)
156 #  define SHELL_CMD "sh"
157 #  define DYNAMIC_LIB_EXT "dll"
158 #  define MODULE_LIB_EXT  "dll"
159 #  define STATIC_LIB_EXT "a"
160 #  define OBJECT_EXT     "o"
161 #  define LIBRARIAN      "ar"
162 #  define LIBRARIAN_OPTS "cr"
163 #  define RANLIB "ranlib"
164 #  define LINKER_FLAG_PREFIX "-Wl,"
165 #  define SHARED_OPTS "-shared"
166 #  define MODULE_OPTS "-shared"
167 #  define MKDIR_NO_UMASK
168 #  define EXE_EXT ".exe"
169 #endif
170
171 #ifndef CC
172 #define CC "gcc"
173 #endif
174
175 #ifndef CXX
176 #define CXX "g++"
177 #endif
178
179 #ifndef LINK_c
180 #define LINK_c "gcc"
181 #endif
182
183 #ifndef LINK_cxx
184 #define LINK_cxx "g++"
185 #endif
186
187 #ifndef LIBDIR
188 #define LIBDIR "/usr/local/lib"
189 #endif
190
191 #define OBJDIR ".libs"
192
193 #ifndef SHELL_CMD
194 #error Unsupported platform: Please add defines for SHELL_CMD etc. for your platform.
195 #endif
196
197 #ifdef NEED_SNPRINTF
198 #include <stdarg.h>
199 #endif
200
201 #ifdef __EMX__
202 #include <process.h>
203 #endif
204
205 #ifndef PATH_MAX
206 #define PATH_MAX 1024
207 #endif
208
209
210 /* We want to say we are libtool 1.4 for shlibtool compatibility. */
211 #define VERSION "1.4"
212
213 enum tool_mode_t {
214     mUnknown,
215     mCompile,
216     mLink,
217     mExecute,
218     mInstall,
219 };
220
221 enum output_t {
222     otGeneral,
223     otObject,
224     otProgram,
225     otLibrary,
226     otStaticLibraryOnly,
227     otDynamicLibraryOnly,
228     otModule,
229 };
230
231 enum pic_mode_e {
232     pic_UNKNOWN,
233     pic_PREFER,
234     pic_AVOID,
235 };
236
237 enum shared_mode_e {
238     share_UNSET,
239     share_STATIC,
240     share_SHARED,
241 };
242
243 enum lib_type {
244     type_UNKNOWN,
245     type_STATIC_LIB,
246     type_DYNAMIC_LIB,
247     type_MODULE_LIB,
248     type_OBJECT,
249 };
250
251 typedef struct {
252     const char **vals;
253     int num;
254 } count_chars;
255
256 typedef struct {
257     const char *normal;
258     const char *install;
259 } library_name;
260
261 typedef struct {
262     count_chars *normal;
263     count_chars *install;
264     count_chars *dependencies;
265 } library_opts;
266
267 typedef struct {
268     int silent;
269     int debug;
270     enum shared_mode_e shared;
271     int export_all;
272     int dry_run;
273     enum pic_mode_e pic_mode;
274     int export_dynamic;
275     int no_install;
276 } options_t;
277
278 typedef struct {
279     enum tool_mode_t mode;
280     enum output_t output;
281     options_t options;
282
283     char *output_name;
284     char *fake_output_name;
285     char *basename;
286
287     const char *install_path;
288     const char *compiler;
289     const char *program;
290     count_chars *program_opts;
291
292     count_chars *arglist;
293     count_chars *tmp_dirs;
294     count_chars *obj_files;
295     count_chars *dep_rpaths;
296     count_chars *rpaths;
297
298     library_name static_name;
299     library_name shared_name;
300     library_name module_name;
301
302     library_opts static_opts;
303     library_opts shared_opts;
304
305     const char *version_info;
306     const char *undefined_flag;
307 } command_t;
308
309 #ifdef RPATH
310 static void add_rpath(count_chars *cc, const char *path);
311 #endif
312
313 static void usage(int code)
314 {
315         printf("Usage: jlibtool [OPTIONS...] COMMANDS...\n");
316         printf("jlibtool is a replacement for GNU libtool with similar functionality.\n\n");
317
318         printf("    --config          show all configuration variables\n");
319         printf("    --debug           enable verbose shell tracing\n");
320         printf("    --dry-run         display commands without modifying any files\n");
321         printf("    --help            display this help message and exit\n");
322         printf("    --mode=MODE       use operational mode MODE (you *must* set mode)\n");
323
324         printf("    --silent          don't print informational messages\n");
325         printf("    --tag=TAG         Ignored for libtool compatibility\n");
326         printf("    --version         print version information\n");
327
328
329         printf("    --shared          Build shared libraries when using --mode=link\n");
330         printf("    --export-all      Try to export 'def' file on some platforms\n");
331
332         printf("\nMODE must be one of the following:\n\n");
333         printf("      compile         compile a source file into a jlibtool object\n");
334         printf("      execute         automatically set library path, then run a program\n");
335         printf("      install         install libraries or executables\n");
336         printf("      link            create a library or an executable\n");
337
338         printf("\nMODE-ARGS can be the following:\n\n");
339         printf("      -export-dynamic  accepted and ignored\n");
340         printf("      -module          create a module when linking\n");
341         printf("      -shared          create a shared library when linking\n");
342         printf("      -prefer-pic      prefer position-independent-code when compiling\n");
343         printf("      -prefer-non-pic  prefer non position-independent-code when compiling\n");
344         printf("      -static          create a static library when linking\n");
345         printf("      -no-install      link libraries locally\n");
346         printf("      -rpath arg       Set install path for shared libraries\n");
347         printf("      -l arg           pass '-l arg' to the link stage\n");
348         printf("      -L arg           pass '-L arg' to the link stage\n");
349         printf("      -R dir           add 'dir' to runtime library search path.\n");
350         printf("      -Zexe            accepted and ignored\n");
351         printf("      -avoid-version   accepted and ignored\n");
352
353         exit(code);
354 }
355
356 #if defined(NEED_SNPRINTF)
357 /* Write at most n characters to the buffer in str, return the
358  * number of chars written or -1 if the buffer would have been
359  * overflowed.
360  *
361  * This is portable to any POSIX-compliant system has /dev/null
362  */
363 static FILE *f=NULL;
364 static int vsnprintf( char *str, size_t n, const char *fmt, va_list ap )
365 {
366        int res;
367
368        if (f == NULL)
369                f = fopen("/dev/null","w");
370        if (f == NULL)
371                return -1;
372
373        setvbuf( f, str, _IOFBF, n );
374
375        res = vfprintf( f, fmt, ap );
376
377        if ( res > 0 && res < n ) {
378                res = vsprintf( str, fmt, ap );
379        }
380        return res;
381 }
382 static int snprintf( char *str, size_t n, const char *fmt, ... )
383 {
384         va_list ap;
385         int res;
386
387         va_start( ap, fmt );
388         res = vsnprintf( str, n, fmt, ap );
389         va_end( ap );
390         return res;
391 }
392 #endif
393
394 static void init_count_chars(count_chars *cc)
395 {
396     cc->vals = (const char**)malloc(PATH_MAX*sizeof(char*));
397     cc->num = 0;
398 }
399
400 static void clear_count_chars(count_chars *cc)
401 {
402     int i;
403     for (i = 0; i < cc->num; i++) {
404         cc->vals[i] = 0;
405     }
406
407     cc->num = 0;
408 }
409
410 static void push_count_chars(count_chars *cc, const char *newval)
411 {
412     cc->vals[cc->num++] = newval;
413 }
414
415 static void pop_count_chars(count_chars *cc)
416 {
417     cc->num--;
418 }
419
420 static void insert_count_chars(count_chars *cc, const char *newval, int position)
421 {
422     int i;
423
424     for (i = cc->num; i > position; i--) {
425         cc->vals[i] = cc->vals[i-1];
426     }
427
428     cc->vals[position] = newval;
429     cc->num++;
430 }
431
432 static void append_count_chars(count_chars *cc, count_chars *cctoadd)
433 {
434     int i;
435     for (i = 0; i < cctoadd->num; i++) {
436         if (cctoadd->vals[i]) {
437             push_count_chars(cc, cctoadd->vals[i]);
438         }
439     }
440 }
441
442 static const char *flatten_count_chars(count_chars *cc, int space)
443 {
444     int i, size;
445     char *newval;
446
447     size = 0;
448     for (i = 0; i < cc->num; i++) {
449         if (cc->vals[i]) {
450             size += strlen(cc->vals[i]) + 1;
451             if (space) {
452               size++;
453             }
454         }
455     }
456
457     newval = (char*)malloc(size + 1);
458     newval[0] = 0;
459
460     for (i = 0; i < cc->num; i++) {
461         if (cc->vals[i]) {
462             strcat(newval, cc->vals[i]);
463             if (space) {
464                 strcat(newval, " ");
465             }
466         }
467     }
468
469     return newval;
470 }
471
472 static char *shell_esc(const char *str)
473 {
474     int in_quote = 0;
475     char *cmd;
476     unsigned char *d;
477     const unsigned char *s;
478
479     cmd = (char *)malloc(2 * strlen(str) + 3);
480     d = (unsigned char *)cmd;
481     s = (const unsigned char *)str;
482
483 #ifdef __MINGW32__
484     *d++ = '\"';
485 #endif
486
487     for (; *s; ++s) {
488         if (*s == '"') {
489             *d++ = '\\';
490             in_quote++;
491         }
492         else if (*s == '\\' || (*s == ' ' && (in_quote % 2))) {
493             *d++ = '\\';
494         }
495         *d++ = *s;
496     }
497
498 #ifdef __MINGW32__
499     *d++ = '\"';
500 #endif
501
502     *d = '\0';
503     return cmd;
504 }
505
506 static int external_spawn(command_t *cmd, const char *file, const char **argv)
507 {
508     file = file;                /* -Wunused */
509
510     if (!cmd->options.silent) {
511         const char **argument = argv;
512         printf("Executing: ");
513         while (*argument) {
514             printf("%s ", *argument);
515             argument++;
516         }
517         puts("");
518     }
519
520     if (cmd->options.dry_run) {
521         return 0;
522     }
523 #if defined(__EMX__) || defined(__MINGW32__)
524     return spawnvp(P_WAIT, argv[0], argv);
525 #else
526     {
527         pid_t pid;
528         pid = fork();
529         if (pid == 0) {
530             return execvp(argv[0], (char**)argv);
531         }
532         else {
533             int statuscode;
534             waitpid(pid, &statuscode, 0);
535             if (WIFEXITED(statuscode)) {
536                 return WEXITSTATUS(statuscode);
537             }
538             return 0;
539         }
540     }
541 #endif
542 }
543
544 static int run_command(command_t *cmd_data, count_chars *cc)
545 {
546     char *command;
547     const char *spawn_args[4];
548     count_chars tmpcc;
549
550     init_count_chars(&tmpcc);
551
552     if (cmd_data->program) {
553         push_count_chars(&tmpcc, cmd_data->program);
554     }
555
556     append_count_chars(&tmpcc, cmd_data->program_opts);
557
558     append_count_chars(&tmpcc, cc);
559
560     command = shell_esc(flatten_count_chars(&tmpcc, 1));
561
562     spawn_args[0] = SHELL_CMD;
563     spawn_args[1] = "-c";
564     spawn_args[2] = command;
565     spawn_args[3] = NULL;
566     return external_spawn(cmd_data, spawn_args[0], spawn_args);
567 }
568
569 /*
570  * print configuration
571  * shlibpath_var is used in configure.
572  */
573 #define printc(_x,_y) if (!value || !strcmp(value, _x)) printf(_x "=\"%s\"\n", _y)
574
575 static void print_config(const char *value)
576 {
577 #ifdef LD_RUN_PATH
578     printc("runpath_var", LD_RUN_PATH);
579 #endif
580 #ifdef LD_LIBRARY_PATH
581     printc("shlibpath_var", LD_LIBRARY_PATH);
582 #endif
583 #ifdef LD_LIBRARY_PATH_LOCAL
584     printc("shlocallibpath_var", LD_LIBRARY_PATH_LOCAL);
585 #endif
586 #ifdef SHELL_CMD
587     printc("SHELL", SHELL_CMD);
588 #endif
589 #ifdef OBJECT_EXT
590     printc("objext", OBJECT_EXT);
591 #endif
592 #ifdef OBJDIR
593     printc("objdir", OBJDIR);
594 #endif
595 #ifdef DYNAMIC_LIB_EXT
596     /* add a '.' prefix because libtool does that. */
597     printc("shrext_cmds", "echo ." DYNAMIC_LIB_EXT);
598     /* add a '.' prefix because libtool does that. */
599     printc("shrext", "." DYNAMIC_LIB_EXT);
600 #endif
601 #ifdef EXE_EXT
602     printc("exeext", EXE_EXT);
603 #endif
604 #ifdef STATIC_LIB_EXT
605     printc("libext", STATIC_LIB_EXT);
606 #endif
607 #ifdef LIBRARIAN
608     printc("AR", LIBRARIAN);
609 #endif
610 #ifdef LIBRARIAN_OPTS
611     printc("AR_FLAGS", LIBRARIAN_OPTS);
612 #endif
613 #ifdef LINKER_FLAG_PREFIX
614     printc("wl", LINKER_FLAG_PREFIX);
615 #endif
616 #ifdef RANLIB
617     printc("ranlib", RANLIB);
618 #endif
619
620 }
621 /*
622  * Add a directory to the runtime library search path.
623  */
624 static void add_runtimedirlib(char *arg, command_t *cmd_data)
625 {
626 #ifdef RPATH
627     add_rpath(cmd_data->shared_opts.dependencies, arg);
628 #else
629     arg = arg;                  /* -Wunused */
630     cmd_data = cmd_data;
631 #endif
632 }
633
634 static int parse_long_opt(char *arg, command_t *cmd_data)
635 {
636     char *equal_pos = strchr(arg, '=');
637     char var[50];
638     char value[500];
639
640     if (equal_pos) {
641         strncpy(var, arg, equal_pos - arg);
642         var[equal_pos - arg] = 0;
643         strcpy(value, equal_pos + 1);
644     } else {
645         strcpy(var, arg);
646         value[0] = '\0';
647     }
648
649     if (strcmp(var, "silent") == 0) {
650         cmd_data->options.silent = 1;
651     } else if (strcmp(var, "quiet") == 0) {
652         cmd_data->options.silent = 1;
653     } else if (strcmp(var, "debug") == 0) {
654         cmd_data->options.debug = 1;
655     } else if (strcmp(var, "mode") == 0) {
656         if (cmd_data->mode != mUnknown) {
657                 fprintf(stderr, "Cannot set --mode twice\n");
658                 exit(1);
659         }
660
661         if (strcmp(value, "compile") == 0) {
662             cmd_data->mode = mCompile;
663             cmd_data->output = otObject;
664
665         } else if (strcmp(value, "link") == 0) {
666             cmd_data->mode = mLink;
667             cmd_data->output = otLibrary;
668
669         } else if (strcmp(value, "install") == 0) {
670             cmd_data->mode = mInstall;
671
672         } else if (strcmp(value, "execute") == 0) {
673             cmd_data->mode = mExecute;
674
675         } else {
676             printf("Unknown mode \"%s\"\n", value);
677         }
678     } else if (strcmp(var, "shared") == 0) {
679       if ((cmd_data->mode == mLink) &&
680           (cmd_data->output == otGeneral)) {
681             cmd_data->output = otDynamicLibraryOnly;
682         }
683         cmd_data->options.shared = share_SHARED;
684     } else if (strcmp(var, "export-all") == 0) {
685         cmd_data->options.export_all = 1;
686     } else if (strcmp(var, "dry-run") == 0) {
687         printf("Dry-run mode on!\n");
688         cmd_data->options.dry_run = 1;
689     } else if (strcmp(var, "version") == 0) {
690         printf("Version " VERSION "\n");
691     } else if (strcmp(var, "help") == 0) {
692         usage(0);
693     } else if (strcmp(var, "config") == 0) {
694         print_config(value);
695         exit(0);
696     } else if (strcmp(var, "tag") == 0) {
697         if (strcmp(value, "CC") == 0) {
698             /* Do nothing. */
699         }
700         if (strcmp(value, "CXX") == 0) {
701             /* Do nothing. */
702         }
703     } else {
704         return 0;
705     }
706
707     return 1;
708 }
709
710 /* Return 1 if we eat it. */
711 static int parse_short_opt(char *arg, command_t *cmd_data)
712 {
713     if (strcmp(arg, "export-dynamic") == 0) {
714         cmd_data->options.export_dynamic = 1;
715         return 1;
716     }
717
718     if (strcmp(arg, "module") == 0) {
719         cmd_data->output = otModule;
720         return 1;
721     }
722
723     if (strcmp(arg, "shared") == 0) {
724         if (cmd_data->mode == mLink) {
725             cmd_data->output = otDynamicLibraryOnly;
726         }
727         cmd_data->options.shared = share_SHARED;
728         return 1;
729     }
730
731     if (strcmp(arg, "Zexe") == 0) {
732         return 1;
733     }
734
735     if (strcmp(arg, "avoid-version") == 0) {
736         return 1;
737     }
738
739     if (strcmp(arg, "prefer-pic") == 0) {
740         cmd_data->options.pic_mode = pic_PREFER;
741         return 1;
742     }
743
744     if (strcmp(arg, "prefer-non-pic") == 0) {
745         cmd_data->options.pic_mode = pic_AVOID;
746         return 1;
747     }
748
749     if (strcmp(arg, "static") == 0) {
750        if ((cmd_data->mode == mLink) &&
751           (cmd_data->output == otLibrary)) {
752             cmd_data->output = otStaticLibraryOnly;
753         }
754         cmd_data->options.shared = share_STATIC;
755         return 1;
756     }
757
758     if (cmd_data->mode == mLink) {
759         if (strcmp(arg, "no-install") == 0) {
760             cmd_data->options.no_install = 1;
761             return 1;
762         }
763         if (arg[0] == 'L' || arg[0] == 'l') {
764             /* Hack... */
765             arg--;
766             push_count_chars(cmd_data->shared_opts.dependencies, arg);
767             return 1;
768         } else if (arg[0] == 'R' && arg[1]) {
769             /* -Rdir Add dir to runtime library search path. */
770             add_runtimedirlib(&arg[1], cmd_data);
771             return 1;
772         }
773     }
774     return 0;
775 }
776
777 #ifdef TRUNCATE_DLL_NAME
778 static char *truncate_dll_name(char *path)
779 {
780     /* Cut DLL name down to 8 characters after removing any mod_ prefix */
781     char *tmppath = strdup(path);
782     char *newname = strrchr(tmppath, '/') + 1;
783     char *ext = strrchr(newname, '.');
784     int len;
785
786     if (ext == NULL)
787         return tmppath;
788
789     len = ext - newname;
790
791     if (strncmp(newname, "mod_", 4) == 0) {
792         strcpy(newname, newname + 4);
793         len -= 4;
794     }
795
796     if (len > 8) {
797         strcpy(newname + 8, strchr(newname, '.'));
798     }
799
800     return tmppath;
801 }
802 #endif
803
804 static long safe_strtol(const char *nptr, const char **endptr, int base)
805 {
806     long rv;
807
808     errno = 0;
809
810     rv = strtol(nptr, (char**)endptr, 10);
811
812     if (errno == ERANGE) {
813         return 0;
814     }
815
816     return rv;
817 }
818
819 static void safe_mkdir(const char *path)
820 {
821     mode_t old_umask;
822
823     old_umask = umask(0);
824     umask(old_umask);
825
826 #ifdef MKDIR_NO_UMASK
827     mkdir(path);
828 #else
829     mkdir(path, ~old_umask);
830 #endif
831 }
832
833 /* returns just a file's name without the path */
834 static const char *jlibtool_basename(const char *fullpath)
835 {
836     const char *name = strrchr(fullpath, '/');
837
838     if (name == NULL) {
839         name = strrchr(fullpath, '\\');
840     }
841
842     if (name == NULL) {
843         name = fullpath;
844     } else {
845         name++;
846     }
847
848     return name;
849 }
850
851 #ifdef GEN_EXPORTS
852 /* returns just a file's name without path or extension */
853 static const char *nameof(const char *fullpath)
854 {
855     const char *name;
856     const char *ext;
857
858     name = jlibtool_basename(fullpath);
859     ext = strrchr(name, '.');
860
861     if (ext) {
862         char *trimmed;
863         trimmed = malloc(ext - name + 1);
864         strncpy(trimmed, name, ext - name);
865         trimmed[ext-name] = 0;
866         return trimmed;
867     }
868
869     return name;
870 }
871 #endif
872
873 /* version_info is in the form of MAJOR:MINOR:PATCH */
874 static const char *darwin_dynamic_link_function(const char *version_info)
875 {
876     char *newarg;
877     long major, minor, patch;
878
879     major = 0;
880     minor = 0;
881     patch = 0;
882
883     if (version_info) {
884         major = safe_strtol(version_info, &version_info, 10);
885
886         if (version_info) {
887             if (version_info[0] == ':') {
888                 version_info++;
889             }
890
891             minor = safe_strtol(version_info, &version_info, 10);
892
893             if (version_info) {
894                 if (version_info[0] == ':') {
895                     version_info++;
896                 }
897
898                 patch = safe_strtol(version_info, &version_info, 10);
899
900             }
901         }
902     }
903
904     /* Avoid -dylib_compatibility_version must be greater than zero errors. */
905     if (major == 0) {
906         major = 1;
907     }
908     newarg = (char*)malloc(100);
909     snprintf(newarg, 99,
910              "-compatibility_version %ld -current_version %ld.%ld",
911              major, major, minor);
912
913     return newarg;
914 }
915
916
917 /*
918  *      Add a '.libs/' to the buffer.  The caller ensures that
919  *      The buffer is large enough to handle 6 extra characters.
920  */
921 static void add_dotlibs(char *buffer)
922 {
923         char *name = strrchr(buffer, '/');
924
925         if (!name) {
926                 if (!buffer[0]) {
927                         strcpy(buffer, ".libs/");
928                         return;
929                 }
930                 name = buffer;
931         } else {
932                 name++;
933         }
934         memmove(name + 6, name, strlen(name));
935         memcpy(name, ".libs/", 6);
936 }
937
938 static char *gen_library_name(const char *name, enum lib_type genlib)
939 {
940     char *newarg, *newext;
941
942     newarg = (char *)malloc(strlen(name) + 11);
943
944     if (genlib == type_MODULE_LIB && strncmp(name, "lib", 3) == 0) {
945         name += 3;
946     }
947
948     if (genlib == type_MODULE_LIB) {
949         strcat(newarg, jlibtool_basename(name));
950     }
951     else {
952         strcat(newarg, name);
953     }
954
955     newext = strrchr(newarg, '.') + 1;
956
957     switch (genlib) {
958     case type_STATIC_LIB:
959         strcpy(newext, STATIC_LIB_EXT);
960         break;
961     case type_DYNAMIC_LIB:
962         strcpy(newext, DYNAMIC_LIB_EXT);
963         break;
964     case type_MODULE_LIB:
965         strcpy(newext, MODULE_LIB_EXT);
966         break;
967
968     default:
969         break;
970     }
971
972     add_dotlibs(newarg);
973
974     return newarg;
975 }
976
977 static char *gen_install_name(const char *name, enum lib_type genlib)
978 {
979     struct stat sb;
980     char *newname;
981     int rv;
982
983     newname = gen_library_name(name, genlib);
984
985     /* Check if it exists. If not, return NULL.  */
986     rv = stat(newname, &sb);
987
988     if (rv) {
989         return NULL;
990     }
991
992     return newname;
993 }
994
995 static const char *check_object_exists(command_t *cmd, const char *arg, int arglen)
996 {
997     char *newarg, *ext;
998     int pass, rv;
999
1000     newarg = (char *)malloc(arglen + 10);
1001     memcpy(newarg, arg, arglen);
1002     newarg[arglen] = 0;
1003     ext = newarg + arglen;
1004
1005     pass = 0;
1006
1007     do {
1008         struct stat sb;
1009
1010         switch (pass) {
1011         case 0:
1012             strcpy(ext, OBJECT_EXT);
1013             break;
1014 /*
1015         case 1:
1016             strcpy(ext, NO_PIC_EXT);
1017             break;
1018 */
1019         default:
1020             break;
1021         }
1022
1023         if (cmd->options.debug) {
1024             printf("Checking (obj): %s\n", newarg);
1025         }
1026         rv = stat(newarg, &sb);
1027     }
1028     while (rv != 0 && ++pass < 1);
1029
1030     if (rv == 0) {
1031         if (pass == 1) {
1032             cmd->options.pic_mode = pic_AVOID;
1033         }
1034         return newarg;
1035     }
1036
1037     return NULL;
1038 }
1039
1040 /* libdircheck values:
1041  * 0 - no .libs suffix
1042  * 1 - .libs suffix
1043  */
1044 static char *check_library_exists(command_t *cmd, const char *arg, int pathlen,
1045                            int libdircheck, enum lib_type *libtype)
1046 {
1047     char *newarg, *ext;
1048     int pass, rv, newpathlen;
1049
1050     newarg = (char *)malloc(strlen(arg) + 10);
1051     strcpy(newarg, arg);
1052     newarg[pathlen] = 0;
1053
1054     newpathlen = pathlen;
1055     if (libdircheck) {
1056         add_dotlibs(newarg);
1057         newpathlen += sizeof(".libs/") - 1;
1058     }
1059
1060     strcpy(newarg+newpathlen, arg+pathlen);
1061     ext = strrchr(newarg, '.') + 1;
1062
1063     pass = 0;
1064
1065     do {
1066         struct stat sb;
1067
1068         switch (pass) {
1069         case 0:
1070             if (cmd->options.pic_mode != pic_AVOID &&
1071                 cmd->options.shared != share_STATIC) {
1072                 strcpy(ext, DYNAMIC_LIB_EXT);
1073                 *libtype = type_DYNAMIC_LIB;
1074                 break;
1075             }
1076             pass = 1;
1077             /* Fall through */
1078         case 1:
1079             strcpy(ext, STATIC_LIB_EXT);
1080             *libtype = type_STATIC_LIB;
1081             break;
1082         case 2:
1083             strcpy(ext, MODULE_LIB_EXT);
1084             *libtype = type_MODULE_LIB;
1085             break;
1086         case 3:
1087             strcpy(ext, OBJECT_EXT);
1088             *libtype = type_OBJECT;
1089             break;
1090         default:
1091             *libtype = type_UNKNOWN;
1092             break;
1093         }
1094
1095         if (cmd->options.debug) {
1096             printf("Checking (lib): %s\n", newarg);
1097         }
1098         rv = stat(newarg, &sb);
1099     }
1100     while (rv != 0 && ++pass < 4);
1101
1102     if (rv == 0) {
1103         return newarg;
1104     }
1105
1106     return NULL;
1107 }
1108
1109 static char * load_install_path(const char *arg)
1110 {
1111     FILE *f;
1112     char *path;
1113
1114     path = malloc(PATH_MAX);
1115
1116     f = fopen(arg,"r");
1117     if (f == NULL) {
1118         return NULL;
1119     }
1120     fgets(path, PATH_MAX, f);
1121     fclose(f);
1122     if (path[strlen(path)-1] == '\n') {
1123         path[strlen(path)-1] = '\0';
1124     }
1125     /* Check that we have an absolute path.
1126      * Otherwise the file could be a GNU libtool file.
1127      */
1128     if (path[0] != '/') {
1129         return NULL;
1130     }
1131     return path;
1132 }
1133
1134 static char * load_noinstall_path(const char *arg, int pathlen)
1135 {
1136     char *newarg, *expanded_path;
1137     int newpathlen;
1138
1139     newarg = (char *)malloc(strlen(arg) + 10);
1140     strcpy(newarg, arg);
1141     newarg[pathlen] = 0;
1142
1143     newpathlen = pathlen;
1144     strcat(newarg, ".libs");
1145     newpathlen += sizeof(".libs") - 1;
1146     newarg[newpathlen] = 0;
1147
1148 #ifdef HAS_REALPATH
1149     expanded_path = malloc(PATH_MAX);
1150     expanded_path = realpath(newarg, expanded_path);
1151     /* Uh, oh.  There was an error.  Fall back on our first guess. */
1152     if (!expanded_path) {
1153         expanded_path = newarg;
1154     }
1155 #else
1156     /* We might get ../ or something goofy.  Oh, well. */
1157     expanded_path = newarg;
1158 #endif
1159
1160     return expanded_path;
1161 }
1162
1163 static void add_dynamic_link_opts(command_t *cmd_data, count_chars *args)
1164 {
1165 #ifdef DYNAMIC_LINK_OPTS
1166     if (cmd_data->options.pic_mode != pic_AVOID) {
1167         if (cmd_data->options.debug) {
1168            printf("Adding: %s\n", DYNAMIC_LINK_OPTS);
1169         }
1170         push_count_chars(args, DYNAMIC_LINK_OPTS);
1171         if (cmd_data->undefined_flag) {
1172             push_count_chars(args, "-undefined");
1173 #if defined(__APPLE__)
1174             /* -undefined dynamic_lookup is used by the bundled Python in
1175              * 10.4, but if we don't set MACOSX_DEPLOYMENT_TARGET to 10.3+,
1176              * we'll get a linker error if we pass this flag.
1177              */
1178             if (strcasecmp(cmd_data->undefined_flag,
1179                            "dynamic_lookup") == 0) {
1180                 insert_count_chars(cmd_data->program_opts,
1181                                    "MACOSX_DEPLOYMENT_TARGET=10.3", 0);
1182             }
1183 #endif
1184             push_count_chars(args, cmd_data->undefined_flag);
1185         }
1186         else {
1187 #ifdef DYNAMIC_LINK_UNDEFINED
1188             if (cmd_data->options.debug) {
1189                 printf("Adding: %s\n", DYNAMIC_LINK_UNDEFINED);
1190             }
1191             push_count_chars(args, DYNAMIC_LINK_UNDEFINED);
1192 #endif
1193         }
1194     }
1195 #endif
1196 }
1197
1198 /* Read the final install location and add it to runtime library search path. */
1199 #ifdef RPATH
1200 static void add_rpath(count_chars *cc, const char *path)
1201 {
1202     int size = 0;
1203     char *tmp;
1204
1205 #ifdef LINKER_FLAG_PREFIX
1206     size = strlen(LINKER_FLAG_PREFIX);
1207 #endif
1208     size = size + strlen(path) + strlen(RPATH) + 2;
1209     tmp = malloc(size);
1210     if (tmp == NULL) {
1211         return;
1212     }
1213 #ifdef LINKER_FLAG_PREFIX
1214     strcpy(tmp, LINKER_FLAG_PREFIX);
1215     strcat(tmp, RPATH);
1216 #else
1217     strcpy(tmp, RPATH);
1218 #endif
1219 #ifndef LINKER_FLAG_NO_EQUALS
1220     strcat(tmp, "=");
1221 #endif
1222     strcat(tmp, path);
1223
1224     push_count_chars(cc, tmp);
1225 }
1226
1227 static void add_rpath_file(count_chars *cc, const char *arg)
1228 {
1229     const char *path;
1230
1231     path = load_install_path(arg);
1232     if (path) {
1233         add_rpath(cc, path);
1234     }
1235 }
1236
1237 static void add_rpath_noinstall(count_chars *cc, const char *arg, int pathlen)
1238 {
1239     const char *path;
1240
1241     path = load_noinstall_path(arg, pathlen);
1242     if (path) {
1243         add_rpath(cc, path);
1244     }
1245 }
1246 #endif
1247
1248 #ifdef DYNAMIC_LINK_NO_INSTALL
1249 static void add_dylink_noinstall(count_chars *cc, const char *arg, int pathlen,
1250                           int extlen)
1251 {
1252     const char *install_path, *current_path, *name;
1253     char *exp_argument;
1254     int i_p_len, c_p_len, name_len, dyext_len, cur_len;
1255
1256     install_path = load_install_path(arg);
1257     current_path = load_noinstall_path(arg, pathlen);
1258
1259     if (!install_path || !current_path) {
1260         return;
1261     }
1262
1263     push_count_chars(cc, DYNAMIC_LINK_NO_INSTALL);
1264
1265     i_p_len = strlen(install_path);
1266     c_p_len = strlen(current_path);
1267
1268     name = arg+pathlen;
1269     name_len = extlen-pathlen;
1270     dyext_len = sizeof(DYNAMIC_LIB_EXT) - 1;
1271
1272     /* No, we need to replace the extension. */
1273     exp_argument = (char *)malloc(i_p_len + c_p_len + (name_len*2) +
1274                                   (dyext_len*2) + 2);
1275
1276     cur_len = 0;
1277     strcpy(exp_argument, install_path);
1278     cur_len += i_p_len;
1279     exp_argument[cur_len++] = '/';
1280     strncpy(exp_argument+cur_len, name, extlen-pathlen);
1281     cur_len += name_len;
1282     strcpy(exp_argument+cur_len, DYNAMIC_LIB_EXT);
1283     cur_len += dyext_len;
1284     exp_argument[cur_len++] = ':';
1285     strcpy(exp_argument+cur_len, current_path);
1286     cur_len += c_p_len;
1287     exp_argument[cur_len++] = '/';
1288     strncpy(exp_argument+cur_len, name, extlen-pathlen);
1289     cur_len += name_len;
1290     strcpy(exp_argument+cur_len, DYNAMIC_LIB_EXT);
1291     cur_len += dyext_len;
1292
1293     push_count_chars(cc, exp_argument);
1294 }
1295 #endif
1296
1297 #ifdef ADD_MINUS_L
1298 /* use -L -llibname to allow to use installed libraries */
1299 static void add_minus_l(count_chars *cc, const char *arg)
1300 {
1301     char *newarg;
1302     char *name = strrchr(arg, '/');
1303     char *file = strrchr(arg, '.');
1304     char *lib  = strstr(name, "lib");
1305
1306     if (name !=NULL && file != NULL && lib == name+1) {
1307         *name = '\0';
1308         *file = '\0';
1309         file = name;
1310         file = file+4;
1311         push_count_chars(cc, "-L");
1312         push_count_chars(cc, arg);
1313         /* we need one argument like -lapr-1 */
1314         newarg = malloc(strlen(file) + 3);
1315         strcpy(newarg, "-l");
1316         strcat(newarg, file);
1317         push_count_chars(cc, newarg);
1318     } else {
1319         push_count_chars(cc, arg);
1320     }
1321 }
1322 #endif
1323
1324 #if 0
1325 static void add_linker_flag_prefix(count_chars *cc, const char *arg)
1326 {
1327 #ifndef LINKER_FLAG_PREFIX
1328     push_count_chars(cc, arg);
1329 #else
1330     char *newarg;
1331     newarg = (char*)malloc(strlen(arg) + sizeof(LINKER_FLAG_PREFIX) + 1);
1332     strcpy(newarg, LINKER_FLAG_PREFIX);
1333     strcat(newarg, arg);
1334     push_count_chars(cc, newarg);
1335 #endif
1336 }
1337 #endif
1338
1339 static int explode_static_lib(command_t *cmd_data, const char *lib)
1340 {
1341     count_chars tmpdir_cc, libname_cc;
1342     const char *tmpdir, *libname;
1343     char savewd[PATH_MAX];
1344     const char *name;
1345     DIR *dir;
1346     struct dirent *entry;
1347     const char *lib_args[4];
1348
1349     /* Bah! */
1350     if (cmd_data->options.dry_run) {
1351         return 0;
1352     }
1353
1354     name = jlibtool_basename(lib);
1355
1356     init_count_chars(&tmpdir_cc);
1357     push_count_chars(&tmpdir_cc, ".libs/");
1358     push_count_chars(&tmpdir_cc, name);
1359     push_count_chars(&tmpdir_cc, ".exploded/");
1360     tmpdir = flatten_count_chars(&tmpdir_cc, 0);
1361
1362     if (!cmd_data->options.silent) {
1363         printf("Making: %s\n", tmpdir);
1364     }
1365     safe_mkdir(tmpdir);
1366
1367     push_count_chars(cmd_data->tmp_dirs, tmpdir);
1368
1369     getcwd(savewd, sizeof(savewd));
1370
1371     if (chdir(tmpdir) != 0) {
1372         if (!cmd_data->options.silent) {
1373             printf("Warning: could not explode %s\n", lib);
1374         }
1375         return 1;
1376     }
1377
1378     if (lib[0] == '/') {
1379         libname = lib;
1380     }
1381     else {
1382         init_count_chars(&libname_cc);
1383         push_count_chars(&libname_cc, "../../");
1384         push_count_chars(&libname_cc, lib);
1385         libname = flatten_count_chars(&libname_cc, 0);
1386     }
1387
1388     lib_args[0] = LIBRARIAN;
1389     lib_args[1] = "x";
1390     lib_args[2] = libname;
1391     lib_args[3] = NULL;
1392
1393     external_spawn(cmd_data, LIBRARIAN, lib_args);
1394
1395     chdir(savewd);
1396     dir = opendir(tmpdir);
1397
1398     while ((entry = readdir(dir)) != NULL) {
1399 #if defined(__APPLE__) && defined(RANLIB)
1400         /* Apple inserts __.SYMDEF which isn't needed.
1401          * Leopard (10.5+) can also add '__.SYMDEF SORTED' which isn't
1402          * much fun either.  Just skip them.
1403          */
1404         if (strstr(entry->d_name, "__.SYMDEF") != NULL) {
1405             continue;
1406         }
1407 #endif
1408         if (entry->d_name[0] != '.') {
1409             push_count_chars(&tmpdir_cc, entry->d_name);
1410             name = flatten_count_chars(&tmpdir_cc, 0);
1411             if (cmd_data->options.debug) {
1412                 printf("Adding: %s\n", name);
1413             }
1414             push_count_chars(cmd_data->obj_files, name);
1415             pop_count_chars(&tmpdir_cc);
1416         }
1417     }
1418
1419     closedir(dir);
1420     return 0;
1421 }
1422
1423 static int parse_input_file_name(char *arg, command_t *cmd_data)
1424 {
1425     const char *ext = strrchr(arg, '.');
1426     const char *name;
1427     int pathlen;
1428     enum lib_type libtype;
1429     const char *newarg;
1430
1431     if (!ext) {
1432         return 0;
1433     }
1434
1435     ext++;
1436     name = jlibtool_basename(arg);
1437
1438     pathlen = name - arg;
1439
1440     if (strcmp(ext, "lo") == 0) {
1441         newarg = check_object_exists(cmd_data, arg, ext - arg);
1442         if (!newarg) {
1443             fprintf(stderr, "Can not find suitable object file for %s\n", arg);
1444             exit(1);
1445         }
1446         if (cmd_data->mode != mLink) {
1447             push_count_chars(cmd_data->arglist, newarg);
1448         }
1449         else {
1450             push_count_chars(cmd_data->obj_files, newarg);
1451         }
1452         return 1;
1453     }
1454
1455     if (strcmp(ext, "la") == 0) {
1456         switch (cmd_data->mode) {
1457         case mLink:
1458             /* Try the .libs dir first! */
1459             newarg = check_library_exists(cmd_data, arg, pathlen, 1, &libtype);
1460             if (!newarg) {
1461                 /* Try the normal dir next. */
1462                 newarg = check_library_exists(cmd_data, arg, pathlen, 0, &libtype);
1463                 if (!newarg) {
1464                     fprintf(stderr, "Can not find suitable library for %s\n", arg);
1465                     exit(1);
1466                 }
1467             }
1468
1469             /* It is not ok to just add the file: a library may added with:
1470                1 - -L path library_name. (For *.so in Linux).
1471                2 - library_name.
1472              */
1473 #ifdef ADD_MINUS_L
1474             if (libtype == type_DYNAMIC_LIB) {
1475                  add_minus_l(cmd_data->shared_opts.dependencies, newarg);
1476             } else if (cmd_data->output == otLibrary &&
1477                        libtype == type_STATIC_LIB) {
1478                 explode_static_lib(cmd_data, newarg);
1479             } else {
1480                  push_count_chars(cmd_data->shared_opts.dependencies, newarg);
1481             }
1482 #else
1483             if (cmd_data->output == otLibrary && libtype == type_STATIC_LIB) {
1484                 explode_static_lib(cmd_data, newarg);
1485             }
1486             else {
1487                 push_count_chars(cmd_data->shared_opts.dependencies, newarg);
1488             }
1489 #endif
1490             if (libtype == type_DYNAMIC_LIB) {
1491                 if (cmd_data->options.no_install) {
1492 #ifdef RPATH
1493                     add_rpath_noinstall(cmd_data->shared_opts.dependencies,
1494                                         arg, pathlen);
1495 #endif
1496 #ifdef DYNAMIC_LINK_NO_INSTALL
1497                     /*
1498                      * This doesn't work as Darwin's linker has no way to
1499                      * override at link-time the search paths for a
1500                      * non-installed library.
1501                      */
1502                     /*
1503                     add_dylink_noinstall(cmd_data->shared_opts.dependencies,
1504                                          arg, pathlen, ext - arg);
1505                     */
1506 #endif
1507                 }
1508                 else {
1509 #ifdef RPATH
1510                     add_rpath_file(cmd_data->shared_opts.dependencies, arg);
1511 #endif
1512                 }
1513             }
1514             break;
1515         case mInstall:
1516             /* If we've already recorded a library to install, we're most
1517              * likely getting the .la file that we want to install as.
1518              * The problem is that we need to add it as the directory,
1519              * not the .la file itself.  Otherwise, we'll do odd things.
1520              */
1521             if (cmd_data->output == otLibrary) {
1522                 arg[pathlen] = '\0';
1523                 push_count_chars(cmd_data->arglist, arg);
1524             }
1525             else {
1526                 cmd_data->output = otLibrary;
1527                 cmd_data->output_name = arg;
1528                 cmd_data->static_name.install = gen_install_name(arg, 0);
1529                 cmd_data->shared_name.install = gen_install_name(arg, 1);
1530                 cmd_data->module_name.install = gen_install_name(arg, 2);
1531
1532                 if (!cmd_data->static_name.install &&
1533                     !cmd_data->shared_name.install &&
1534                     !cmd_data->module_name.install) {
1535                   fprintf(stderr, "Files to install do not exist\n");
1536                   exit(1);
1537                 }
1538
1539             }
1540             break;
1541         default:
1542             break;
1543         }
1544         return 1;
1545     }
1546
1547     if (strcmp(ext, "c") == 0) {
1548         /* If we don't already have an idea what our output name will be. */
1549         if (cmd_data->basename == NULL) {
1550             cmd_data->basename = (char *)malloc(strlen(arg) + 4);
1551             strcpy(cmd_data->basename, arg);
1552             strcpy(strrchr(cmd_data->basename, '.') + 1, "lo");
1553
1554             cmd_data->fake_output_name = strrchr(cmd_data->basename, '/');
1555             if (cmd_data->fake_output_name) {
1556                 cmd_data->fake_output_name++;
1557             }
1558             else {
1559                 cmd_data->fake_output_name = cmd_data->basename;
1560             }
1561         }
1562     }
1563
1564     return 0;
1565 }
1566
1567 static int parse_output_file_name(char *arg, command_t *cmd_data)
1568 {
1569     const char *name;
1570     const char *ext;
1571     char *newarg = NULL;
1572     int pathlen;
1573
1574     cmd_data->fake_output_name = arg;
1575
1576     name = jlibtool_basename(arg);
1577     ext = strrchr(name, '.');
1578
1579 #ifdef EXE_EXT
1580     if (!ext || strcmp(ext, EXE_EXT) == 0) {
1581 #else
1582     if (!ext) {
1583 #endif
1584         cmd_data->basename = arg;
1585         cmd_data->output = otProgram;
1586 #if defined(_OSD_POSIX)
1587         cmd_data->options.pic_mode = pic_AVOID;
1588 #endif
1589         newarg = (char *)malloc(strlen(arg) + 5);
1590         strcpy(newarg, arg);
1591 #ifdef EXE_EXT
1592         if (!ext) {
1593           strcat(newarg, EXE_EXT);
1594         }
1595 #endif
1596         cmd_data->output_name = newarg;
1597         return 1;
1598     }
1599
1600     ext++;
1601     pathlen = name - arg;
1602
1603     if (strcmp(ext, "la") == 0) {
1604         assert(cmd_data->mode == mLink);
1605
1606         cmd_data->basename = arg;
1607         cmd_data->static_name.normal = gen_library_name(arg, type_STATIC_LIB);
1608         cmd_data->shared_name.normal = gen_library_name(arg, type_DYNAMIC_LIB);
1609         cmd_data->module_name.normal = gen_library_name(arg, type_MODULE_LIB);
1610         cmd_data->static_name.install = gen_install_name(arg, type_STATIC_LIB);
1611         cmd_data->shared_name.install = gen_install_name(arg, type_DYNAMIC_LIB);
1612         cmd_data->module_name.install = gen_install_name(arg, type_MODULE_LIB);
1613
1614         if (!cmd_data->options.dry_run) {
1615                 char *newname;
1616                 char *newext;
1617                 newname = malloc(strlen(cmd_data->static_name.normal) + 1);
1618
1619                 strcpy(newname, cmd_data->static_name.normal);
1620                 newext = strrchr(newname, '/');
1621                 if (!newext) {
1622                         /* Check first to see if the dir already exists! */
1623                         safe_mkdir(".libs");
1624                 } else {
1625                         *newext = '\0';
1626                         safe_mkdir(newname);
1627                 }
1628                 free(newname);
1629         }
1630
1631 #ifdef TRUNCATE_DLL_NAME
1632         if (shared) {
1633           arg = truncate_dll_name(arg);
1634         }
1635 #endif
1636
1637         cmd_data->output_name = arg;
1638         return 1;
1639     }
1640
1641     if (strcmp(ext, STATIC_LIB_EXT) == 0) {
1642         assert(cmd_data->mode == mLink);
1643
1644         cmd_data->basename = arg;
1645         cmd_data->options.shared = share_STATIC;
1646         cmd_data->output = otStaticLibraryOnly;
1647         cmd_data->static_name.normal = gen_library_name(arg, type_STATIC_LIB);
1648         cmd_data->static_name.install = gen_install_name(arg, type_STATIC_LIB);
1649
1650         if (!cmd_data->options.dry_run) {
1651                 char *newname;
1652                 char *newext;
1653                 newname = malloc(strlen(cmd_data->static_name.normal) + 1);
1654
1655                 strcpy(newname, cmd_data->static_name.normal);
1656                 newext = strrchr(newname, '/');
1657                 if (!newext) {
1658                         /* Check first to see if the dir already exists! */
1659                         safe_mkdir(".libs");
1660                 } else {
1661                         *newext = '\0';
1662                         safe_mkdir(newname);
1663                 }
1664                 free(newname);
1665         }
1666
1667         cmd_data->output_name = arg;
1668         return 1;
1669     }
1670
1671     if (strcmp(ext, DYNAMIC_LIB_EXT) == 0) {
1672         assert(cmd_data->mode == mLink);
1673
1674         cmd_data->basename = arg;
1675         cmd_data->options.shared = share_SHARED;
1676         cmd_data->output = otDynamicLibraryOnly;
1677         cmd_data->shared_name.normal = gen_library_name(arg, type_DYNAMIC_LIB);
1678         cmd_data->module_name.normal = gen_library_name(arg, type_MODULE_LIB);
1679         cmd_data->shared_name.install = gen_install_name(arg, type_DYNAMIC_LIB);
1680         cmd_data->module_name.install = gen_install_name(arg, type_MODULE_LIB);
1681
1682         if (!cmd_data->options.dry_run) {
1683                 char *newname;
1684                 char *newext;
1685                 newname = malloc(strlen(cmd_data->shared_name.normal) + 1);
1686
1687                 strcpy(newname, cmd_data->shared_name.normal);
1688                 newext = strrchr(newname, '/');
1689                 if (!newext) {
1690                         /* Check first to see if the dir already exists! */
1691                         safe_mkdir(".libs");
1692                 } else {
1693                         *newext = '\0';
1694                         safe_mkdir(newname);
1695                 }
1696                 free(newname);
1697         }
1698
1699         cmd_data->output_name = arg;
1700         return 1;
1701     }
1702
1703     if (strcmp(ext, "lo") == 0) {
1704         char *newext;
1705         cmd_data->basename = arg;
1706         cmd_data->output = otObject;
1707         newarg = (char *)malloc(strlen(arg) + 2);
1708         strcpy(newarg, arg);
1709         newext = strrchr(newarg, '.') + 1;
1710         strcpy(newext, OBJECT_EXT);
1711         cmd_data->output_name = newarg;
1712         return 1;
1713     }
1714
1715     if (strcmp(ext, DYNAMIC_LIB_EXT) == 0) {
1716       fprintf(stderr, "Please build libraries with .la target, not ."
1717               DYNAMIC_LIB_EXT "\n");
1718       exit(1);
1719     }
1720
1721     if (strcmp(ext, STATIC_LIB_EXT) == 0) {
1722       fprintf(stderr, "Please build libraries with .la target, not ."
1723               STATIC_LIB_EXT "\n");
1724       exit(1);
1725     }
1726
1727     return 0;
1728 }
1729
1730 static char *automode(char *arg, command_t *cmd_data)
1731 {
1732         if (cmd_data->mode != mUnknown) return arg;
1733
1734         if (strcmp(arg, "CC") == 0) {
1735                 arg = CC;
1736                 cmd_data->mode = mCompile;
1737
1738         } else if (strcmp(arg, "CXX") == 0) {
1739                 arg = CXX;
1740                 cmd_data->mode = mCompile;
1741
1742         } else if (strcmp(arg, "LINK") == 0) {
1743                 arg = LINK_c;
1744                 cmd_data->mode = mLink;
1745
1746         } else if (strcmp(arg, "LINK.c") == 0) {
1747                 arg = LINK_c;
1748                 cmd_data->mode = mLink;
1749
1750         } else if (strcmp(arg, "LINK.cxx") == 0) {
1751                 arg = LINK_cxx;
1752                 cmd_data->mode = mLink;
1753         }
1754         
1755         return arg;
1756 }
1757
1758 static void parse_args(int argc, char *argv[], command_t *cmd_data)
1759 {
1760     int a;
1761     char *arg, *base;
1762     int argused;
1763
1764     /*
1765      *  We now take a major step past libtool.
1766      *
1767      *  IF there's no "--mode=...", AND we recognise
1768      *  the binary as a "special" name, THEN replace it
1769      *  with the correct one, and set the correct mode.
1770      */
1771     base = jlibtool_basename(argv[0]);
1772     arg = automode(base, cmd_data);
1773     
1774     if (arg != base) {
1775             if (cmd_data->options.debug) {
1776                     printf("Adding: %s\n", arg);
1777             }
1778             push_count_chars(cmd_data->arglist, arg);
1779             assert(cmd_data->mode != mUnknown);
1780     }
1781
1782     /*
1783      *  We first pass over the command-line arguments looking for
1784      *  "--mode", etc.  If so, then use the libtool compatibility
1785      *  method for building the software.  Otherwise, auto-detect it
1786      *  via "-o" and the extensions.
1787      */
1788     base = NULL;
1789     if (cmd_data->mode == mUnknown) for (a = 1; a < argc; a++) {
1790         arg = argv[a];
1791
1792         if (strncmp(arg, "--mode=", 7) == 0) {
1793           base = NULL;
1794           break;
1795         }
1796
1797         /*
1798          *      Stop if we get another magic method
1799          */
1800         if ((a == 1) &&
1801             ((strncmp(arg, "LINK", 4) == 0) ||
1802              (strcmp(arg, "CC") == 0) ||
1803              (strcmp(arg, "CXX") == 0))) {
1804           base = NULL;
1805           break;
1806         }
1807
1808         if (strncmp(arg, "-o", 2) == 0) {
1809           base = argv[++a];
1810         }
1811     }
1812
1813     if (base) {
1814             arg = strrchr(base, '.');
1815             if (!arg) {
1816                     cmd_data->mode = mLink;
1817                     push_count_chars(cmd_data->arglist, LINK_c);
1818             }
1819 #ifdef EXE_EXT
1820             else if (strcmp(arg, EXE_EXT) == 0) {
1821                     cmd_data->mode = mLink;
1822                     push_count_chars(cmd_data->arglist, LINK_c);
1823             }
1824 #endif
1825             else if (strcmp(arg + 1, DYNAMIC_LIB_EXT) == 0) {
1826                     cmd_data->mode = mLink;
1827                     push_count_chars(cmd_data->arglist, LINK_c);
1828             }
1829             else if (strcmp(arg + 1, STATIC_LIB_EXT) == 0) {
1830                     cmd_data->mode = mLink;
1831                     push_count_chars(cmd_data->arglist, LINK_c);
1832             }
1833             else if (strcmp(arg + 1, "la") == 0) {
1834                     cmd_data->mode = mLink;
1835                     push_count_chars(cmd_data->arglist, LINK_c);
1836             }
1837             else if ((strcmp(arg + 1, "lo") == 0) ||
1838                      (strcmp(arg + 1, "o") == 0)) {
1839                     cmd_data->mode = mCompile;
1840                     push_count_chars(cmd_data->arglist, CC);
1841             }
1842     }
1843
1844     for (a = 1; a < argc; a++) {
1845         arg = argv[a];
1846         argused = 1;
1847
1848         if (arg[0] == '-') {
1849             if (arg[1] == '-') {
1850                 argused = parse_long_opt(arg + 2, cmd_data);
1851             }
1852             else {
1853                 argused = parse_short_opt(arg + 1, cmd_data);
1854             }
1855
1856             /* We haven't done anything with it yet, try some of the
1857              * more complicated short opts... */
1858             if (argused == 0 && a + 1 < argc) {
1859                 if (arg[1] == 'o' && !arg[2]) {
1860                     arg = argv[++a];
1861                     argused = parse_output_file_name(arg, cmd_data);
1862                 } else if (strcmp(arg+1, "MT") == 0) {
1863                     if (cmd_data->options.debug) {
1864                         printf("Adding: %s\n", arg);
1865                     }
1866                     push_count_chars(cmd_data->arglist, arg);
1867                     arg = argv[++a];
1868                     if (!cmd_data->options.silent) {
1869                         printf(" %s\n", arg);
1870                     }
1871                     push_count_chars(cmd_data->arglist, arg);
1872                     argused = 1;
1873                 } else if (strcmp(arg+1, "rpath") == 0) {
1874                     /* Aha, we should try to link both! */
1875                     cmd_data->install_path = argv[++a];
1876                     argused = 1;
1877                 } else if (strcmp(arg+1, "release") == 0) {
1878                     /* Store for later deciphering */
1879                     cmd_data->version_info = argv[++a];
1880                     argused = 1;
1881                 } else if (strcmp(arg+1, "version-info") == 0) {
1882                     /* Store for later deciphering */
1883                     cmd_data->version_info = argv[++a];
1884                     argused = 1;
1885                 } else if (strcmp(arg+1, "export-symbols-regex") == 0) {
1886                     /* Skip the argument. */
1887                     ++a;
1888                     argused = 1;
1889                 } else if (strcmp(arg+1, "release") == 0) {
1890                     /* Skip the argument. */
1891                     ++a;
1892                     argused = 1;
1893                 } else if (strcmp(arg+1, "undefined") == 0) {
1894                     cmd_data->undefined_flag = argv[++a];
1895                     argused = 1;
1896                 } else if (arg[1] == 'R' && !arg[2]) {
1897                     /* -R dir Add dir to runtime library search path. */
1898                     add_runtimedirlib(argv[++a], cmd_data);
1899                     argused = 1;
1900                 }
1901             }
1902         } else {
1903             argused = parse_input_file_name(arg, cmd_data);
1904         }
1905
1906         if (!argused) {
1907                 /*
1908                  *  If we still don't have a run mode, look for a magic
1909                  *  program name CC, LINK, or whatever.  Then replace that
1910                  *  with the name of the real program we want to run.
1911                  */
1912                 if ((cmd_data->arglist->num == 0) &&
1913                     (cmd_data->mode == mUnknown)) {
1914                         arg = automode(arg, cmd_data);
1915                 }
1916
1917             if (cmd_data->options.debug) {
1918                 printf("Adding: %s\n", arg);
1919             }
1920             push_count_chars(cmd_data->arglist, arg);
1921         }
1922     }
1923
1924 }
1925
1926 #ifdef GEN_EXPORTS
1927 static void generate_def_file(command_t *cmd_data)
1928 {
1929     char def_file[1024];
1930     char implib_file[1024];
1931     char *ext;
1932     FILE *hDef;
1933     char *export_args[1024];
1934     int num_export_args = 0;
1935     char *cmd;
1936     int cmd_size = 0;
1937     int a;
1938
1939     if (cmd_data->output_name) {
1940         strcpy(def_file, cmd_data->output_name);
1941         strcat(def_file, ".def");
1942         hDef = fopen(def_file, "w");
1943
1944         if (hDef != NULL) {
1945             fprintf(hDef, "LIBRARY '%s' INITINSTANCE\n", nameof(cmd_data->output_name));
1946             fprintf(hDef, "DATA NONSHARED\n");
1947             fprintf(hDef, "EXPORTS\n");
1948             fclose(hDef);
1949
1950             for (a = 0; a < cmd_data->num_obj_files; a++) {
1951                 cmd_size += strlen(cmd_data->obj_files[a]) + 1;
1952             }
1953
1954             cmd_size += strlen(GEN_EXPORTS) + strlen(def_file) + 3;
1955             cmd = (char *)malloc(cmd_size);
1956             strcpy(cmd, GEN_EXPORTS);
1957
1958             for (a=0; a < cmd_data->num_obj_files; a++) {
1959                 strcat(cmd, " ");
1960                 strcat(cmd, cmd_data->obj_files[a] );
1961             }
1962
1963             strcat(cmd, ">>");
1964             strcat(cmd, def_file);
1965             puts(cmd);
1966             export_args[num_export_args++] = SHELL_CMD;
1967             export_args[num_export_args++] = "-c";
1968             export_args[num_export_args++] = cmd;
1969             export_args[num_export_args++] = NULL;
1970             external_spawn(cmd_data, export_args[0], (const char**)export_args);
1971             cmd_data->arglist[cmd_data->num_args++] = strdup(def_file);
1972
1973             /* Now make an import library for the dll */
1974             num_export_args = 0;
1975             export_args[num_export_args++] = DEF2IMPLIB_CMD;
1976             export_args[num_export_args++] = "-o";
1977
1978             strcpy(implib_file, ".libs/");
1979             strcat(implib_file, cmd_data->basename);
1980             ext = strrchr(implib_file, '.');
1981
1982             if (ext)
1983                 *ext = 0;
1984
1985             strcat(implib_file, ".");
1986             strcat(implib_file, STATIC_LIB_EXT);
1987
1988             export_args[num_export_args++] = implib_file;
1989             export_args[num_export_args++] = def_file;
1990             export_args[num_export_args++] = NULL;
1991             external_spawn(cmd_data, export_args[0], (const char**)export_args);
1992
1993         }
1994     }
1995 }
1996 #endif
1997
1998 #if 0
1999 static const char* expand_path(const char *relpath)
2000 {
2001     char foo[PATH_MAX], *newpath;
2002
2003     getcwd(foo, PATH_MAX-1);
2004     newpath = (char*)malloc(strlen(foo)+strlen(relpath)+2);
2005     strcpy(newpath, foo);
2006     strcat(newpath, "/");
2007     strcat(newpath, relpath);
2008     return newpath;
2009 }
2010 #endif
2011
2012 static void link_fixup(command_t *c)
2013 {
2014     /* If we were passed an -rpath directive, we need to build
2015      * shared objects too.  Otherwise, we should only create static
2016      * libraries.
2017      */
2018     if (!c->install_path && (c->output == otDynamicLibraryOnly ||
2019         c->output == otModule || c->output == otLibrary)) {
2020         if (c->options.shared == share_SHARED) {
2021                 c->install_path = LIBDIR;
2022         }
2023     }
2024
2025     if (c->output == otDynamicLibraryOnly ||
2026         c->output == otModule ||
2027         c->output == otLibrary) {
2028
2029         push_count_chars(c->shared_opts.normal, "-o");
2030         if (c->output == otModule) {
2031             push_count_chars(c->shared_opts.normal, c->module_name.normal);
2032         }
2033         else {
2034             char *tmp;
2035             push_count_chars(c->shared_opts.normal, c->shared_name.normal);
2036 #ifdef DYNAMIC_INSTALL_NAME
2037             push_count_chars(c->shared_opts.normal, DYNAMIC_INSTALL_NAME);
2038
2039             if (!c->install_path) {
2040                     fprintf(stderr, "Installation mode requires -rpath\n");
2041                     exit(1);
2042             }
2043
2044             tmp = (char*)malloc(PATH_MAX);
2045             strcpy(tmp, c->install_path);
2046             if (c->shared_name.install) {
2047                     strcat(tmp, strrchr(c->shared_name.install, '/'));
2048             } else {
2049                     strcat(tmp, strrchr(c->shared_name.normal, '/'));
2050             }
2051             push_count_chars(c->shared_opts.normal, tmp);
2052 #endif
2053         }
2054
2055         append_count_chars(c->shared_opts.normal, c->obj_files);
2056         append_count_chars(c->shared_opts.normal, c->shared_opts.dependencies);
2057
2058         if (c->options.export_all) {
2059 #ifdef GEN_EXPORTS
2060             generate_def_file(c);
2061 #endif
2062         }
2063     }
2064
2065     if (c->output == otLibrary || c->output == otStaticLibraryOnly) {
2066         push_count_chars(c->static_opts.normal, "-o");
2067         push_count_chars(c->static_opts.normal, c->output_name);
2068     }
2069
2070     if (c->output == otProgram) {
2071         if (c->output_name) {
2072             push_count_chars(c->arglist, "-o");
2073             push_count_chars(c->arglist, c->output_name);
2074             append_count_chars(c->arglist, c->obj_files);
2075             append_count_chars(c->arglist, c->shared_opts.dependencies);
2076             add_dynamic_link_opts(c, c->arglist);
2077         }
2078     }
2079 }
2080
2081 static void post_parse_fixup(command_t *cmd_data)
2082 {
2083     switch (cmd_data->mode)
2084     {
2085     case mCompile:
2086 #ifdef PIC_FLAG
2087         if (cmd_data->options.pic_mode != pic_AVOID) {
2088             push_count_chars(cmd_data->arglist, PIC_FLAG);
2089         }
2090 #endif
2091         if (cmd_data->output_name) {
2092             push_count_chars(cmd_data->arglist, "-o");
2093             push_count_chars(cmd_data->arglist, cmd_data->output_name);
2094         }
2095         break;
2096     case mLink:
2097         link_fixup(cmd_data);
2098         break;
2099     case mInstall:
2100         if (cmd_data->output == otLibrary) {
2101             link_fixup(cmd_data);
2102         }
2103     default:
2104         break;
2105     }
2106
2107 #ifdef USE_OMF
2108     if (cmd_data->output == otObject ||
2109         cmd_data->output == otProgram ||
2110         cmd_data->output == otLibrary ||
2111         cmd_data->output == otDynamicLibraryOnly) {
2112         push_count_chars(cmd_data->arglist, "-Zomf");
2113     }
2114 #endif
2115
2116     if (cmd_data->options.shared &&
2117             (cmd_data->output == otObject ||
2118              cmd_data->output == otLibrary ||
2119              cmd_data->output == otDynamicLibraryOnly)) {
2120 #ifdef SHARE_SW
2121         push_count_chars(cmd_data->arglist, SHARE_SW);
2122 #endif
2123     }
2124 }
2125
2126 static int run_mode(command_t *cmd_data)
2127 {
2128     int rv;
2129     count_chars *cctemp;
2130
2131     cctemp = (count_chars*)malloc(sizeof(count_chars));
2132     init_count_chars(cctemp);
2133
2134     switch (cmd_data->mode)
2135     {
2136     case mCompile:
2137         rv = run_command(cmd_data, cmd_data->arglist);
2138         if (rv) {
2139             return rv;
2140         }
2141         break;
2142     case mInstall:
2143         /* Well, we'll assume it's a file going to a directory... */
2144         /* For brain-dead install-sh based scripts, we have to repeat
2145          * the command N-times.  install-sh should die.
2146          */
2147         if (!cmd_data->output_name) {
2148             rv = run_command(cmd_data, cmd_data->arglist);
2149             if (rv) {
2150                 return rv;
2151             }
2152         }
2153         if (cmd_data->output_name) {
2154             append_count_chars(cctemp, cmd_data->arglist);
2155             insert_count_chars(cctemp,
2156                                cmd_data->output_name,
2157                                cctemp->num - 1);
2158             rv = run_command(cmd_data, cctemp);
2159             if (rv) {
2160                 return rv;
2161             }
2162             clear_count_chars(cctemp);
2163         }
2164         if (cmd_data->static_name.install) {
2165             append_count_chars(cctemp, cmd_data->arglist);
2166             insert_count_chars(cctemp,
2167                                cmd_data->static_name.install,
2168                                cctemp->num - 1);
2169             rv = run_command(cmd_data, cctemp);
2170             if (rv) {
2171                 return rv;
2172             }
2173 #if defined(__APPLE__) && defined(RANLIB)
2174             /* From the Apple libtool(1) manpage on Tiger/10.4:
2175              * ----
2176              * With  the way libraries used to be created, errors were possible
2177              * if the library was modified with ar(1) and  the  table  of
2178              * contents  was  not updated  by  rerunning ranlib(1).  Thus the
2179              * link editor, ld, warns when the modification date of a library
2180              * is more  recent  than  the  creation date  of its table of
2181              * contents.  Unfortunately, this means that you get the warning
2182              * even if you only copy the library.
2183              * ----
2184              *
2185              * This means that when we install the static archive, we need to
2186              * rerun ranlib afterwards.
2187              */
2188             const char *lib_args[3], *static_lib_name;
2189             char *tmp;
2190             size_t len1, len2;
2191             len1 = strlen(cmd_data->arglist->vals[cmd_data->arglist->num - 1]);
2192
2193             static_lib_name = jlibtool_basename(cmd_data->static_name.install);
2194             len2 = strlen(static_lib_name);
2195
2196             tmp = malloc(len1 + len2 + 2);
2197
2198             snprintf(tmp, len1 + len2 + 2, "%s/%s",
2199                     cmd_data->arglist->vals[cmd_data->arglist->num - 1],
2200                     static_lib_name);
2201
2202             lib_args[0] = RANLIB;
2203             lib_args[1] = tmp;
2204             lib_args[2] = NULL;
2205             external_spawn(cmd_data, RANLIB, lib_args);
2206             free(tmp);
2207 #endif
2208             clear_count_chars(cctemp);
2209         }
2210         if (cmd_data->shared_name.install) {
2211             append_count_chars(cctemp, cmd_data->arglist);
2212             insert_count_chars(cctemp,
2213                                cmd_data->shared_name.install,
2214                                cctemp->num - 1);
2215             rv = run_command(cmd_data, cctemp);
2216             if (rv) {
2217                 return rv;
2218             }
2219             clear_count_chars(cctemp);
2220         }
2221         if (cmd_data->module_name.install) {
2222             append_count_chars(cctemp, cmd_data->arglist);
2223             insert_count_chars(cctemp,
2224                                cmd_data->module_name.install,
2225                                cctemp->num - 1);
2226             rv = run_command(cmd_data, cctemp);
2227             if (rv) {
2228                 return rv;
2229             }
2230             clear_count_chars(cctemp);
2231         }
2232         break;
2233     case mLink:
2234         if (cmd_data->output == otStaticLibraryOnly ||
2235             cmd_data->output == otLibrary) {
2236 #ifdef RANLIB
2237             const char *lib_args[3];
2238 #endif
2239             /* Removes compiler! */
2240             cmd_data->program = LIBRARIAN;
2241             push_count_chars(cmd_data->program_opts, LIBRARIAN_OPTS);
2242             push_count_chars(cmd_data->program_opts,
2243                              cmd_data->static_name.normal);
2244
2245             rv = run_command(cmd_data, cmd_data->obj_files);
2246             if (rv) {
2247                 return rv;
2248             }
2249
2250 #ifdef RANLIB
2251             lib_args[0] = RANLIB;
2252             lib_args[1] = cmd_data->static_name.normal;
2253             lib_args[2] = NULL;
2254             external_spawn(cmd_data, RANLIB, lib_args);
2255 #endif
2256         }
2257
2258         if (cmd_data->output == otDynamicLibraryOnly ||
2259             cmd_data->output == otModule ||
2260             cmd_data->output == otLibrary) {
2261             cmd_data->program = NULL;
2262             clear_count_chars(cmd_data->program_opts);
2263
2264             append_count_chars(cmd_data->program_opts, cmd_data->arglist);
2265             if (cmd_data->output == otModule) {
2266 #ifdef MODULE_OPTS
2267                 push_count_chars(cmd_data->program_opts, MODULE_OPTS);
2268 #endif
2269             } else {
2270 #ifdef SHARED_OPTS
2271                 push_count_chars(cmd_data->program_opts, SHARED_OPTS);
2272 #endif
2273 #ifdef dynamic_link_version_func
2274                 push_count_chars(cmd_data->program_opts,
2275                              dynamic_link_version_func(cmd_data->version_info));
2276 #endif
2277             }
2278             add_dynamic_link_opts(cmd_data, cmd_data->program_opts);
2279
2280             rv = run_command(cmd_data, cmd_data->shared_opts.normal);
2281             if (rv) {
2282                 return rv;
2283             }
2284         }
2285         if (cmd_data->output == otProgram) {
2286             rv = run_command(cmd_data, cmd_data->arglist);
2287             if (rv) {
2288                 return rv;
2289             }
2290         }
2291         break;
2292     case mExecute:
2293     {
2294         char *l, libpath[PATH_MAX];
2295
2296         strcpy(libpath, cmd_data->arglist->vals[0]);
2297         add_dotlibs(libpath);
2298         l = strrchr(libpath, '/');
2299         if (!l) l = strrchr(libpath, '\\');
2300         if (l) {
2301             *l = '\0';
2302             l = libpath;
2303         } else {
2304             l = ".libs/";
2305         }
2306
2307         l = "./build/lib/.libs";
2308         setenv(LD_LIBRARY_PATH_LOCAL, l, 1);
2309         rv = run_command(cmd_data, cmd_data->arglist);
2310         if (rv) {
2311             return rv;
2312         }
2313     }
2314       break;
2315
2316     default:
2317         break;
2318     }
2319
2320     return 0;
2321 }
2322
2323 static void cleanup_tmp_dir(const char *dirname)
2324 {
2325     DIR *dir;
2326     struct dirent *entry;
2327     char fullname[1024];
2328
2329     dir = opendir(dirname);
2330
2331     if (dir == NULL)
2332         return;
2333
2334     while ((entry = readdir(dir)) != NULL) {
2335         if (entry->d_name[0] != '.') {
2336             strcpy(fullname, dirname);
2337             strcat(fullname, "/");
2338             strcat(fullname, entry->d_name);
2339             remove(fullname);
2340         }
2341     }
2342
2343     rmdir(dirname);
2344 }
2345
2346 static void cleanup_tmp_dirs(command_t *cmd_data)
2347 {
2348     int d;
2349
2350     for (d = 0; d < cmd_data->tmp_dirs->num; d++) {
2351         cleanup_tmp_dir(cmd_data->tmp_dirs->vals[d]);
2352     }
2353 }
2354
2355 static int ensure_fake_uptodate(command_t *cmd_data)
2356 {
2357     /* FIXME: could do the stat/touch here, but nah... */
2358     const char *touch_args[3];
2359
2360     if (cmd_data->mode == mInstall) {
2361         return 0;
2362     }
2363     if (!cmd_data->fake_output_name) {
2364         return 0;
2365     }
2366
2367     touch_args[0] = "touch";
2368     touch_args[1] = cmd_data->fake_output_name;
2369     touch_args[2] = NULL;
2370     return external_spawn(cmd_data, "touch", touch_args);
2371 }
2372
2373 /* Store the install path in the *.la file */
2374 static int add_for_runtime(command_t *cmd_data)
2375 {
2376     if (cmd_data->mode == mInstall) {
2377         return 0;
2378     }
2379     if (cmd_data->output == otDynamicLibraryOnly ||
2380         cmd_data->output == otLibrary) {
2381         FILE *f=fopen(cmd_data->fake_output_name,"w");
2382         if (f == NULL) {
2383             return -1;
2384         }
2385         fprintf(f,"%s\n", cmd_data->install_path);
2386         fclose(f);
2387         return(0);
2388     } else {
2389         return(ensure_fake_uptodate(cmd_data));
2390     }
2391 }
2392
2393 int main(int argc, char *argv[])
2394 {
2395     int rc;
2396     command_t cmd_data;
2397
2398     memset(&cmd_data, 0, sizeof(cmd_data));
2399
2400     cmd_data.options.pic_mode = pic_UNKNOWN;
2401
2402     cmd_data.program_opts = (count_chars*)malloc(sizeof(count_chars));
2403     init_count_chars(cmd_data.program_opts);
2404     cmd_data.arglist = (count_chars*)malloc(sizeof(count_chars));
2405     init_count_chars(cmd_data.arglist);
2406     cmd_data.tmp_dirs = (count_chars*)malloc(sizeof(count_chars));
2407     init_count_chars(cmd_data.tmp_dirs);
2408     cmd_data.obj_files = (count_chars*)malloc(sizeof(count_chars));
2409     init_count_chars(cmd_data.obj_files);
2410     cmd_data.dep_rpaths = (count_chars*)malloc(sizeof(count_chars));
2411     init_count_chars(cmd_data.dep_rpaths);
2412     cmd_data.rpaths = (count_chars*)malloc(sizeof(count_chars));
2413     init_count_chars(cmd_data.rpaths);
2414     cmd_data.static_opts.normal = (count_chars*)malloc(sizeof(count_chars));
2415     init_count_chars(cmd_data.static_opts.normal);
2416     cmd_data.shared_opts.normal = (count_chars*)malloc(sizeof(count_chars));
2417     init_count_chars(cmd_data.shared_opts.normal);
2418     cmd_data.shared_opts.dependencies = (count_chars*)malloc(sizeof(count_chars));
2419     init_count_chars(cmd_data.shared_opts.dependencies);
2420
2421     cmd_data.mode = mUnknown;
2422     cmd_data.output = otGeneral;
2423
2424     parse_args(argc, argv, &cmd_data);
2425     post_parse_fixup(&cmd_data);
2426
2427     if (cmd_data.mode == mUnknown) {
2428        usage(1);
2429     }
2430
2431     rc = run_mode(&cmd_data);
2432
2433     if (!rc) {
2434        add_for_runtime(&cmd_data);
2435     }
2436
2437     cleanup_tmp_dirs(&cmd_data);
2438     return rc;
2439 }