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