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