- New function Buf_Append(), which is given a pointer to a string to
[dragonfly.git] / usr.bin / make / arch.c
1 /*
2  * Copyright (c) 1988, 1989, 1990, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 1989 by Berkeley Softworks
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Adam de Boor.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  * @(#)arch.c   8.2 (Berkeley) 1/2/94
39  * $FreeBSD: src/usr.bin/make/arch.c,v 1.15.2.1 2001/02/13 03:13:57 will Exp $
40  * $DragonFly: src/usr.bin/make/arch.c,v 1.26 2005/01/09 23:03:28 okumoto Exp $
41  */
42
43 /*-
44  * arch.c --
45  *      Functions to manipulate libraries, archives and their members.
46  *
47  *      Once again, cacheing/hashing comes into play in the manipulation
48  * of archives. The first time an archive is referenced, all of its members'
49  * headers are read and hashed and the archive closed again. All hashed
50  * archives are kept on a list which is searched each time an archive member
51  * is referenced.
52  *
53  * The interface to this module is:
54  *      Arch_ParseArchive       Given an archive specification, return a list
55  *                              of GNode's, one for each member in the spec.
56  *                              FAILURE is returned if the specification is
57  *                              invalid for some reason.
58  *
59  *      Arch_Touch              Alter the modification time of the archive
60  *                              member described by the given node to be
61  *                              the current time.
62  *
63  *      Arch_TouchLib           Update the modification time of the library
64  *                              described by the given node. This is special
65  *                              because it also updates the modification time
66  *                              of the library's table of contents.
67  *
68  *      Arch_MTime              Find the modification time of a member of
69  *                              an archive *in the archive*. The time is also
70  *                              placed in the member's GNode. Returns the
71  *                              modification time.
72  *
73  *      Arch_MemTime            Find the modification time of a member of
74  *                              an archive. Called when the member doesn't
75  *                              already exist. Looks in the archive for the
76  *                              modification time. Returns the modification
77  *                              time.
78  *
79  *      Arch_FindLib            Search for a library along a path. The
80  *                              library name in the GNode should be in
81  *                              -l<name> format.
82  *
83  *      Arch_LibOODate          Special function to decide if a library node
84  *                              is out-of-date.
85  *
86  *      Arch_Init               Initialize this module.
87  */
88
89 #include <sys/param.h>
90 #include <sys/types.h>
91 #include <ar.h>
92 #include <ctype.h>
93 #include <regex.h>
94 #include <stdlib.h>
95 #include <string.h>
96 #include <utime.h>
97
98 #include "arch.h"
99 #include "config.h"
100 #include "dir.h"
101 #include "globals.h"
102 #include "GNode.h"
103 #include "hash.h"
104 #include "make.h"
105 #include "targ.h"
106 #include "util.h"
107 #include "var.h"
108
109 /* Lst of archives we've already examined */
110 static Lst archives = Lst_Initializer(archives);
111
112 typedef struct Arch {
113     char        *name;          /* Name of archive */
114     Hash_Table  members;        /* All the members of the archive described
115                                  * by <name, struct ar_hdr *> key/value pairs */
116     char        *fnametab;      /* Extended name table strings */
117     size_t      fnamesize;      /* Size of the string table */
118 } Arch;
119
120 static struct ar_hdr *ArchStatMember(const char *, const char *, Boolean);
121 static FILE *ArchFindMember(const char *, const char *, struct ar_hdr *, const char *);
122 #if defined(__svr4__) || defined(__SVR4) || defined(__ELF__)
123 #define SVR4ARCHIVES
124 static int ArchSVR4Entry(Arch *, char *, size_t, FILE *);
125 #endif
126
127 /*-
128  *-----------------------------------------------------------------------
129  * Arch_ParseArchive --
130  *      Parse the archive specification in the given line and find/create
131  *      the nodes for the specified archive members, placing their nodes
132  *      on the given list, given the pointer to the start of the
133  *      specification, a Lst on which to place the nodes, and a context
134  *      in which to expand variables.
135  *
136  * Results:
137  *      SUCCESS if it was a valid specification. The linePtr is updated
138  *      to point to the first non-space after the archive spec. The
139  *      nodes for the members are placed on the given list.
140  *
141  * Side Effects:
142  *      Some nodes may be created. The given list is extended.
143  *
144  *-----------------------------------------------------------------------
145  */
146 ReturnStatus
147 Arch_ParseArchive(char **linePtr, Lst *nodeLst, GNode *ctxt)
148 {
149     char        *cp;            /* Pointer into line */
150     GNode       *gn;            /* New node */
151     char        *libName;       /* Library-part of specification */
152     char        *memName;       /* Member-part of specification */
153     char        *nameBuf;       /* temporary place for node name */
154     char        saveChar;       /* Ending delimiter of member-name */
155     Boolean     subLibName;     /* TRUE if libName should have/had
156                                  * variable substitution performed on it */
157
158     libName = *linePtr;
159
160     subLibName = FALSE;
161
162     for (cp = libName; *cp != '(' && *cp != '\0'; cp++) {
163         if (*cp == '$') {
164             /*
165              * Variable spec, so call the Var module to parse the puppy
166              * so we can safely advance beyond it...
167              */
168             size_t length;
169             Boolean     freeIt;
170             char        *result;
171
172             result = Var_Parse(cp, ctxt, TRUE, &length, &freeIt);
173             if (result == var_Error) {
174                 return (FAILURE);
175             } else {
176                 subLibName = TRUE;
177             }
178
179             if (freeIt) {
180                 free(result);
181             }
182             cp += length - 1;
183         }
184     }
185
186     *cp++ = '\0';
187     if (subLibName) {
188         libName = Var_Subst(NULL, libName, ctxt, TRUE);
189     }
190
191
192     for (;;) {
193         /*
194          * First skip to the start of the member's name, mark that
195          * place and skip to the end of it (either white-space or
196          * a close paren).
197          */
198         Boolean doSubst = FALSE; /* TRUE if need to substitute in memName */
199
200         while (*cp != '\0' && *cp != ')' && isspace((unsigned char)*cp)) {
201             cp++;
202         }
203         memName = cp;
204         while (*cp != '\0' && *cp != ')' && !isspace((unsigned char)*cp)) {
205             if (*cp == '$') {
206                 /*
207                  * Variable spec, so call the Var module to parse the puppy
208                  * so we can safely advance beyond it...
209                  */
210                 size_t length;
211                 Boolean freeIt;
212                 char    *result;
213
214                 result = Var_Parse(cp, ctxt, TRUE, &length, &freeIt);
215                 if (result == var_Error) {
216                     return (FAILURE);
217                 } else {
218                     doSubst = TRUE;
219                 }
220
221                 if (freeIt) {
222                     free(result);
223                 }
224                 cp += length;
225             } else {
226                 cp++;
227             }
228         }
229
230         /*
231          * If the specification ends without a closing parenthesis,
232          * chances are there's something wrong (like a missing backslash),
233          * so it's better to return failure than allow such things to happen
234          */
235         if (*cp == '\0') {
236             printf("No closing parenthesis in archive specification\n");
237             return (FAILURE);
238         }
239
240         /*
241          * If we didn't move anywhere, we must be done
242          */
243         if (cp == memName) {
244             break;
245         }
246
247         saveChar = *cp;
248         *cp = '\0';
249
250         /*
251          * XXX: This should be taken care of intelligently by
252          * SuffExpandChildren, both for the archive and the member portions.
253          */
254         /*
255          * If member contains variables, try and substitute for them.
256          * This will slow down archive specs with dynamic sources, of course,
257          * since we'll be (non-)substituting them three times, but them's
258          * the breaks -- we need to do this since SuffExpandChildren calls
259          * us, otherwise we could assume the thing would be taken care of
260          * later.
261          */
262         if (doSubst) {
263             char    *buf;
264             char    *sacrifice;
265             char    *oldMemName = memName;
266             size_t   sz;
267
268             memName = Var_Subst(NULL, memName, ctxt, TRUE);
269
270             /*
271              * Now form an archive spec and recurse to deal with nested
272              * variables and multi-word variable values.... The results
273              * are just placed at the end of the nodeLst we're returning.
274              */
275
276             sz = strlen(memName) + strlen(libName) + 3;
277             buf = sacrifice = emalloc(sz);
278
279             snprintf(buf, sz, "%s(%s)", libName, memName);
280
281             if (strchr(memName, '$') && strcmp(memName, oldMemName) == 0) {
282                 /*
283                  * Must contain dynamic sources, so we can't deal with it now.
284                  * Just create an ARCHV node for the thing and let
285                  * SuffExpandChildren handle it...
286                  */
287                 gn = Targ_FindNode(buf, TARG_CREATE);
288
289                 if (gn == NULL) {
290                     free(buf);
291                     return (FAILURE);
292                 } else {
293                     gn->type |= OP_ARCHV;
294                     Lst_AtEnd(nodeLst, (void *)gn);
295                 }
296             } else if (Arch_ParseArchive(&sacrifice, nodeLst, ctxt) != SUCCESS) {
297                 /*
298                  * Error in nested call -- free buffer and return FAILURE
299                  * ourselves.
300                  */
301                 free(buf);
302                 return (FAILURE);
303             }
304             /*
305              * Free buffer and continue with our work.
306              */
307             free(buf);
308         } else if (Dir_HasWildcards(memName)) {
309             Lst members = Lst_Initializer(members);
310             char  *member;
311             size_t sz = MAXPATHLEN;
312             size_t nsz;
313
314             nameBuf = emalloc(sz);
315
316             Dir_Expand(memName, &dirSearchPath, &members);
317             while (!Lst_IsEmpty(&members)) {
318                 member = Lst_DeQueue(&members);
319                 nsz = strlen(libName) + strlen(member) + 3; /* 3 = ()+\0 */
320                 if (sz < nsz) {
321                         sz = nsz * 2;
322                         nameBuf = erealloc(nameBuf, sz);
323                 }
324                 snprintf(nameBuf, sz, "%s(%s)", libName, member);
325                 free(member);
326                 gn = Targ_FindNode(nameBuf, TARG_CREATE);
327                 if (gn == NULL) {
328                     free(nameBuf);
329                     /* XXXHB Lst_Destroy(&members) */
330                     return (FAILURE);
331                 } else {
332                     /*
333                      * We've found the node, but have to make sure the rest of
334                      * the world knows it's an archive member, without having
335                      * to constantly check for parentheses, so we type the
336                      * thing with the OP_ARCHV bit before we place it on the
337                      * end of the provided list.
338                      */
339                     gn->type |= OP_ARCHV;
340                     Lst_AtEnd(nodeLst, (void *)gn);
341                 }
342             }
343             free(nameBuf);
344         } else {
345             size_t sz = strlen(libName) + strlen(memName) + 3;
346             nameBuf = emalloc(sz);
347             snprintf(nameBuf, sz, "%s(%s)", libName, memName);
348             gn = Targ_FindNode(nameBuf, TARG_CREATE);
349             free(nameBuf);
350             if (gn == NULL) {
351                 return (FAILURE);
352             } else {
353                 /*
354                  * We've found the node, but have to make sure the rest of the
355                  * world knows it's an archive member, without having to
356                  * constantly check for parentheses, so we type the thing with
357                  * the OP_ARCHV bit before we place it on the end of the
358                  * provided list.
359                  */
360                 gn->type |= OP_ARCHV;
361                 Lst_AtEnd(nodeLst, gn);
362             }
363         }
364         if (doSubst) {
365             free(memName);
366         }
367
368         *cp = saveChar;
369     }
370
371     /*
372      * If substituted libName, free it now, since we need it no longer.
373      */
374     if (subLibName) {
375         free(libName);
376     }
377
378     /*
379      * We promised the pointer would be set up at the next non-space, so
380      * we must advance cp there before setting *linePtr... (note that on
381      * entrance to the loop, cp is guaranteed to point at a ')')
382      */
383     do {
384         cp++;
385     } while (*cp != '\0' && isspace((unsigned char)*cp));
386
387     *linePtr = cp;
388     return (SUCCESS);
389 }
390
391 /*-
392  *-----------------------------------------------------------------------
393  * ArchFindArchive --
394  *      See if the given archive is the one we are looking for. Called
395  *      From ArchStatMember and ArchFindMember via Lst_Find with the
396  *      current list element and the name we want.
397  *
398  * Results:
399  *      0 if it is, non-zero if it isn't.
400  *
401  * Side Effects:
402  *      None.
403  *
404  *-----------------------------------------------------------------------
405  */
406 static int
407 ArchFindArchive(const void *ar, const void *archName)
408 {
409         return (strcmp(archName, ((const Arch *)ar)->name));
410 }
411
412 /*-
413  *-----------------------------------------------------------------------
414  * ArchStatMember --
415  *      Locate a member of an archive, given the path of the archive and
416  *      the path of the desired member, and a boolean representing whether
417  *      or not the archive should be hashed (if not already hashed).
418  *
419  * Results:
420  *      A pointer to the current struct ar_hdr structure for the member. Note
421  *      That no position is returned, so this is not useful for touching
422  *      archive members. This is mostly because we have no assurances that
423  *      The archive will remain constant after we read all the headers, so
424  *      there's not much point in remembering the position...
425  *
426  * Side Effects:
427  *
428  *-----------------------------------------------------------------------
429  */
430 static struct ar_hdr *
431 ArchStatMember(const char *archive, const char *member, Boolean hash)
432 {
433 #define AR_MAX_NAME_LEN     (sizeof(arh.ar_name) - 1)
434     FILE        *arch;  /* Stream to archive */
435     int         size;   /* Size of archive member */
436     char        *cp;    /* Useful character pointer */
437     char        magic[SARMAG];
438     LstNode     *ln;    /* Lst member containing archive descriptor */
439     Arch        *ar;    /* Archive descriptor */
440     Hash_Entry  *he;    /* Entry containing member's description */
441     struct ar_hdr arh;  /* archive-member header for reading archive */
442     char        memName[MAXPATHLEN]; /* Current member name while hashing. */
443
444     /*
445      * Because of space constraints and similar things, files are archived
446      * using their final path components, not the entire thing, so we need
447      * to point 'member' to the final component, if there is one, to make
448      * the comparisons easier...
449      */
450     cp = strrchr(member, '/');
451     if ((cp != NULL) && (strcmp(member, RANLIBMAG) != 0))
452         member = cp + 1;
453
454     ln = Lst_Find(&archives, archive, ArchFindArchive);
455     if (ln != NULL) {
456         ar = Lst_Datum(ln);
457
458         he = Hash_FindEntry(&ar->members, member);
459
460         if (he != NULL) {
461             return ((struct ar_hdr *)Hash_GetValue (he));
462         } else {
463             /* Try truncated name */
464             char copy[AR_MAX_NAME_LEN + 1];
465             size_t len = strlen(member);
466
467             if (len > AR_MAX_NAME_LEN) {
468                 len = AR_MAX_NAME_LEN;
469                 strncpy(copy, member, AR_MAX_NAME_LEN);
470                 copy[AR_MAX_NAME_LEN] = '\0';
471             }
472             if ((he = Hash_FindEntry(&ar->members, copy)) != NULL)
473                 return (Hash_GetValue(he));
474             return (NULL);
475         }
476     }
477
478     if (!hash) {
479         /*
480          * Caller doesn't want the thing hashed, just use ArchFindMember
481          * to read the header for the member out and close down the stream
482          * again. Since the archive is not to be hashed, we assume there's
483          * no need to allocate extra room for the header we're returning,
484          * so just declare it static.
485          */
486          static struct ar_hdr   sarh;
487
488          arch = ArchFindMember(archive, member, &sarh, "r");
489
490         if (arch == NULL) {
491             return (NULL);
492         } else {
493             fclose(arch);
494             return (&sarh);
495         }
496     }
497
498     /*
499      * We don't have this archive on the list yet, so we want to find out
500      * everything that's in it and cache it so we can get at it quickly.
501      */
502     arch = fopen(archive, "r");
503     if (arch == NULL) {
504         return (NULL);
505     }
506
507     /*
508      * We use the ARMAG string to make sure this is an archive we
509      * can handle...
510      */
511     if ((fread(magic, SARMAG, 1, arch) != 1) ||
512         (strncmp(magic, ARMAG, SARMAG) != 0)) {
513             fclose(arch);
514             return (NULL);
515     }
516
517     ar = emalloc(sizeof(Arch));
518     ar->name = estrdup(archive);
519     ar->fnametab = NULL;
520     ar->fnamesize = 0;
521     Hash_InitTable(&ar->members, -1);
522     memName[AR_MAX_NAME_LEN] = '\0';
523
524     while (fread(&arh, sizeof(struct ar_hdr), 1, arch) == 1) {
525         if (strncmp(arh.ar_fmag, ARFMAG, sizeof(arh.ar_fmag)) != 0) {
526             /*
527              * The header is bogus, so the archive is bad
528              * and there's no way we can recover...
529              */
530             goto badarch;
531         } else {
532             /*
533              * We need to advance the stream's pointer to the start of the
534              * next header. Files are padded with newlines to an even-byte
535              * boundary, so we need to extract the size of the file from the
536              * 'size' field of the header and round it up during the seek.
537              */
538             arh.ar_size[sizeof(arh.ar_size) - 1] = '\0';
539             size = (int)strtol(arh.ar_size, NULL, 10);
540
541             strncpy(memName, arh.ar_name, sizeof(arh.ar_name));
542             for (cp = &memName[AR_MAX_NAME_LEN]; *cp == ' '; cp--) {
543                 continue;
544             }
545             cp[1] = '\0';
546
547 #ifdef SVR4ARCHIVES
548             /*
549              * svr4 names are slash terminated. Also svr4 extended AR format.
550              */
551             if (memName[0] == '/') {
552                 /*
553                  * svr4 magic mode; handle it
554                  */
555                 switch (ArchSVR4Entry(ar, memName, size, arch)) {
556                 case -1:  /* Invalid data */
557                     goto badarch;
558                 case 0:   /* List of files entry */
559                     continue;
560                 default:  /* Got the entry */
561                     break;
562                 }
563             }
564             else {
565                 if (cp[0] == '/')
566                     cp[0] = '\0';
567             }
568 #endif
569
570 #ifdef AR_EFMT1
571             /*
572              * BSD 4.4 extended AR format: #1/<namelen>, with name as the
573              * first <namelen> bytes of the file
574              */
575             if (strncmp(memName, AR_EFMT1, sizeof(AR_EFMT1) - 1) == 0 &&
576                 isdigit(memName[sizeof(AR_EFMT1) - 1])) {
577
578                 unsigned int elen = atoi(&memName[sizeof(AR_EFMT1)-1]);
579
580                 if (elen > MAXPATHLEN)
581                         goto badarch;
582                 if (fread(memName, elen, 1, arch) != 1)
583                         goto badarch;
584                 memName[elen] = '\0';
585                 fseek(arch, -elen, SEEK_CUR);
586                 /* XXX Multiple levels may be asked for, make this conditional
587                  * on one, and use DEBUGF.
588                  */
589                 if (DEBUG(ARCH) || DEBUG(MAKE)) {
590                     fprintf(stderr, "ArchStat: Extended format entry for %s\n", memName);
591                 }
592             }
593 #endif
594
595             he = Hash_CreateEntry(&ar->members, memName, NULL);
596             Hash_SetValue(he, emalloc(sizeof(struct ar_hdr)));
597             memcpy(Hash_GetValue(he), &arh, sizeof(struct ar_hdr));
598         }
599         fseek(arch, (size + 1) & ~1, SEEK_CUR);
600     }
601
602     fclose(arch);
603
604     Lst_AtEnd(&archives, ar);
605
606     /*
607      * Now that the archive has been read and cached, we can look into
608      * the hash table to find the desired member's header.
609      */
610     he = Hash_FindEntry(&ar->members, member);
611
612     if (he != NULL) {
613         return (Hash_GetValue (he));
614     } else {
615         return (NULL);
616     }
617
618 badarch:
619     fclose(arch);
620     Hash_DeleteTable(&ar->members);
621     free(ar->fnametab);
622     free(ar);
623     return (NULL);
624 }
625
626 #ifdef SVR4ARCHIVES
627 /*-
628  *-----------------------------------------------------------------------
629  * ArchSVR4Entry --
630  *      Parse an SVR4 style entry that begins with a slash.
631  *      If it is "//", then load the table of filenames
632  *      If it is "/<offset>", then try to substitute the long file name
633  *      from offset of a table previously read.
634  *
635  * Results:
636  *      -1: Bad data in archive
637  *       0: A table was loaded from the file
638  *       1: Name was successfully substituted from table
639  *       2: Name was not successfully substituted from table
640  *
641  * Side Effects:
642  *      If a table is read, the file pointer is moved to the next archive
643  *      member
644  *
645  *-----------------------------------------------------------------------
646  */
647 static int
648 ArchSVR4Entry(Arch *ar, char *name, size_t size, FILE *arch)
649 {
650 #define ARLONGNAMES1 "//"
651 #define ARLONGNAMES2 "/ARFILENAMES"
652     size_t entry;
653     char *ptr, *eptr;
654
655     if (strncmp(name, ARLONGNAMES1, sizeof(ARLONGNAMES1) - 1) == 0 ||
656         strncmp(name, ARLONGNAMES2, sizeof(ARLONGNAMES2) - 1) == 0) {
657
658         if (ar->fnametab != NULL) {
659             DEBUGF(ARCH, ("Attempted to redefine an SVR4 name table\n"));
660             return (-1);
661         }
662
663         /*
664          * This is a table of archive names, so we build one for
665          * ourselves
666          */
667         ar->fnametab = emalloc(size);
668         ar->fnamesize = size;
669
670         if (fread(ar->fnametab, size, 1, arch) != 1) {
671             DEBUGF(ARCH, ("Reading an SVR4 name table failed\n"));
672             return (-1);
673         }
674         eptr = ar->fnametab + size;
675         for (entry = 0, ptr = ar->fnametab; ptr < eptr; ptr++)
676             switch (*ptr) {
677             case '/':
678                 entry++;
679                 *ptr = '\0';
680                 break;
681
682             case '\n':
683                 break;
684
685             default:
686                 break;
687             }
688         DEBUGF(ARCH, ("Found svr4 archive name table with %zu entries\n", entry));
689         return (0);
690     }
691
692     if (name[1] == ' ' || name[1] == '\0')
693         return (2);
694
695     entry = (size_t)strtol(&name[1], &eptr, 0);
696     if ((*eptr != ' ' && *eptr != '\0') || eptr == &name[1]) {
697         DEBUGF(ARCH, ("Could not parse SVR4 name %s\n", name));
698         return (2);
699     }
700     if (entry >= ar->fnamesize) {
701         DEBUGF(ARCH, ("SVR4 entry offset %s is greater than %zu\n",
702                name, ar->fnamesize));
703         return (2);
704     }
705
706     DEBUGF(ARCH, ("Replaced %s with %s\n", name, &ar->fnametab[entry]));
707
708     strncpy(name, &ar->fnametab[entry], MAXPATHLEN);
709     name[MAXPATHLEN - 1] = '\0';
710     return (1);
711 }
712 #endif
713
714
715 /*-
716  *-----------------------------------------------------------------------
717  * ArchFindMember --
718  *      Locate a member of an archive, given the path of the archive and
719  *      the path of the desired member. If the archive is to be modified,
720  *      the mode should be "r+", if not, it should be "r".  arhPtr is a
721  *      poitner to the header structure to fill in.
722  *
723  * Results:
724  *      An FILE *, opened for reading and writing, positioned at the
725  *      start of the member's struct ar_hdr, or NULL if the member was
726  *      nonexistent. The current struct ar_hdr for member.
727  *
728  * Side Effects:
729  *      The passed struct ar_hdr structure is filled in.
730  *
731  *-----------------------------------------------------------------------
732  */
733 static FILE *
734 ArchFindMember(const char *archive, const char *member, struct ar_hdr *arhPtr, const char *mode)
735 {
736     FILE        *arch;  /* Stream to archive */
737     int         size;   /* Size of archive member */
738     const char  *cp;    /* Useful character pointer */
739     char        magic[SARMAG];
740     size_t      len, tlen;
741
742     arch = fopen(archive, mode);
743     if (arch == NULL) {
744         return (NULL);
745     }
746
747     /*
748      * We use the ARMAG string to make sure this is an archive we
749      * can handle...
750      */
751     if ((fread(magic, SARMAG, 1, arch) != 1) ||
752         (strncmp(magic, ARMAG, SARMAG) != 0)) {
753             fclose(arch);
754             return (NULL);
755     }
756
757     /*
758      * Because of space constraints and similar things, files are archived
759      * using their final path components, not the entire thing, so we need
760      * to point 'member' to the final component, if there is one, to make
761      * the comparisons easier...
762      */
763     cp = strrchr(member, '/');
764     if ((cp != NULL) && (strcmp(member, RANLIBMAG) != 0)) {
765         member = cp + 1;
766     }
767     len = tlen = strlen(member);
768     if (len > sizeof(arhPtr->ar_name)) {
769         tlen = sizeof(arhPtr->ar_name);
770     }
771
772     while (fread(arhPtr, sizeof(struct ar_hdr), 1, arch) == 1) {
773         if (strncmp(arhPtr->ar_fmag, ARFMAG, sizeof(arhPtr->ar_fmag) ) != 0) {
774              /*
775               * The header is bogus, so the archive is bad
776               * and there's no way we can recover...
777               */
778              fclose(arch);
779              return (NULL);
780         } else if (strncmp(member, arhPtr->ar_name, tlen) == 0) {
781             /*
782              * If the member's name doesn't take up the entire 'name' field,
783              * we have to be careful of matching prefixes. Names are space-
784              * padded to the right, so if the character in 'name' at the end
785              * of the matched string is anything but a space, this isn't the
786              * member we sought.
787              */
788             if (tlen != sizeof(arhPtr->ar_name) && arhPtr->ar_name[tlen] != ' '){
789                 goto skip;
790             } else {
791                 /*
792                  * To make life easier, we reposition the file at the start
793                  * of the header we just read before we return the stream.
794                  * In a more general situation, it might be better to leave
795                  * the file at the actual member, rather than its header, but
796                  * not here...
797                  */
798                 fseek(arch, -sizeof(struct ar_hdr), SEEK_CUR);
799                 return (arch);
800             }
801         } else
802 #ifdef AR_EFMT1
803                 /*
804                  * BSD 4.4 extended AR format: #1/<namelen>, with name as the
805                  * first <namelen> bytes of the file
806                  */
807             if (strncmp(arhPtr->ar_name, AR_EFMT1,
808                                         sizeof(AR_EFMT1) - 1) == 0 &&
809                 isdigit(arhPtr->ar_name[sizeof(AR_EFMT1) - 1])) {
810
811                 unsigned int elen = atoi(&arhPtr->ar_name[sizeof(AR_EFMT1)-1]);
812                 char ename[MAXPATHLEN];
813
814                 if (elen > MAXPATHLEN) {
815                         fclose(arch);
816                         return NULL;
817                 }
818                 if (fread(ename, elen, 1, arch) != 1) {
819                         fclose(arch);
820                         return NULL;
821                 }
822                 ename[elen] = '\0';
823                 /*
824                  * XXX choose one.
825                  */
826                 if (DEBUG(ARCH) || DEBUG(MAKE)) {
827                     printf("ArchFind: Extended format entry for %s\n", ename);
828                 }
829                 if (strncmp(ename, member, len) == 0) {
830                         /* Found as extended name */
831                         fseek(arch, -sizeof(struct ar_hdr) - elen, SEEK_CUR);
832                         return (arch);
833                 }
834                 fseek(arch, -elen, SEEK_CUR);
835                 goto skip;
836         } else
837 #endif
838         {
839 skip:
840             /*
841              * This isn't the member we're after, so we need to advance the
842              * stream's pointer to the start of the next header. Files are
843              * padded with newlines to an even-byte boundary, so we need to
844              * extract the size of the file from the 'size' field of the
845              * header and round it up during the seek.
846              */
847             arhPtr->ar_size[sizeof(arhPtr->ar_size) - 1] = '\0';
848             size = (int)strtol(arhPtr->ar_size, NULL, 10);
849             fseek(arch, (size + 1) & ~1, SEEK_CUR);
850         }
851     }
852
853     /*
854      * We've looked everywhere, but the member is not to be found. Close the
855      * archive and return NULL -- an error.
856      */
857     fclose(arch);
858     return (NULL);
859 }
860
861 /*-
862  *-----------------------------------------------------------------------
863  * Arch_Touch --
864  *      Touch a member of an archive.
865  *
866  * Results:
867  *      The 'time' field of the member's header is updated.
868  *
869  * Side Effects:
870  *      The modification time of the entire archive is also changed.
871  *      For a library, this could necessitate the re-ranlib'ing of the
872  *      whole thing.
873  *
874  *-----------------------------------------------------------------------
875  */
876 void
877 Arch_Touch(GNode *gn)
878 {
879     FILE *        arch;   /* Stream open to archive, positioned properly */
880     struct ar_hdr arh;    /* Current header describing member */
881     char *p1, *p2;
882
883     arch = ArchFindMember(Var_Value(ARCHIVE, gn, &p1),
884                           Var_Value(TARGET, gn, &p2),
885                           &arh, "r+");
886     free(p1);
887     free(p2);
888     snprintf(arh.ar_date, sizeof(arh.ar_date), "%-12ld", (long)now);
889
890     if (arch != NULL) {
891         fwrite(&arh, sizeof(struct ar_hdr), 1, arch);
892         fclose(arch);
893     }
894 }
895
896 /*-
897  *-----------------------------------------------------------------------
898  * Arch_TouchLib --
899  *      Given a node which represents a library, touch the thing, making
900  *      sure that the table of contents also is touched.
901  *
902  * Results:
903  *      None.
904  *
905  * Side Effects:
906  *      Both the modification time of the library and of the RANLIBMAG
907  *      member are set to 'now'.
908  *
909  *-----------------------------------------------------------------------
910  */
911 void
912 Arch_TouchLib(GNode *gn)
913 {
914 #ifdef RANLIBMAG
915     FILE                *arch;  /* Stream open to archive */
916     struct ar_hdr       arh;    /* Header describing table of contents */
917     struct utimbuf      times;  /* Times for utime() call */
918
919     arch = ArchFindMember(gn->path, RANLIBMAG, &arh, "r+");
920     snprintf(arh.ar_date, sizeof(arh.ar_date), "%-12ld", (long) now);
921
922     if (arch != NULL) {
923         fwrite(&arh, sizeof(struct ar_hdr), 1, arch);
924         fclose(arch);
925
926         times.actime = times.modtime = now;
927         utime(gn->path, &times);
928     }
929 #endif
930 }
931
932 /*-
933  *-----------------------------------------------------------------------
934  * Arch_MTime --
935  *      Return the modification time of a member of an archive, given its
936  *      name.
937  *
938  * Results:
939  *      The modification time(seconds).
940  *
941  * Side Effects:
942  *      The mtime field of the given node is filled in with the value
943  *      returned by the function.
944  *
945  *-----------------------------------------------------------------------
946  */
947 int
948 Arch_MTime(GNode *gn)
949 {
950     struct ar_hdr *arhPtr;    /* Header of desired member */
951     int           modTime;    /* Modification time as an integer */
952     char *p1, *p2;
953
954     arhPtr = ArchStatMember(Var_Value(ARCHIVE, gn, &p1),
955                              Var_Value(TARGET, gn, &p2),
956                              TRUE);
957     free(p1);
958     free(p2);
959
960     if (arhPtr != NULL) {
961         modTime = (int)strtol(arhPtr->ar_date, NULL, 10);
962     } else {
963         modTime = 0;
964     }
965
966     gn->mtime = modTime;
967     return (modTime);
968 }
969
970 /*-
971  *-----------------------------------------------------------------------
972  * Arch_MemMTime --
973  *      Given a non-existent archive member's node, get its modification
974  *      time from its archived form, if it exists.
975  *
976  * Results:
977  *      The modification time.
978  *
979  * Side Effects:
980  *      The mtime field is filled in.
981  *
982  *-----------------------------------------------------------------------
983  */
984 int
985 Arch_MemMTime(GNode *gn)
986 {
987     LstNode     *ln;
988     GNode       *pgn;
989     char        *nameStart;
990     char        *nameEnd;
991
992     for (ln = Lst_First(&gn->parents); ln != NULL; ln = Lst_Succ(ln)) {
993         pgn = Lst_Datum(ln);
994
995         if (pgn->type & OP_ARCHV) {
996             /*
997              * If the parent is an archive specification and is being made
998              * and its member's name matches the name of the node we were
999              * given, record the modification time of the parent in the
1000              * child. We keep searching its parents in case some other
1001              * parent requires this child to exist...
1002              */
1003             nameStart = strchr(pgn->name, '(') + 1;
1004             nameEnd = strchr(nameStart, ')');
1005
1006             if (pgn->make &&
1007                 strncmp(nameStart, gn->name, nameEnd - nameStart) == 0) {
1008                                      gn->mtime = Arch_MTime(pgn);
1009             }
1010         } else if (pgn->make) {
1011             /*
1012              * Something which isn't a library depends on the existence of
1013              * this target, so it needs to exist.
1014              */
1015             gn->mtime = 0;
1016             break;
1017         }
1018     }
1019     return (gn->mtime);
1020 }
1021
1022 /*-
1023  *-----------------------------------------------------------------------
1024  * Arch_FindLib --
1025  *      Search for a named library along the given search path.
1026  *
1027  * Results:
1028  *      None.
1029  *
1030  * Side Effects:
1031  *      The node's 'path' field is set to the found path (including the
1032  *      actual file name, not -l...). If the system can handle the -L
1033  *      flag when linking (or we cannot find the library), we assume that
1034  *      the user has placed the .LIBRARIES variable in the final linking
1035  *      command (or the linker will know where to find it) and set the
1036  *      TARGET variable for this node to be the node's name. Otherwise,
1037  *      we set the TARGET variable to be the full path of the library,
1038  *      as returned by Dir_FindFile.
1039  *
1040  *-----------------------------------------------------------------------
1041  */
1042 void
1043 Arch_FindLib(GNode *gn, Lst *path)
1044 {
1045     char            *libName;   /* file name for archive */
1046     size_t          sz;
1047
1048     sz = strlen(gn->name) + 4;
1049     libName = emalloc(sz);
1050     snprintf(libName, sz, "lib%s.a", &gn->name[2]);
1051
1052     gn->path = Dir_FindFile(libName, path);
1053
1054     free(libName);
1055
1056 #ifdef LIBRARIES
1057     Var_Set(TARGET, gn->name, gn);
1058 #else
1059     Var_Set(TARGET, gn->path == NULL ? gn->name : gn->path, gn);
1060 #endif /* LIBRARIES */
1061 }
1062
1063 /*-
1064  *-----------------------------------------------------------------------
1065  * Arch_LibOODate --
1066  *      Decide if a node with the OP_LIB attribute is out-of-date. Called
1067  *      from Make_OODate to make its life easier, with the library's
1068  *      graph node.
1069  *
1070  *      There are several ways for a library to be out-of-date that are
1071  *      not available to ordinary files. In addition, there are ways
1072  *      that are open to regular files that are not available to
1073  *      libraries. A library that is only used as a source is never
1074  *      considered out-of-date by itself. This does not preclude the
1075  *      library's modification time from making its parent be out-of-date.
1076  *      A library will be considered out-of-date for any of these reasons,
1077  *      given that it is a target on a dependency line somewhere:
1078  *          Its modification time is less than that of one of its
1079  *                sources (gn->mtime < gn->cmtime).
1080  *          Its modification time is greater than the time at which the
1081  *                make began (i.e. it's been modified in the course
1082  *                of the make, probably by archiving).
1083  *          The modification time of one of its sources is greater than
1084  *                the one of its RANLIBMAG member (i.e. its table of contents
1085  *                is out-of-date). We don't compare of the archive time
1086  *                vs. TOC time because they can be too close. In my
1087  *                opinion we should not bother with the TOC at all since
1088  *                this is used by 'ar' rules that affect the data contents
1089  *                of the archive, not by ranlib rules, which affect the
1090  *                TOC.
1091  *
1092  * Results:
1093  *      TRUE if the library is out-of-date. FALSE otherwise.
1094  *
1095  * Side Effects:
1096  *      The library will be hashed if it hasn't been already.
1097  *
1098  *-----------------------------------------------------------------------
1099  */
1100 Boolean
1101 Arch_LibOODate(GNode *gn)
1102 {
1103     Boolean       oodate;
1104
1105     if (OP_NOP(gn->type) && Lst_IsEmpty(&gn->children)) {
1106         oodate = FALSE;
1107     } else if ((gn->mtime > now) || (gn->mtime < gn->cmtime)) {
1108         oodate = TRUE;
1109     } else {
1110 #ifdef RANLIBMAG
1111         struct ar_hdr   *arhPtr;        /* Header for __.SYMDEF */
1112         int             modTimeTOC;     /* The table-of-contents's mod time */
1113
1114         arhPtr = ArchStatMember(gn->path, RANLIBMAG, FALSE);
1115
1116         if (arhPtr != NULL) {
1117             modTimeTOC = (int)strtol(arhPtr->ar_date, NULL, 10);
1118
1119             /* XXX choose one. */
1120             if (DEBUG(ARCH) || DEBUG(MAKE)) {
1121                 printf("%s modified %s...", RANLIBMAG, Targ_FmtTime(modTimeTOC));
1122             }
1123             oodate = (gn->cmtime > modTimeTOC);
1124         } else {
1125             /*
1126              * A library w/o a table of contents is out-of-date
1127              */
1128             if (DEBUG(ARCH) || DEBUG(MAKE)) {
1129                 printf("No t.o.c....");
1130             }
1131             oodate = TRUE;
1132         }
1133 #else
1134         oodate = (gn->mtime == 0); /* out-of-date if not present */
1135 #endif
1136     }
1137     return (oodate);
1138 }
1139
1140 /*-
1141  *-----------------------------------------------------------------------
1142  * Arch_Init --
1143  *      Initialize things for this module.
1144  *
1145  * Results:
1146  *      None.
1147  *
1148  *-----------------------------------------------------------------------
1149  */
1150 void
1151 Arch_Init(void)
1152 {
1153 }