Fix for coverity (don't leak memory in add_rpath_noinstall)
[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     int status;
822     mode_t old_umask;
823
824     old_umask = umask(0);
825     umask(old_umask);
826
827 #ifdef MKDIR_NO_UMASK
828     status = mkdir(path);
829 #else
830     status = mkdir(path, ~old_umask);
831 #endif
832     if ((status < 0) && (errno != EEXIST)) {
833         printf("Warning: mkdir of %s failed\n", path);
834     }
835 }
836
837 /* returns just a file's name without the path */
838 static const char *jlibtool_basename(const char *fullpath)
839 {
840     const char *name = strrchr(fullpath, '/');
841
842     if (name == NULL) {
843         name = strrchr(fullpath, '\\');
844     }
845
846     if (name == NULL) {
847         name = fullpath;
848     } else {
849         name++;
850     }
851
852     return name;
853 }
854
855 #ifdef GEN_EXPORTS
856 /* returns just a file's name without path or extension */
857 static const char *nameof(const char *fullpath)
858 {
859     const char *name;
860     const char *ext;
861
862     name = jlibtool_basename(fullpath);
863     ext = strrchr(name, '.');
864
865     if (ext) {
866         char *trimmed;
867         trimmed = malloc(ext - name + 1);
868         strncpy(trimmed, name, ext - name);
869         trimmed[ext-name] = 0;
870         return trimmed;
871     }
872
873     return name;
874 }
875 #endif
876
877 /* version_info is in the form of MAJOR:MINOR:PATCH */
878 static const char *darwin_dynamic_link_function(const char *version_info)
879 {
880     char *newarg;
881     long major, minor, patch;
882
883     major = 0;
884     minor = 0;
885     patch = 0;
886
887     if (version_info) {
888         major = safe_strtol(version_info, &version_info, 10);
889
890         if (version_info) {
891             if (version_info[0] == ':') {
892                 version_info++;
893             }
894
895             minor = safe_strtol(version_info, &version_info, 10);
896
897             if (version_info) {
898                 if (version_info[0] == ':') {
899                     version_info++;
900                 }
901
902                 patch = safe_strtol(version_info, &version_info, 10);
903
904             }
905         }
906     }
907
908     /* Avoid -dylib_compatibility_version must be greater than zero errors. */
909     if (major == 0) {
910         major = 1;
911     }
912     newarg = (char*)malloc(100);
913     snprintf(newarg, 99,
914              "-compatibility_version %ld -current_version %ld.%ld",
915              major, major, minor);
916
917     return newarg;
918 }
919
920
921 /*
922  *      Add a '.libs/' to the buffer.  The caller ensures that
923  *      The buffer is large enough to handle 6 extra characters.
924  */
925 static void add_dotlibs(char *buffer)
926 {
927         char *name = strrchr(buffer, '/');
928
929         if (!name) {
930                 if (!buffer[0]) {
931                         strcpy(buffer, ".libs/");
932                         return;
933                 }
934                 name = buffer;
935         } else {
936                 name++;
937         }
938         memmove(name + 6, name, strlen(name));
939         memcpy(name, ".libs/", 6);
940 }
941
942 static char *gen_library_name(const char *name, enum lib_type genlib)
943 {
944     char *newarg, *newext;
945
946     newarg = (char *)calloc(strlen(name) + 11, 1);
947
948     if (genlib == type_MODULE_LIB && strncmp(name, "lib", 3) == 0) {
949         name += 3;
950     }
951
952     if (genlib == type_MODULE_LIB) {
953         strcpy(newarg, jlibtool_basename(name));
954     }
955     else {
956         strcpy(newarg, name);
957     }
958
959     newext = strrchr(newarg, '.') + 1;
960     if (!newext) {
961         free(newarg);
962         return NULL;
963     }
964
965     switch (genlib) {
966     case type_STATIC_LIB:
967         strcpy(newext, STATIC_LIB_EXT);
968         break;
969     case type_DYNAMIC_LIB:
970         strcpy(newext, DYNAMIC_LIB_EXT);
971         break;
972     case type_MODULE_LIB:
973         strcpy(newext, MODULE_LIB_EXT);
974         break;
975
976     default:
977         break;
978     }
979
980     add_dotlibs(newarg);
981
982     return newarg;
983 }
984
985 static char *gen_install_name(const char *name, enum lib_type genlib)
986 {
987     char *newname;
988     int rv;
989     struct stat sb;
990
991     newname = gen_library_name(name, genlib);
992     if (!newname) return NULL;
993
994     /* Check if it exists. If not, return NULL.  */
995     rv = stat(newname, &sb);
996
997     if (rv) {
998         free(newname);
999         return NULL;
1000     }
1001
1002     return newname;
1003 }
1004
1005 static const char *check_object_exists(command_t *cmd, const char *arg, int arglen)
1006 {
1007     char *newarg, *ext;
1008     int pass, rv;
1009
1010     newarg = (char *)malloc(arglen + 10);
1011     memcpy(newarg, arg, arglen);
1012     newarg[arglen] = 0;
1013     ext = newarg + arglen;
1014
1015     pass = 0;
1016
1017     do {
1018         struct stat sb;
1019
1020         switch (pass) {
1021         case 0:
1022             strcpy(ext, OBJECT_EXT);
1023             break;
1024 /*
1025         case 1:
1026             strcpy(ext, NO_PIC_EXT);
1027             break;
1028 */
1029         default:
1030             break;
1031         }
1032
1033         if (cmd->options.debug) {
1034             printf("Checking (obj): %s\n", newarg);
1035         }
1036         rv = stat(newarg, &sb);
1037     }
1038     while (rv != 0 && ++pass < 1);
1039
1040     if (rv == 0) {
1041         if (pass == 1) {
1042             cmd->options.pic_mode = pic_AVOID;
1043         }
1044         return newarg;
1045     }
1046
1047     return NULL;
1048 }
1049
1050 /* libdircheck values:
1051  * 0 - no .libs suffix
1052  * 1 - .libs suffix
1053  */
1054 static char *check_library_exists(command_t *cmd, const char *arg, int pathlen,
1055                            int libdircheck, enum lib_type *libtype)
1056 {
1057     char *newarg, *ext;
1058     int pass, rv, newpathlen;
1059
1060     newarg = (char *)malloc(strlen(arg) + 10);
1061     strcpy(newarg, arg);
1062     newarg[pathlen] = 0;
1063
1064     newpathlen = pathlen;
1065     if (libdircheck) {
1066         add_dotlibs(newarg);
1067         newpathlen += sizeof(".libs/") - 1;
1068     }
1069
1070     strcpy(newarg+newpathlen, arg+pathlen);
1071     ext = strrchr(newarg, '.') + 1;
1072
1073     pass = 0;
1074
1075     do {
1076         struct stat sb;
1077
1078         switch (pass) {
1079         case 0:
1080             if (cmd->options.pic_mode != pic_AVOID &&
1081                 cmd->options.shared != share_STATIC) {
1082                 strcpy(ext, DYNAMIC_LIB_EXT);
1083                 *libtype = type_DYNAMIC_LIB;
1084                 break;
1085             }
1086             pass = 1;
1087             /* Fall through */
1088         case 1:
1089             strcpy(ext, STATIC_LIB_EXT);
1090             *libtype = type_STATIC_LIB;
1091             break;
1092         case 2:
1093             strcpy(ext, MODULE_LIB_EXT);
1094             *libtype = type_MODULE_LIB;
1095             break;
1096         case 3:
1097             strcpy(ext, OBJECT_EXT);
1098             *libtype = type_OBJECT;
1099             break;
1100         default:
1101             *libtype = type_UNKNOWN;
1102             break;
1103         }
1104
1105         if (cmd->options.debug) {
1106             printf("Checking (lib): %s\n", newarg);
1107         }
1108         rv = stat(newarg, &sb);
1109     }
1110     while (rv != 0 && ++pass < 4);
1111
1112     if (rv == 0) {
1113         return newarg;
1114     }
1115
1116     return NULL;
1117 }
1118
1119 static char * load_install_path(const char *arg)
1120 {
1121     FILE *f;
1122     char *path;
1123
1124     path = malloc(PATH_MAX);
1125
1126     f = fopen(arg,"r");
1127     if (f == NULL) {
1128         return NULL;
1129     }
1130     fgets(path, PATH_MAX, f);
1131     fclose(f);
1132     if (path[strlen(path)-1] == '\n') {
1133         path[strlen(path)-1] = '\0';
1134     }
1135     /* Check that we have an absolute path.
1136      * Otherwise the file could be a GNU libtool file.
1137      */
1138     if (path[0] != '/') {
1139         return NULL;
1140     }
1141     return path;
1142 }
1143
1144 static char * load_noinstall_path(const char *arg, int pathlen)
1145 {
1146     char *newarg, *expanded_path;
1147     int newpathlen;
1148
1149     newarg = (char *)malloc(strlen(arg) + 10);
1150     strcpy(newarg, arg);
1151     newarg[pathlen] = 0;
1152
1153     newpathlen = pathlen;
1154     strcat(newarg, ".libs");
1155     newpathlen += sizeof(".libs") - 1;
1156     newarg[newpathlen] = 0;
1157
1158 #ifdef HAS_REALPATH
1159     expanded_path = malloc(PATH_MAX);
1160     expanded_path = realpath(newarg, expanded_path);
1161     /* Uh, oh.  There was an error.  Fall back on our first guess. */
1162     if (!expanded_path) {
1163         expanded_path = newarg;
1164     }
1165 #else
1166     /* We might get ../ or something goofy.  Oh, well. */
1167     expanded_path = newarg;
1168 #endif
1169
1170     return expanded_path;
1171 }
1172
1173 static void add_dynamic_link_opts(command_t *cmd_data, count_chars *args)
1174 {
1175 #ifdef DYNAMIC_LINK_OPTS
1176     if (cmd_data->options.pic_mode != pic_AVOID) {
1177         if (cmd_data->options.debug) {
1178            printf("Adding: %s\n", DYNAMIC_LINK_OPTS);
1179         }
1180         push_count_chars(args, DYNAMIC_LINK_OPTS);
1181         if (cmd_data->undefined_flag) {
1182             push_count_chars(args, "-undefined");
1183 #if defined(__APPLE__)
1184             /* -undefined dynamic_lookup is used by the bundled Python in
1185              * 10.4, but if we don't set MACOSX_DEPLOYMENT_TARGET to 10.3+,
1186              * we'll get a linker error if we pass this flag.
1187              */
1188             if (strcasecmp(cmd_data->undefined_flag,
1189                            "dynamic_lookup") == 0) {
1190                 insert_count_chars(cmd_data->program_opts,
1191                                    "MACOSX_DEPLOYMENT_TARGET=10.3", 0);
1192             }
1193 #endif
1194             push_count_chars(args, cmd_data->undefined_flag);
1195         }
1196         else {
1197 #ifdef DYNAMIC_LINK_UNDEFINED
1198             if (cmd_data->options.debug) {
1199                 printf("Adding: %s\n", DYNAMIC_LINK_UNDEFINED);
1200             }
1201             push_count_chars(args, DYNAMIC_LINK_UNDEFINED);
1202 #endif
1203         }
1204     }
1205 #endif
1206 }
1207
1208 /* Read the final install location and add it to runtime library search path. */
1209 #ifdef RPATH
1210 static void add_rpath(count_chars *cc, const char *path)
1211 {
1212     int size = 0;
1213     char *tmp;
1214
1215 #ifdef LINKER_FLAG_PREFIX
1216     size = strlen(LINKER_FLAG_PREFIX);
1217 #endif
1218     size = size + strlen(path) + strlen(RPATH) + 2;
1219     tmp = malloc(size);
1220     if (tmp == NULL) {
1221         return;
1222     }
1223 #ifdef LINKER_FLAG_PREFIX
1224     strcpy(tmp, LINKER_FLAG_PREFIX);
1225     strcat(tmp, RPATH);
1226 #else
1227     strcpy(tmp, RPATH);
1228 #endif
1229 #ifndef LINKER_FLAG_NO_EQUALS
1230     strcat(tmp, "=");
1231 #endif
1232     strcat(tmp, path);
1233
1234     push_count_chars(cc, tmp);
1235 }
1236
1237 static void add_rpath_file(count_chars *cc, const char *arg)
1238 {
1239     const char *path;
1240
1241     path = load_install_path(arg);
1242     if (path) {
1243         add_rpath(cc, path);
1244     }
1245 }
1246
1247 static void add_rpath_noinstall(count_chars *cc, const char *arg, int pathlen)
1248 {
1249     const char *path;
1250
1251     path = load_noinstall_path(arg, pathlen);
1252     if (path) {
1253         add_rpath(cc, path);
1254         free(path);
1255     }
1256 }
1257 #endif
1258
1259 #ifdef DYNAMIC_LINK_NO_INSTALL
1260 static void add_dylink_noinstall(count_chars *cc, const char *arg, int pathlen,
1261                           int extlen)
1262 {
1263     const char *install_path, *current_path, *name;
1264     char *exp_argument;
1265     int i_p_len, c_p_len, name_len, dyext_len, cur_len;
1266
1267     install_path = load_install_path(arg);
1268     current_path = load_noinstall_path(arg, pathlen);
1269
1270     if (!install_path || !current_path) {
1271         return;
1272     }
1273
1274     push_count_chars(cc, DYNAMIC_LINK_NO_INSTALL);
1275
1276     i_p_len = strlen(install_path);
1277     c_p_len = strlen(current_path);
1278
1279     name = arg+pathlen;
1280     name_len = extlen-pathlen;
1281     dyext_len = sizeof(DYNAMIC_LIB_EXT) - 1;
1282
1283     /* No, we need to replace the extension. */
1284     exp_argument = (char *)malloc(i_p_len + c_p_len + (name_len*2) +
1285                                   (dyext_len*2) + 2);
1286
1287     cur_len = 0;
1288     strcpy(exp_argument, install_path);
1289     cur_len += i_p_len;
1290     exp_argument[cur_len++] = '/';
1291     strncpy(exp_argument+cur_len, name, extlen-pathlen);
1292     cur_len += name_len;
1293     strcpy(exp_argument+cur_len, DYNAMIC_LIB_EXT);
1294     cur_len += dyext_len;
1295     exp_argument[cur_len++] = ':';
1296     strcpy(exp_argument+cur_len, current_path);
1297     cur_len += c_p_len;
1298     exp_argument[cur_len++] = '/';
1299     strncpy(exp_argument+cur_len, name, extlen-pathlen);
1300     cur_len += name_len;
1301     strcpy(exp_argument+cur_len, DYNAMIC_LIB_EXT);
1302     cur_len += dyext_len;
1303
1304     push_count_chars(cc, exp_argument);
1305 }
1306 #endif
1307
1308 #ifdef ADD_MINUS_L
1309 /* use -L -llibname to allow to use installed libraries */
1310 static void add_minus_l(count_chars *cc, const char *arg)
1311 {
1312     char *newarg;
1313     char *name = strrchr(arg, '/');
1314     char *file = strrchr(arg, '.');
1315
1316     if ((name != NULL) && (file != NULL) &&
1317         (strstr(name, "lib") == (name + 1))) {
1318         *name = '\0';
1319         *file = '\0';
1320         file = name;
1321         file = file+4;
1322         push_count_chars(cc, "-L");
1323         push_count_chars(cc, arg);
1324         /* we need one argument like -lapr-1 */
1325         newarg = malloc(strlen(file) + 3);
1326         strcpy(newarg, "-l");
1327         strcat(newarg, file);
1328         push_count_chars(cc, newarg);
1329     } else {
1330         push_count_chars(cc, arg);
1331     }
1332 }
1333 #endif
1334
1335 #if 0
1336 static void add_linker_flag_prefix(count_chars *cc, const char *arg)
1337 {
1338 #ifndef LINKER_FLAG_PREFIX
1339     push_count_chars(cc, arg);
1340 #else
1341     char *newarg;
1342     newarg = (char*)malloc(strlen(arg) + sizeof(LINKER_FLAG_PREFIX) + 1);
1343     strcpy(newarg, LINKER_FLAG_PREFIX);
1344     strcat(newarg, arg);
1345     push_count_chars(cc, newarg);
1346 #endif
1347 }
1348 #endif
1349
1350 static int explode_static_lib(command_t *cmd_data, const char *lib)
1351 {
1352     count_chars tmpdir_cc, libname_cc;
1353     const char *tmpdir, *libname;
1354     char savewd[PATH_MAX];
1355     const char *name;
1356     DIR *dir;
1357     struct dirent *entry;
1358     const char *lib_args[4];
1359
1360     /* Bah! */
1361     if (cmd_data->options.dry_run) {
1362         return 0;
1363     }
1364
1365     name = jlibtool_basename(lib);
1366
1367     init_count_chars(&tmpdir_cc);
1368     push_count_chars(&tmpdir_cc, ".libs/");
1369     push_count_chars(&tmpdir_cc, name);
1370     push_count_chars(&tmpdir_cc, ".exploded/");
1371     tmpdir = flatten_count_chars(&tmpdir_cc, 0);
1372
1373     if (!cmd_data->options.silent) {
1374         printf("Making: %s\n", tmpdir);
1375     }
1376     safe_mkdir(tmpdir);
1377
1378     push_count_chars(cmd_data->tmp_dirs, tmpdir);
1379
1380     getcwd(savewd, sizeof(savewd));
1381
1382     if (chdir(tmpdir) != 0) {
1383         if (!cmd_data->options.silent) {
1384             printf("Warning: could not explode %s\n", lib);
1385         }
1386         return 1;
1387     }
1388
1389     if (lib[0] == '/') {
1390         libname = lib;
1391     }
1392     else {
1393         init_count_chars(&libname_cc);
1394         push_count_chars(&libname_cc, "../../");
1395         push_count_chars(&libname_cc, lib);
1396         libname = flatten_count_chars(&libname_cc, 0);
1397     }
1398
1399     lib_args[0] = LIBRARIAN;
1400     lib_args[1] = "x";
1401     lib_args[2] = libname;
1402     lib_args[3] = NULL;
1403
1404     external_spawn(cmd_data, LIBRARIAN, lib_args);
1405
1406     chdir(savewd);
1407     dir = opendir(tmpdir);
1408
1409     while ((entry = readdir(dir)) != NULL) {
1410 #if defined(__APPLE__) && defined(RANLIB)
1411         /* Apple inserts __.SYMDEF which isn't needed.
1412          * Leopard (10.5+) can also add '__.SYMDEF SORTED' which isn't
1413          * much fun either.  Just skip them.
1414          */
1415         if (strstr(entry->d_name, "__.SYMDEF") != NULL) {
1416             continue;
1417         }
1418 #endif
1419         if (entry->d_name[0] != '.') {
1420             push_count_chars(&tmpdir_cc, entry->d_name);
1421             name = flatten_count_chars(&tmpdir_cc, 0);
1422             if (cmd_data->options.debug) {
1423                 printf("Adding: %s\n", name);
1424             }
1425             push_count_chars(cmd_data->obj_files, name);
1426             pop_count_chars(&tmpdir_cc);
1427         }
1428     }
1429
1430     closedir(dir);
1431     return 0;
1432 }
1433
1434 static int parse_input_file_name(char *arg, command_t *cmd_data)
1435 {
1436     const char *ext = strrchr(arg, '.');
1437     const char *name;
1438     int pathlen;
1439     enum lib_type libtype;
1440     const char *newarg;
1441
1442     if (!ext) {
1443         return 0;
1444     }
1445
1446     ext++;
1447     name = jlibtool_basename(arg);
1448
1449     pathlen = name - arg;
1450
1451     if (strcmp(ext, "lo") == 0) {
1452         newarg = check_object_exists(cmd_data, arg, ext - arg);
1453         if (!newarg) {
1454             fprintf(stderr, "Can not find suitable object file for %s\n", arg);
1455             exit(1);
1456         }
1457         if (cmd_data->mode != mLink) {
1458             push_count_chars(cmd_data->arglist, newarg);
1459         }
1460         else {
1461             push_count_chars(cmd_data->obj_files, newarg);
1462         }
1463         return 1;
1464     }
1465
1466     if (strcmp(ext, "la") == 0) {
1467         switch (cmd_data->mode) {
1468         case mLink:
1469             /* Try the .libs dir first! */
1470             newarg = check_library_exists(cmd_data, arg, pathlen, 1, &libtype);
1471             if (!newarg) {
1472                 /* Try the normal dir next. */
1473                 newarg = check_library_exists(cmd_data, arg, pathlen, 0, &libtype);
1474                 if (!newarg) {
1475                     fprintf(stderr, "Can not find suitable library for %s\n", arg);
1476                     exit(1);
1477                 }
1478             }
1479
1480             /* It is not ok to just add the file: a library may added with:
1481                1 - -L path library_name. (For *.so in Linux).
1482                2 - library_name.
1483              */
1484 #ifdef ADD_MINUS_L
1485             if (libtype == type_DYNAMIC_LIB) {
1486                  add_minus_l(cmd_data->shared_opts.dependencies, newarg);
1487             } else if (cmd_data->output == otLibrary &&
1488                        libtype == type_STATIC_LIB) {
1489                 explode_static_lib(cmd_data, newarg);
1490             } else {
1491                  push_count_chars(cmd_data->shared_opts.dependencies, newarg);
1492             }
1493 #else
1494             if (cmd_data->output == otLibrary && libtype == type_STATIC_LIB) {
1495                 explode_static_lib(cmd_data, newarg);
1496             }
1497             else {
1498                 push_count_chars(cmd_data->shared_opts.dependencies, newarg);
1499             }
1500 #endif
1501             if (libtype == type_DYNAMIC_LIB) {
1502                 if (cmd_data->options.no_install) {
1503 #ifdef RPATH
1504                     add_rpath_noinstall(cmd_data->shared_opts.dependencies,
1505                                         arg, pathlen);
1506 #endif
1507 #ifdef DYNAMIC_LINK_NO_INSTALL
1508                     /*
1509                      * This doesn't work as Darwin's linker has no way to
1510                      * override at link-time the search paths for a
1511                      * non-installed library.
1512                      */
1513                     /*
1514                     add_dylink_noinstall(cmd_data->shared_opts.dependencies,
1515                                          arg, pathlen, ext - arg);
1516                     */
1517 #endif
1518                 }
1519                 else {
1520 #ifdef RPATH
1521                     add_rpath_file(cmd_data->shared_opts.dependencies, arg);
1522 #endif
1523                 }
1524             }
1525             break;
1526         case mInstall:
1527             /* If we've already recorded a library to install, we're most
1528              * likely getting the .la file that we want to install as.
1529              * The problem is that we need to add it as the directory,
1530              * not the .la file itself.  Otherwise, we'll do odd things.
1531              */
1532             if (cmd_data->output == otLibrary) {
1533                 arg[pathlen] = '\0';
1534                 push_count_chars(cmd_data->arglist, arg);
1535             }
1536             else {
1537                 cmd_data->output = otLibrary;
1538                 cmd_data->output_name = arg;
1539                 cmd_data->static_name.install = gen_install_name(arg, 0);
1540                 cmd_data->shared_name.install = gen_install_name(arg, 1);
1541                 cmd_data->module_name.install = gen_install_name(arg, 2);
1542
1543                 if (!cmd_data->static_name.install &&
1544                     !cmd_data->shared_name.install &&
1545                     !cmd_data->module_name.install) {
1546                   fprintf(stderr, "Files to install do not exist\n");
1547                   exit(1);
1548                 }
1549
1550             }
1551             break;
1552         default:
1553             break;
1554         }
1555         return 1;
1556     }
1557
1558     if (strcmp(ext, "c") == 0) {
1559         /* If we don't already have an idea what our output name will be. */
1560         if (cmd_data->basename == NULL) {
1561             cmd_data->basename = (char *)malloc(strlen(arg) + 4);
1562             strcpy(cmd_data->basename, arg);
1563             strcpy(strrchr(cmd_data->basename, '.') + 1, "lo");
1564
1565             cmd_data->fake_output_name = strrchr(cmd_data->basename, '/');
1566             if (cmd_data->fake_output_name) {
1567                 cmd_data->fake_output_name++;
1568             }
1569             else {
1570                 cmd_data->fake_output_name = cmd_data->basename;
1571             }
1572         }
1573     }
1574
1575     return 0;
1576 }
1577
1578 static int parse_output_file_name(char *arg, command_t *cmd_data)
1579 {
1580     const char *name;
1581     const char *ext;
1582     char *newarg = NULL;
1583     int pathlen;
1584
1585     cmd_data->fake_output_name = arg;
1586
1587     name = jlibtool_basename(arg);
1588     ext = strrchr(name, '.');
1589
1590 #ifdef EXE_EXT
1591     if (!ext || strcmp(ext, EXE_EXT) == 0) {
1592 #else
1593     if (!ext) {
1594 #endif
1595         cmd_data->basename = arg;
1596         cmd_data->output = otProgram;
1597 #if defined(_OSD_POSIX)
1598         cmd_data->options.pic_mode = pic_AVOID;
1599 #endif
1600         newarg = (char *)malloc(strlen(arg) + 5);
1601         strcpy(newarg, arg);
1602 #ifdef EXE_EXT
1603         if (!ext) {
1604           strcat(newarg, EXE_EXT);
1605         }
1606 #endif
1607         cmd_data->output_name = newarg;
1608         return 1;
1609     }
1610
1611     ext++;
1612     pathlen = name - arg;
1613
1614     if (strcmp(ext, "la") == 0) {
1615         assert(cmd_data->mode == mLink);
1616
1617         cmd_data->basename = arg;
1618         cmd_data->static_name.normal = gen_library_name(arg, type_STATIC_LIB);
1619         cmd_data->shared_name.normal = gen_library_name(arg, type_DYNAMIC_LIB);
1620         cmd_data->module_name.normal = gen_library_name(arg, type_MODULE_LIB);
1621         cmd_data->static_name.install = gen_install_name(arg, type_STATIC_LIB);
1622         cmd_data->shared_name.install = gen_install_name(arg, type_DYNAMIC_LIB);
1623         cmd_data->module_name.install = gen_install_name(arg, type_MODULE_LIB);
1624
1625         if (!cmd_data->options.dry_run) {
1626                 char *newname;
1627                 char *newext;
1628                 newname = malloc(strlen(cmd_data->static_name.normal) + 1);
1629
1630                 strcpy(newname, cmd_data->static_name.normal);
1631                 newext = strrchr(newname, '/');
1632                 if (!newext) {
1633                         /* Check first to see if the dir already exists! */
1634                         safe_mkdir(".libs");
1635                 } else {
1636                         *newext = '\0';
1637                         safe_mkdir(newname);
1638                 }
1639                 free(newname);
1640         }
1641
1642 #ifdef TRUNCATE_DLL_NAME
1643         if (shared) {
1644           arg = truncate_dll_name(arg);
1645         }
1646 #endif
1647
1648         cmd_data->output_name = arg;
1649         return 1;
1650     }
1651
1652     if (strcmp(ext, STATIC_LIB_EXT) == 0) {
1653         assert(cmd_data->mode == mLink);
1654
1655         cmd_data->basename = arg;
1656         cmd_data->options.shared = share_STATIC;
1657         cmd_data->output = otStaticLibraryOnly;
1658         cmd_data->static_name.normal = gen_library_name(arg, type_STATIC_LIB);
1659         cmd_data->static_name.install = gen_install_name(arg, type_STATIC_LIB);
1660
1661         if (!cmd_data->options.dry_run) {
1662                 char *newname;
1663                 char *newext;
1664                 newname = malloc(strlen(cmd_data->static_name.normal) + 1);
1665
1666                 strcpy(newname, cmd_data->static_name.normal);
1667                 newext = strrchr(newname, '/');
1668                 if (!newext) {
1669                         /* Check first to see if the dir already exists! */
1670                         safe_mkdir(".libs");
1671                 } else {
1672                         *newext = '\0';
1673                         safe_mkdir(newname);
1674                 }
1675                 free(newname);
1676         }
1677
1678         cmd_data->output_name = arg;
1679         return 1;
1680     }
1681
1682     if (strcmp(ext, DYNAMIC_LIB_EXT) == 0) {
1683         assert(cmd_data->mode == mLink);
1684
1685         cmd_data->basename = arg;
1686         cmd_data->options.shared = share_SHARED;
1687         cmd_data->output = otDynamicLibraryOnly;
1688         cmd_data->shared_name.normal = gen_library_name(arg, type_DYNAMIC_LIB);
1689         cmd_data->module_name.normal = gen_library_name(arg, type_MODULE_LIB);
1690         cmd_data->shared_name.install = gen_install_name(arg, type_DYNAMIC_LIB);
1691         cmd_data->module_name.install = gen_install_name(arg, type_MODULE_LIB);
1692
1693         if (!cmd_data->options.dry_run) {
1694                 char *newname;
1695                 char *newext;
1696                 newname = malloc(strlen(cmd_data->shared_name.normal) + 1);
1697
1698                 strcpy(newname, cmd_data->shared_name.normal);
1699                 newext = strrchr(newname, '/');
1700                 if (!newext) {
1701                         /* Check first to see if the dir already exists! */
1702                         safe_mkdir(".libs");
1703                 } else {
1704                         *newext = '\0';
1705                         safe_mkdir(newname);
1706                 }
1707                 free(newname);
1708         }
1709
1710         cmd_data->output_name = arg;
1711         return 1;
1712     }
1713
1714     if (strcmp(ext, "lo") == 0) {
1715         char *newext;
1716         cmd_data->basename = arg;
1717         cmd_data->output = otObject;
1718         newarg = (char *)malloc(strlen(arg) + 2);
1719         strcpy(newarg, arg);
1720         newext = strrchr(newarg, '.') + 1;
1721         strcpy(newext, OBJECT_EXT);
1722         cmd_data->output_name = newarg;
1723         return 1;
1724     }
1725
1726     if (strcmp(ext, DYNAMIC_LIB_EXT) == 0) {
1727       fprintf(stderr, "Please build libraries with .la target, not ."
1728               DYNAMIC_LIB_EXT "\n");
1729       exit(1);
1730     }
1731
1732     if (strcmp(ext, STATIC_LIB_EXT) == 0) {
1733       fprintf(stderr, "Please build libraries with .la target, not ."
1734               STATIC_LIB_EXT "\n");
1735       exit(1);
1736     }
1737
1738     return 0;
1739 }
1740
1741 static char *automode(char *arg, command_t *cmd_data)
1742 {
1743         if (cmd_data->mode != mUnknown) return arg;
1744
1745         if (strcmp(arg, "CC") == 0) {
1746                 arg = CC;
1747                 cmd_data->mode = mCompile;
1748
1749         } else if (strcmp(arg, "CXX") == 0) {
1750                 arg = CXX;
1751                 cmd_data->mode = mCompile;
1752
1753         } else if (strcmp(arg, "LINK") == 0) {
1754                 arg = LINK_c;
1755                 cmd_data->mode = mLink;
1756
1757         } else if (strcmp(arg, "LINK.c") == 0) {
1758                 arg = LINK_c;
1759                 cmd_data->mode = mLink;
1760
1761         } else if (strcmp(arg, "LINK.cxx") == 0) {
1762                 arg = LINK_cxx;
1763                 cmd_data->mode = mLink;
1764         }
1765         
1766         return arg;
1767 }
1768
1769 static void parse_args(int argc, char *argv[], command_t *cmd_data)
1770 {
1771     int a;
1772     char *arg, *base;
1773     int argused;
1774
1775     /*
1776      *  We now take a major step past libtool.
1777      *
1778      *  IF there's no "--mode=...", AND we recognise
1779      *  the binary as a "special" name, THEN replace it
1780      *  with the correct one, and set the correct mode.
1781      */
1782     base = jlibtool_basename(argv[0]);
1783     arg = automode(base, cmd_data);
1784     
1785     if (arg != base) {
1786             if (cmd_data->options.debug) {
1787                     printf("Adding: %s\n", arg);
1788             }
1789             push_count_chars(cmd_data->arglist, arg);
1790             assert(cmd_data->mode != mUnknown);
1791     }
1792
1793     /*
1794      *  We first pass over the command-line arguments looking for
1795      *  "--mode", etc.  If so, then use the libtool compatibility
1796      *  method for building the software.  Otherwise, auto-detect it
1797      *  via "-o" and the extensions.
1798      */
1799     base = NULL;
1800     if (cmd_data->mode == mUnknown) for (a = 1; a < argc; a++) {
1801         arg = argv[a];
1802
1803         if (strncmp(arg, "--mode=", 7) == 0) {
1804           base = NULL;
1805           break;
1806         }
1807
1808         /*
1809          *      Stop if we get another magic method
1810          */
1811         if ((a == 1) &&
1812             ((strncmp(arg, "LINK", 4) == 0) ||
1813              (strcmp(arg, "CC") == 0) ||
1814              (strcmp(arg, "CXX") == 0))) {
1815           base = NULL;
1816           break;
1817         }
1818
1819         if (strncmp(arg, "-o", 2) == 0) {
1820           base = argv[++a];
1821         }
1822     }
1823
1824     if (base) {
1825             arg = strrchr(base, '.');
1826             if (!arg) {
1827                     cmd_data->mode = mLink;
1828                     push_count_chars(cmd_data->arglist, LINK_c);
1829             }
1830 #ifdef EXE_EXT
1831             else if (strcmp(arg, EXE_EXT) == 0) {
1832                     cmd_data->mode = mLink;
1833                     push_count_chars(cmd_data->arglist, LINK_c);
1834             }
1835 #endif
1836             else if (strcmp(arg + 1, DYNAMIC_LIB_EXT) == 0) {
1837                     cmd_data->mode = mLink;
1838                     push_count_chars(cmd_data->arglist, LINK_c);
1839             }
1840             else if (strcmp(arg + 1, STATIC_LIB_EXT) == 0) {
1841                     cmd_data->mode = mLink;
1842                     push_count_chars(cmd_data->arglist, LINK_c);
1843             }
1844             else if (strcmp(arg + 1, "la") == 0) {
1845                     cmd_data->mode = mLink;
1846                     push_count_chars(cmd_data->arglist, LINK_c);
1847             }
1848             else if ((strcmp(arg + 1, "lo") == 0) ||
1849                      (strcmp(arg + 1, "o") == 0)) {
1850                     cmd_data->mode = mCompile;
1851                     push_count_chars(cmd_data->arglist, CC);
1852             }
1853     }
1854
1855     for (a = 1; a < argc; a++) {
1856         arg = argv[a];
1857         argused = 1;
1858
1859         if (arg[0] == '-') {
1860             if (arg[1] == '-') {
1861                 argused = parse_long_opt(arg + 2, cmd_data);
1862             }
1863             else {
1864                 argused = parse_short_opt(arg + 1, cmd_data);
1865             }
1866
1867             /* We haven't done anything with it yet, try some of the
1868              * more complicated short opts... */
1869             if (argused == 0 && a + 1 < argc) {
1870                 if (arg[1] == 'o' && !arg[2]) {
1871                     arg = argv[++a];
1872                     argused = parse_output_file_name(arg, cmd_data);
1873                 } else if (strcmp(arg+1, "MT") == 0) {
1874                     if (cmd_data->options.debug) {
1875                         printf("Adding: %s\n", arg);
1876                     }
1877                     push_count_chars(cmd_data->arglist, arg);
1878                     arg = argv[++a];
1879                     if (!cmd_data->options.silent) {
1880                         printf(" %s\n", arg);
1881                     }
1882                     push_count_chars(cmd_data->arglist, arg);
1883                     argused = 1;
1884                 } else if (strcmp(arg+1, "rpath") == 0) {
1885                     /* Aha, we should try to link both! */
1886                     cmd_data->install_path = argv[++a];
1887                     argused = 1;
1888                 } else if (strcmp(arg+1, "release") == 0) {
1889                     /* Store for later deciphering */
1890                     cmd_data->version_info = argv[++a];
1891                     argused = 1;
1892                 } else if (strcmp(arg+1, "version-info") == 0) {
1893                     /* Store for later deciphering */
1894                     cmd_data->version_info = argv[++a];
1895                     argused = 1;
1896                 } else if (strcmp(arg+1, "export-symbols-regex") == 0) {
1897                     /* Skip the argument. */
1898                     ++a;
1899                     argused = 1;
1900                 } else if (strcmp(arg+1, "release") == 0) {
1901                     /* Skip the argument. */
1902                     ++a;
1903                     argused = 1;
1904                 } else if (strcmp(arg+1, "undefined") == 0) {
1905                     cmd_data->undefined_flag = argv[++a];
1906                     argused = 1;
1907                 } else if (arg[1] == 'R' && !arg[2]) {
1908                     /* -R dir Add dir to runtime library search path. */
1909                     add_runtimedirlib(argv[++a], cmd_data);
1910                     argused = 1;
1911                 }
1912             }
1913         } else {
1914             argused = parse_input_file_name(arg, cmd_data);
1915         }
1916
1917         if (!argused) {
1918                 /*
1919                  *  If we still don't have a run mode, look for a magic
1920                  *  program name CC, LINK, or whatever.  Then replace that
1921                  *  with the name of the real program we want to run.
1922                  */
1923                 if ((cmd_data->arglist->num == 0) &&
1924                     (cmd_data->mode == mUnknown)) {
1925                         arg = automode(arg, cmd_data);
1926                 }
1927
1928             if (cmd_data->options.debug) {
1929                 printf("Adding: %s\n", arg);
1930             }
1931             push_count_chars(cmd_data->arglist, arg);
1932         }
1933     }
1934
1935 }
1936
1937 #ifdef GEN_EXPORTS
1938 static void generate_def_file(command_t *cmd_data)
1939 {
1940     char def_file[1024];
1941     char implib_file[1024];
1942     char *ext;
1943     FILE *hDef;
1944     char *export_args[1024];
1945     int num_export_args = 0;
1946     char *cmd;
1947     int cmd_size = 0;
1948     int a;
1949
1950     if (cmd_data->output_name) {
1951         strcpy(def_file, cmd_data->output_name);
1952         strcat(def_file, ".def");
1953         hDef = fopen(def_file, "w");
1954
1955         if (hDef != NULL) {
1956             fprintf(hDef, "LIBRARY '%s' INITINSTANCE\n", nameof(cmd_data->output_name));
1957             fprintf(hDef, "DATA NONSHARED\n");
1958             fprintf(hDef, "EXPORTS\n");
1959             fclose(hDef);
1960
1961             for (a = 0; a < cmd_data->num_obj_files; a++) {
1962                 cmd_size += strlen(cmd_data->obj_files[a]) + 1;
1963             }
1964
1965             cmd_size += strlen(GEN_EXPORTS) + strlen(def_file) + 3;
1966             cmd = (char *)malloc(cmd_size);
1967             strcpy(cmd, GEN_EXPORTS);
1968
1969             for (a=0; a < cmd_data->num_obj_files; a++) {
1970                 strcat(cmd, " ");
1971                 strcat(cmd, cmd_data->obj_files[a] );
1972             }
1973
1974             strcat(cmd, ">>");
1975             strcat(cmd, def_file);
1976             puts(cmd);
1977             export_args[num_export_args++] = SHELL_CMD;
1978             export_args[num_export_args++] = "-c";
1979             export_args[num_export_args++] = cmd;
1980             export_args[num_export_args++] = NULL;
1981             external_spawn(cmd_data, export_args[0], (const char**)export_args);
1982             cmd_data->arglist[cmd_data->num_args++] = strdup(def_file);
1983
1984             /* Now make an import library for the dll */
1985             num_export_args = 0;
1986             export_args[num_export_args++] = DEF2IMPLIB_CMD;
1987             export_args[num_export_args++] = "-o";
1988
1989             strcpy(implib_file, ".libs/");
1990             strcat(implib_file, cmd_data->basename);
1991             ext = strrchr(implib_file, '.');
1992
1993             if (ext)
1994                 *ext = 0;
1995
1996             strcat(implib_file, ".");
1997             strcat(implib_file, STATIC_LIB_EXT);
1998
1999             export_args[num_export_args++] = implib_file;
2000             export_args[num_export_args++] = def_file;
2001             export_args[num_export_args++] = NULL;
2002             external_spawn(cmd_data, export_args[0], (const char**)export_args);
2003
2004         }
2005     }
2006 }
2007 #endif
2008
2009 #if 0
2010 static const char* expand_path(const char *relpath)
2011 {
2012     char foo[PATH_MAX], *newpath;
2013
2014     getcwd(foo, PATH_MAX-1);
2015     newpath = (char*)malloc(strlen(foo)+strlen(relpath)+2);
2016     strcpy(newpath, foo);
2017     strcat(newpath, "/");
2018     strcat(newpath, relpath);
2019     return newpath;
2020 }
2021 #endif
2022
2023 static void link_fixup(command_t *c)
2024 {
2025     /* If we were passed an -rpath directive, we need to build
2026      * shared objects too.  Otherwise, we should only create static
2027      * libraries.
2028      */
2029     if (!c->install_path && (c->output == otDynamicLibraryOnly ||
2030         c->output == otModule || c->output == otLibrary)) {
2031         if (c->options.shared == share_SHARED) {
2032                 c->install_path = LIBDIR;
2033         }
2034     }
2035
2036     if (c->output == otDynamicLibraryOnly ||
2037         c->output == otModule ||
2038         c->output == otLibrary) {
2039
2040         push_count_chars(c->shared_opts.normal, "-o");
2041         if (c->output == otModule) {
2042             push_count_chars(c->shared_opts.normal, c->module_name.normal);
2043         }
2044         else {
2045             char *tmp;
2046             push_count_chars(c->shared_opts.normal, c->shared_name.normal);
2047 #ifdef DYNAMIC_INSTALL_NAME
2048             push_count_chars(c->shared_opts.normal, DYNAMIC_INSTALL_NAME);
2049
2050             if (!c->install_path) {
2051                     fprintf(stderr, "Installation mode requires -rpath\n");
2052                     exit(1);
2053             }
2054
2055             tmp = (char*)malloc(PATH_MAX);
2056             strcpy(tmp, c->install_path);
2057             if (c->shared_name.install) {
2058                     strcat(tmp, strrchr(c->shared_name.install, '/'));
2059             } else {
2060                     strcat(tmp, strrchr(c->shared_name.normal, '/'));
2061             }
2062             push_count_chars(c->shared_opts.normal, tmp);
2063 #endif
2064         }
2065
2066         append_count_chars(c->shared_opts.normal, c->obj_files);
2067         append_count_chars(c->shared_opts.normal, c->shared_opts.dependencies);
2068
2069         if (c->options.export_all) {
2070 #ifdef GEN_EXPORTS
2071             generate_def_file(c);
2072 #endif
2073         }
2074     }
2075
2076     if (c->output == otLibrary || c->output == otStaticLibraryOnly) {
2077         push_count_chars(c->static_opts.normal, "-o");
2078         push_count_chars(c->static_opts.normal, c->output_name);
2079     }
2080
2081     if (c->output == otProgram) {
2082         if (c->output_name) {
2083             push_count_chars(c->arglist, "-o");
2084             push_count_chars(c->arglist, c->output_name);
2085             append_count_chars(c->arglist, c->obj_files);
2086             append_count_chars(c->arglist, c->shared_opts.dependencies);
2087             add_dynamic_link_opts(c, c->arglist);
2088         }
2089     }
2090 }
2091
2092 static void post_parse_fixup(command_t *cmd_data)
2093 {
2094     switch (cmd_data->mode)
2095     {
2096     case mCompile:
2097 #ifdef PIC_FLAG
2098         if (cmd_data->options.pic_mode != pic_AVOID) {
2099             push_count_chars(cmd_data->arglist, PIC_FLAG);
2100         }
2101 #endif
2102         if (cmd_data->output_name) {
2103             push_count_chars(cmd_data->arglist, "-o");
2104             push_count_chars(cmd_data->arglist, cmd_data->output_name);
2105         }
2106         break;
2107     case mLink:
2108         link_fixup(cmd_data);
2109         break;
2110     case mInstall:
2111         if (cmd_data->output == otLibrary) {
2112             link_fixup(cmd_data);
2113         }
2114     default:
2115         break;
2116     }
2117
2118 #ifdef USE_OMF
2119     if (cmd_data->output == otObject ||
2120         cmd_data->output == otProgram ||
2121         cmd_data->output == otLibrary ||
2122         cmd_data->output == otDynamicLibraryOnly) {
2123         push_count_chars(cmd_data->arglist, "-Zomf");
2124     }
2125 #endif
2126
2127     if (cmd_data->options.shared &&
2128             (cmd_data->output == otObject ||
2129              cmd_data->output == otLibrary ||
2130              cmd_data->output == otDynamicLibraryOnly)) {
2131 #ifdef SHARE_SW
2132         push_count_chars(cmd_data->arglist, SHARE_SW);
2133 #endif
2134     }
2135 }
2136
2137 static int run_mode(command_t *cmd_data)
2138 {
2139     int rv;
2140     count_chars *cctemp;
2141
2142     cctemp = (count_chars*)malloc(sizeof(count_chars));
2143     init_count_chars(cctemp);
2144
2145     switch (cmd_data->mode)
2146     {
2147     case mCompile:
2148         rv = run_command(cmd_data, cmd_data->arglist);
2149         if (rv) {
2150             return rv;
2151         }
2152         break;
2153     case mInstall:
2154         /* Well, we'll assume it's a file going to a directory... */
2155         /* For brain-dead install-sh based scripts, we have to repeat
2156          * the command N-times.  install-sh should die.
2157          */
2158         if (!cmd_data->output_name) {
2159             rv = run_command(cmd_data, cmd_data->arglist);
2160             if (rv) {
2161                 return rv;
2162             }
2163         }
2164         if (cmd_data->output_name) {
2165             append_count_chars(cctemp, cmd_data->arglist);
2166             insert_count_chars(cctemp,
2167                                cmd_data->output_name,
2168                                cctemp->num - 1);
2169             rv = run_command(cmd_data, cctemp);
2170             if (rv) {
2171                 return rv;
2172             }
2173             clear_count_chars(cctemp);
2174         }
2175         if (cmd_data->static_name.install) {
2176             append_count_chars(cctemp, cmd_data->arglist);
2177             insert_count_chars(cctemp,
2178                                cmd_data->static_name.install,
2179                                cctemp->num - 1);
2180             rv = run_command(cmd_data, cctemp);
2181             if (rv) {
2182                 return rv;
2183             }
2184 #if defined(__APPLE__) && defined(RANLIB)
2185             /* From the Apple libtool(1) manpage on Tiger/10.4:
2186              * ----
2187              * With  the way libraries used to be created, errors were possible
2188              * if the library was modified with ar(1) and  the  table  of
2189              * contents  was  not updated  by  rerunning ranlib(1).  Thus the
2190              * link editor, ld, warns when the modification date of a library
2191              * is more  recent  than  the  creation date  of its table of
2192              * contents.  Unfortunately, this means that you get the warning
2193              * even if you only copy the library.
2194              * ----
2195              *
2196              * This means that when we install the static archive, we need to
2197              * rerun ranlib afterwards.
2198              */
2199             const char *lib_args[3], *static_lib_name;
2200             char *tmp;
2201             size_t len1, len2;
2202             len1 = strlen(cmd_data->arglist->vals[cmd_data->arglist->num - 1]);
2203
2204             static_lib_name = jlibtool_basename(cmd_data->static_name.install);
2205             len2 = strlen(static_lib_name);
2206
2207             tmp = malloc(len1 + len2 + 2);
2208
2209             snprintf(tmp, len1 + len2 + 2, "%s/%s",
2210                     cmd_data->arglist->vals[cmd_data->arglist->num - 1],
2211                     static_lib_name);
2212
2213             lib_args[0] = RANLIB;
2214             lib_args[1] = tmp;
2215             lib_args[2] = NULL;
2216             external_spawn(cmd_data, RANLIB, lib_args);
2217             free(tmp);
2218 #endif
2219             clear_count_chars(cctemp);
2220         }
2221         if (cmd_data->shared_name.install) {
2222             append_count_chars(cctemp, cmd_data->arglist);
2223             insert_count_chars(cctemp,
2224                                cmd_data->shared_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         if (cmd_data->module_name.install) {
2233             append_count_chars(cctemp, cmd_data->arglist);
2234             insert_count_chars(cctemp,
2235                                cmd_data->module_name.install,
2236                                cctemp->num - 1);
2237             rv = run_command(cmd_data, cctemp);
2238             if (rv) {
2239                 return rv;
2240             }
2241             clear_count_chars(cctemp);
2242         }
2243         break;
2244     case mLink:
2245         if (cmd_data->output == otStaticLibraryOnly ||
2246             cmd_data->output == otLibrary) {
2247 #ifdef RANLIB
2248             const char *lib_args[3];
2249 #endif
2250             /* Removes compiler! */
2251             cmd_data->program = LIBRARIAN;
2252             push_count_chars(cmd_data->program_opts, LIBRARIAN_OPTS);
2253             push_count_chars(cmd_data->program_opts,
2254                              cmd_data->static_name.normal);
2255
2256             rv = run_command(cmd_data, cmd_data->obj_files);
2257             if (rv) {
2258                 return rv;
2259             }
2260
2261 #ifdef RANLIB
2262             lib_args[0] = RANLIB;
2263             lib_args[1] = cmd_data->static_name.normal;
2264             lib_args[2] = NULL;
2265             external_spawn(cmd_data, RANLIB, lib_args);
2266 #endif
2267         }
2268
2269         if (cmd_data->output == otDynamicLibraryOnly ||
2270             cmd_data->output == otModule ||
2271             cmd_data->output == otLibrary) {
2272             cmd_data->program = NULL;
2273             clear_count_chars(cmd_data->program_opts);
2274
2275             append_count_chars(cmd_data->program_opts, cmd_data->arglist);
2276             if (cmd_data->output == otModule) {
2277 #ifdef MODULE_OPTS
2278                 push_count_chars(cmd_data->program_opts, MODULE_OPTS);
2279 #endif
2280             } else {
2281 #ifdef SHARED_OPTS
2282                 push_count_chars(cmd_data->program_opts, SHARED_OPTS);
2283 #endif
2284 #ifdef dynamic_link_version_func
2285                 push_count_chars(cmd_data->program_opts,
2286                              dynamic_link_version_func(cmd_data->version_info));
2287 #endif
2288             }
2289             add_dynamic_link_opts(cmd_data, cmd_data->program_opts);
2290
2291             rv = run_command(cmd_data, cmd_data->shared_opts.normal);
2292             if (rv) {
2293                 return rv;
2294             }
2295         }
2296         if (cmd_data->output == otProgram) {
2297             rv = run_command(cmd_data, cmd_data->arglist);
2298             if (rv) {
2299                 return rv;
2300             }
2301         }
2302         break;
2303     case mExecute:
2304     {
2305         char *l, libpath[PATH_MAX];
2306
2307         strcpy(libpath, cmd_data->arglist->vals[0]);
2308         add_dotlibs(libpath);
2309         l = strrchr(libpath, '/');
2310         if (!l) l = strrchr(libpath, '\\');
2311         if (l) {
2312             *l = '\0';
2313             l = libpath;
2314         } else {
2315             l = ".libs/";
2316         }
2317
2318         l = "./build/lib/.libs";
2319         setenv(LD_LIBRARY_PATH_LOCAL, l, 1);
2320         rv = run_command(cmd_data, cmd_data->arglist);
2321         if (rv) {
2322             return rv;
2323         }
2324     }
2325       break;
2326
2327     default:
2328         break;
2329     }
2330
2331     return 0;
2332 }
2333
2334 static void cleanup_tmp_dir(const char *dirname)
2335 {
2336     DIR *dir;
2337     struct dirent *entry;
2338     char fullname[1024];
2339
2340     dir = opendir(dirname);
2341
2342     if (dir == NULL)
2343         return;
2344
2345     while ((entry = readdir(dir)) != NULL) {
2346         if (entry->d_name[0] != '.') {
2347             strcpy(fullname, dirname);
2348             strcat(fullname, "/");
2349             strcat(fullname, entry->d_name);
2350             (void) remove(fullname);
2351         }
2352     }
2353
2354     rmdir(dirname);
2355 }
2356
2357 static void cleanup_tmp_dirs(command_t *cmd_data)
2358 {
2359     int d;
2360
2361     for (d = 0; d < cmd_data->tmp_dirs->num; d++) {
2362         cleanup_tmp_dir(cmd_data->tmp_dirs->vals[d]);
2363     }
2364 }
2365
2366 static int ensure_fake_uptodate(command_t *cmd_data)
2367 {
2368     /* FIXME: could do the stat/touch here, but nah... */
2369     const char *touch_args[3];
2370
2371     if (cmd_data->mode == mInstall) {
2372         return 0;
2373     }
2374     if (!cmd_data->fake_output_name) {
2375         return 0;
2376     }
2377
2378     touch_args[0] = "touch";
2379     touch_args[1] = cmd_data->fake_output_name;
2380     touch_args[2] = NULL;
2381     return external_spawn(cmd_data, "touch", touch_args);
2382 }
2383
2384 /* Store the install path in the *.la file */
2385 static int add_for_runtime(command_t *cmd_data)
2386 {
2387     if (cmd_data->mode == mInstall) {
2388         return 0;
2389     }
2390     if (cmd_data->output == otDynamicLibraryOnly ||
2391         cmd_data->output == otLibrary) {
2392         FILE *f=fopen(cmd_data->fake_output_name,"w");
2393         if (f == NULL) {
2394             return -1;
2395         }
2396         fprintf(f,"%s\n", cmd_data->install_path);
2397         fclose(f);
2398         return(0);
2399     } else {
2400         return(ensure_fake_uptodate(cmd_data));
2401     }
2402 }
2403
2404 int main(int argc, char *argv[])
2405 {
2406     int rc;
2407     command_t cmd_data;
2408
2409     memset(&cmd_data, 0, sizeof(cmd_data));
2410
2411     cmd_data.options.pic_mode = pic_UNKNOWN;
2412
2413     cmd_data.program_opts = (count_chars*)malloc(sizeof(count_chars));
2414     init_count_chars(cmd_data.program_opts);
2415     cmd_data.arglist = (count_chars*)malloc(sizeof(count_chars));
2416     init_count_chars(cmd_data.arglist);
2417     cmd_data.tmp_dirs = (count_chars*)malloc(sizeof(count_chars));
2418     init_count_chars(cmd_data.tmp_dirs);
2419     cmd_data.obj_files = (count_chars*)malloc(sizeof(count_chars));
2420     init_count_chars(cmd_data.obj_files);
2421     cmd_data.dep_rpaths = (count_chars*)malloc(sizeof(count_chars));
2422     init_count_chars(cmd_data.dep_rpaths);
2423     cmd_data.rpaths = (count_chars*)malloc(sizeof(count_chars));
2424     init_count_chars(cmd_data.rpaths);
2425     cmd_data.static_opts.normal = (count_chars*)malloc(sizeof(count_chars));
2426     init_count_chars(cmd_data.static_opts.normal);
2427     cmd_data.shared_opts.normal = (count_chars*)malloc(sizeof(count_chars));
2428     init_count_chars(cmd_data.shared_opts.normal);
2429     cmd_data.shared_opts.dependencies = (count_chars*)malloc(sizeof(count_chars));
2430     init_count_chars(cmd_data.shared_opts.dependencies);
2431
2432     cmd_data.mode = mUnknown;
2433     cmd_data.output = otGeneral;
2434
2435     parse_args(argc, argv, &cmd_data);
2436     post_parse_fixup(&cmd_data);
2437
2438     if (cmd_data.mode == mUnknown) {
2439        usage(1);
2440     }
2441
2442     rc = run_mode(&cmd_data);
2443
2444     if (!rc) {
2445        add_for_runtime(&cmd_data);
2446     }
2447
2448     cleanup_tmp_dirs(&cmd_data);
2449     return rc;
2450 }