]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/ar/write.c
MFC r342575, r342580: ar: detect and error out on 32-bit symbol table overflow
[FreeBSD/FreeBSD.git] / usr.bin / ar / write.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2007 Kai Wang
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer
12  *    in this position and unchanged.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31
32 #include <sys/endian.h>
33 #include <sys/mman.h>
34 #include <sys/queue.h>
35 #include <sys/stat.h>
36 #include <archive.h>
37 #include <archive_entry.h>
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <gelf.h>
41 #include <libgen.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <sysexits.h>
46 #include <unistd.h>
47
48 #include "ar.h"
49
50 #define _ARMAG_LEN 8            /* length of ar magic string */
51 #define _ARHDR_LEN 60           /* length of ar header */
52 #define _INIT_AS_CAP 128        /* initial archive string table size */
53 #define _INIT_SYMOFF_CAP (256*(sizeof(uint32_t))) /* initial so table size */
54 #define _INIT_SYMNAME_CAP 1024                    /* initial sn table size */
55 #define _MAXNAMELEN_SVR4 15     /* max member name length in svr4 variant */
56 #define _TRUNCATE_LEN 15        /* number of bytes to keep for member name */
57
58 static void     add_to_ar_str_table(struct bsdar *bsdar, const char *name);
59 static void     add_to_ar_sym_table(struct bsdar *bsdar, const char *name);
60 static struct ar_obj    *create_obj_from_file(struct bsdar *bsdar,
61                     const char *name, time_t mtime);
62 static void     create_symtab_entry(struct bsdar *bsdar, void *maddr,
63                     size_t size);
64 static void     free_obj(struct bsdar *bsdar, struct ar_obj *obj);
65 static void     insert_obj(struct bsdar *bsdar, struct ar_obj *obj,
66                     struct ar_obj *pos);
67 static void     prefault_buffer(const char *buf, size_t s);
68 static void     read_objs(struct bsdar *bsdar, const char *archive,
69                     int checkargv);
70 static void     write_archive(struct bsdar *bsdar, char mode);
71 static void     write_cleanup(struct bsdar *bsdar);
72 static void     write_data(struct bsdar *bsdar, struct archive *a,
73                     const void *buf, size_t s);
74 static void     write_objs(struct bsdar *bsdar);
75
76 void
77 ar_mode_d(struct bsdar *bsdar)
78 {
79
80         write_archive(bsdar, 'd');
81 }
82
83 void
84 ar_mode_m(struct bsdar *bsdar)
85 {
86
87         write_archive(bsdar, 'm');
88 }
89
90 void
91 ar_mode_q(struct bsdar *bsdar)
92 {
93
94         write_archive(bsdar, 'q');
95 }
96
97 void
98 ar_mode_r(struct bsdar *bsdar)
99 {
100
101         write_archive(bsdar, 'r');
102 }
103
104 void
105 ar_mode_s(struct bsdar *bsdar)
106 {
107
108         write_archive(bsdar, 's');
109 }
110
111 void
112 ar_mode_A(struct bsdar *bsdar)
113 {
114
115         write_archive(bsdar, 'A');
116 }
117
118 /*
119  * Create object from file, return created obj upon success, or NULL
120  * when an error occurs or the member is not newer than existing
121  * one while -u is specified.
122  */
123 static struct ar_obj *
124 create_obj_from_file(struct bsdar *bsdar, const char *name, time_t mtime)
125 {
126         struct ar_obj           *obj;
127         struct stat              sb;
128         const char              *bname;
129         char                    *tmpname;
130
131         if (name == NULL)
132                 return (NULL);
133
134         obj = malloc(sizeof(struct ar_obj));
135         if (obj == NULL)
136                 bsdar_errc(bsdar, EX_SOFTWARE, errno, "malloc failed");
137         if ((obj->fd = open(name, O_RDONLY, 0)) < 0) {
138                 bsdar_warnc(bsdar, errno, "can't open file: %s", name);
139                 free(obj);
140                 return (NULL);
141         }
142
143         tmpname = strdup(name);
144         if (tmpname == NULL)
145                 bsdar_errc(bsdar, EX_SOFTWARE, errno, "strdup failed");
146         if ((bname = basename(tmpname)) == NULL)
147                 bsdar_errc(bsdar, EX_SOFTWARE, errno, "basename failed");
148         if (bsdar->options & AR_TR && strlen(bname) > _TRUNCATE_LEN) {
149                 if ((obj->name = malloc(_TRUNCATE_LEN + 1)) == NULL)
150                         bsdar_errc(bsdar, EX_SOFTWARE, errno, "malloc failed");
151                 (void)strncpy(obj->name, bname, _TRUNCATE_LEN);
152                 obj->name[_TRUNCATE_LEN] = '\0';
153         } else
154                 if ((obj->name = strdup(bname)) == NULL)
155                     bsdar_errc(bsdar, EX_SOFTWARE, errno, "strdup failed");
156         free(tmpname);
157
158         if (fstat(obj->fd, &sb) < 0) {
159                 bsdar_warnc(bsdar, errno, "can't fstat file: %s", obj->name);
160                 goto giveup;
161         }
162         if (!S_ISREG(sb.st_mode)) {
163                 bsdar_warnc(bsdar, 0, "%s is not an ordinary file", obj->name);
164                 goto giveup;
165         }
166
167         /*
168          * When option '-u' is specified and member is not newer than the
169          * existing one, the replace will not happen. While if mtime == 0,
170          * which indicates that this is to "replace a none exist member",
171          * the replace will proceed regardless of '-u'.
172          */
173         if (mtime != 0 && bsdar->options & AR_U && sb.st_mtime <= mtime)
174                 goto giveup;
175
176         /*
177          * When option '-D' is specified, mtime and UID / GID from the file
178          * will be replaced with 0, and file mode with 644. This ensures that 
179          * checksums will match for two archives containing the exact same
180          * files.
181          */
182         if (bsdar->options & AR_D) {
183                 obj->uid = 0;
184                 obj->gid = 0;
185                 obj->mtime = 0;
186                 obj->md = S_IFREG | 0644;
187         } else {
188                 obj->uid = sb.st_uid;
189                 obj->gid = sb.st_gid;
190                 obj->mtime = sb.st_mtime;
191                 obj->md = sb.st_mode;
192         }
193         obj->size = sb.st_size;
194         obj->dev = sb.st_dev;
195         obj->ino = sb.st_ino;
196
197         if (obj->size == 0) {
198                 obj->maddr = NULL;
199                 return (obj);
200         }
201
202         if ((obj->maddr = mmap(NULL, obj->size, PROT_READ,
203             MAP_PRIVATE, obj->fd, (off_t)0)) == MAP_FAILED) {
204                 bsdar_warnc(bsdar, errno, "can't mmap file: %s", obj->name);
205                 goto giveup;
206         }
207         if (close(obj->fd) < 0)
208                 bsdar_errc(bsdar, EX_SOFTWARE, errno, "close failed: %s",
209                     obj->name);
210
211         return (obj);
212
213 giveup:
214         if (close(obj->fd) < 0)
215                 bsdar_errc(bsdar, EX_SOFTWARE, errno, "close failed: %s",
216                     obj->name);
217         free(obj->name);
218         free(obj);
219         return (NULL);
220 }
221
222 /*
223  * Free object itself and its associated allocations.
224  */
225 static void
226 free_obj(struct bsdar *bsdar, struct ar_obj *obj)
227 {
228         if (obj->fd == -1)
229                 free(obj->maddr);
230         else
231                 if (obj->maddr != NULL && munmap(obj->maddr, obj->size))
232                         bsdar_warnc(bsdar, errno,
233                             "can't munmap file: %s", obj->name);
234         free(obj->name);
235         free(obj);
236 }
237
238 /*
239  * Insert obj to the tail, or before/after the pos obj.
240  */
241 static void
242 insert_obj(struct bsdar *bsdar, struct ar_obj *obj, struct ar_obj *pos)
243 {
244         if (obj == NULL)
245                 bsdar_errc(bsdar, EX_SOFTWARE, 0, "try to insert a null obj");
246
247         if (pos == NULL || obj == pos)
248                 /*
249                  * If the object to move happens to be the position obj,
250                  * or if there is not a pos obj, move it to tail.
251                  */
252                 goto tail;
253
254         if (bsdar->options & AR_B) {
255                 TAILQ_INSERT_BEFORE(pos, obj, objs);
256                 return;
257         }
258         if (bsdar->options & AR_A) {
259                 TAILQ_INSERT_AFTER(&bsdar->v_obj, pos, obj, objs);
260                 return;
261         }
262
263 tail:
264         TAILQ_INSERT_TAIL(&bsdar->v_obj, obj, objs);
265
266 }
267
268 /*
269  * Read objects from archive into v_obj list. Note that checkargv is
270  * set when read_objs is used to read objects from the target of
271  * ADDLIB command (ar script mode), in this case argv array possibly
272  * specifies the members ADDLIB want.
273  */
274 static void
275 read_objs(struct bsdar *bsdar, const char *archive, int checkargv)
276 {
277         struct archive           *a;
278         struct archive_entry     *entry;
279         struct ar_obj            *obj;
280         const char               *name;
281         const char               *bname;
282         char                     *buff;
283         char                    **av;
284         size_t                    size;
285         int                       i, r, find;
286
287         if ((a = archive_read_new()) == NULL)
288                 bsdar_errc(bsdar, EX_SOFTWARE, 0, "archive_read_new failed");
289         archive_read_support_format_ar(a);
290         AC(archive_read_open_filename(a, archive, DEF_BLKSZ));
291         for (;;) {
292                 r = archive_read_next_header(a, &entry);
293                 if (r == ARCHIVE_FATAL)
294                         bsdar_errc(bsdar, EX_DATAERR, 0, "%s",
295                             archive_error_string(a));
296                 if (r == ARCHIVE_EOF)
297                         break;
298                 if (r == ARCHIVE_WARN || r == ARCHIVE_RETRY)
299                         bsdar_warnc(bsdar, 0, "%s", archive_error_string(a));
300                 if (r == ARCHIVE_RETRY) {
301                         bsdar_warnc(bsdar, 0, "Retrying...");
302                         continue;
303                 }
304
305                 name = archive_entry_pathname(entry);
306
307                 /*
308                  * skip pseudo members.
309                  */
310                 if (strcmp(name, "/") == 0 || strcmp(name, "//") == 0)
311                         continue;
312
313                 /*
314                  * If checkargv is set, only read those members specified
315                  * in argv.
316                  */
317                 if (checkargv && bsdar->argc > 0) {
318                         find = 0;
319                         for(i = 0; i < bsdar->argc; i++) {
320                                 av = &bsdar->argv[i];
321                                 if (*av == NULL)
322                                         continue;
323                                 if ((bname = basename(*av)) == NULL)
324                                         bsdar_errc(bsdar, EX_SOFTWARE, errno,
325                                             "basename failed");
326                                 if (strcmp(bname, name) != 0)
327                                         continue;
328
329                                 *av = NULL;
330                                 find = 1;
331                                 break;
332                         }
333                         if (!find)
334                                 continue;
335                 }
336
337                 size = archive_entry_size(entry);
338
339                 if (size > 0) {
340                         if ((buff = malloc(size)) == NULL)
341                                 bsdar_errc(bsdar, EX_SOFTWARE, errno,
342                                     "malloc failed");
343                         if (archive_read_data(a, buff, size) != (ssize_t)size) {
344                                 bsdar_warnc(bsdar, 0, "%s",
345                                     archive_error_string(a));
346                                 free(buff);
347                                 continue;
348                         }
349                 } else
350                         buff = NULL;
351
352                 obj = malloc(sizeof(struct ar_obj));
353                 if (obj == NULL)
354                         bsdar_errc(bsdar, EX_SOFTWARE, errno, "malloc failed");
355                 obj->maddr = buff;
356                 if ((obj->name = strdup(name)) == NULL)
357                         bsdar_errc(bsdar, EX_SOFTWARE, errno, "strdup failed");
358                 obj->size = size;
359                 obj->uid = archive_entry_uid(entry);
360                 obj->gid = archive_entry_gid(entry);
361                 obj->md = archive_entry_mode(entry);
362                 obj->mtime = archive_entry_mtime(entry);
363                 obj->dev = 0;
364                 obj->ino = 0;
365
366                 /*
367                  * Objects from archive have obj->fd set to -1,
368                  * for the ease of cleaning up.
369                  */
370                 obj->fd = -1;
371                 TAILQ_INSERT_TAIL(&bsdar->v_obj, obj, objs);
372         }
373         AC(archive_read_close(a));
374         AC(archive_read_free(a));
375 }
376
377 /*
378  * Determine the constitution of resulting archive.
379  */
380 static void
381 write_archive(struct bsdar *bsdar, char mode)
382 {
383         struct ar_obj            *nobj, *obj, *obj_temp, *pos;
384         struct stat               sb;
385         const char               *bname;
386         char                    **av;
387         int                       i;
388
389         TAILQ_INIT(&bsdar->v_obj);
390         nobj = NULL;
391         pos = NULL;
392         memset(&sb, 0, sizeof(sb));
393
394         /*
395          * Test if the specified archive exists, to figure out
396          * whether we are creating one here.
397          */
398         if (stat(bsdar->filename, &sb) != 0) {
399                 if (errno != ENOENT) {
400                         bsdar_warnc(bsdar, 0, "stat %s failed",
401                             bsdar->filename);
402                         return;
403                 }
404
405                 /* We do not create archive in mode 'd', 'm' and 's'.  */
406                 if (mode != 'r' && mode != 'q') {
407                         bsdar_warnc(bsdar, 0, "%s: no such file",
408                             bsdar->filename);
409                         return;
410                 }
411
412                 /* Issue a warning if -c is not specified when creating. */
413                 if (!(bsdar->options & AR_C))
414                         bsdar_warnc(bsdar, 0, "creating %s", bsdar->filename);
415                 goto new_archive;
416         }
417
418         /*
419          * First read members from existing archive.
420          */
421         read_objs(bsdar, bsdar->filename, 0);
422
423         /*
424          * For mode 's', no member will be moved, deleted or replaced.
425          */
426         if (mode == 's')
427                 goto write_objs;
428
429         /*
430          * For mode 'q', we don't need to adjust existing members either.
431          * Also, -a, -b and -i are ignored in this mode. New members are
432          * always inserted at tail.
433          */
434         if (mode == 'q')
435                 goto new_archive;
436
437         /*
438          * Mode 'A' adds the contents of another archive to the tail of
439          * current archive. Note that mode 'A' is a special mode for the
440          * ADDLIB command of the ar script mode. Currently there is no
441          * access to this function from the ar command line mode.
442          */
443         if (mode == 'A') {
444                 /*
445                  * Read objects from the target archive of ADDLIB command.
446                  * If there are members specified in argv, read those members
447                  * only, otherwise the entire archive will be read.
448                  */
449                 read_objs(bsdar, bsdar->addlib, 1);
450                 goto write_objs;
451         }
452
453         /*
454          * Try to find the position member specified by user.
455          */
456         if (bsdar->options & AR_A || bsdar->options & AR_B) {
457                 TAILQ_FOREACH(obj, &bsdar->v_obj, objs) {
458                         if (strcmp(obj->name, bsdar->posarg) == 0) {
459                                 pos = obj;
460                                 break;
461                         }
462                 }
463
464                 /*
465                  * If can't find `pos' specified by user,
466                  * silently insert objects at tail.
467                  */
468                 if (pos == NULL)
469                         bsdar->options &= ~(AR_A | AR_B);
470         }
471
472         for (i = 0; i < bsdar->argc; i++) {
473                 av = &bsdar->argv[i];
474
475                 TAILQ_FOREACH_SAFE(obj, &bsdar->v_obj, objs, obj_temp) {
476                         if ((bname = basename(*av)) == NULL)
477                                 bsdar_errc(bsdar, EX_SOFTWARE, errno,
478                                     "basename failed");
479                         if (bsdar->options & AR_TR) {
480                                 if (strncmp(bname, obj->name, _TRUNCATE_LEN))
481                                         continue;
482                         } else
483                                 if (strcmp(bname, obj->name) != 0)
484                                         continue;
485
486                         if (mode == 'r') {
487                                 /*
488                                  * if the new member is not qualified
489                                  * to replace the old one, skip it.
490                                  */
491                                 nobj = create_obj_from_file(bsdar, *av,
492                                     obj->mtime);
493                                 if (nobj == NULL)
494                                         goto skip_obj;
495                         }
496
497                         if (bsdar->options & AR_V)
498                                 (void)fprintf(stdout, "%c - %s\n", mode,
499                                     *av);
500
501                         TAILQ_REMOVE(&bsdar->v_obj, obj, objs);
502                         if (mode == 'd' || mode == 'r')
503                                 free_obj(bsdar, obj);
504
505                         if (mode == 'm')
506                                 insert_obj(bsdar, obj, pos);
507                         if (mode == 'r')
508                                 insert_obj(bsdar, nobj, pos);
509
510                 skip_obj:
511                         *av = NULL;
512                         break;
513                 }
514
515         }
516
517 new_archive:
518         /*
519          * When operating in mode 'r', directly add those user specified
520          * objects which do not exist in current archive. When operating
521          * in mode 'q', all objects specified in command line args are
522          * appended to the archive, without comparing with existing ones.
523          */
524         for (i = 0; i < bsdar->argc; i++) {
525                 av = &bsdar->argv[i];
526                 if (*av != NULL && (mode == 'r' || mode == 'q')) {
527                         nobj = create_obj_from_file(bsdar, *av, 0);
528                         if (nobj != NULL)
529                                 insert_obj(bsdar, nobj, pos);
530                         if (bsdar->options & AR_V && nobj != NULL)
531                                 (void)fprintf(stdout, "a - %s\n", *av);
532                         *av = NULL;
533                 }
534         }
535
536 write_objs:
537         write_objs(bsdar);
538         write_cleanup(bsdar);
539 }
540
541 /*
542  * Memory cleaning up.
543  */
544 static void
545 write_cleanup(struct bsdar *bsdar)
546 {
547         struct ar_obj           *obj, *obj_temp;
548
549         TAILQ_FOREACH_SAFE(obj, &bsdar->v_obj, objs, obj_temp) {
550                 TAILQ_REMOVE(&bsdar->v_obj, obj, objs);
551                 free_obj(bsdar, obj);
552         }
553
554         free(bsdar->as);
555         free(bsdar->s_so);
556         free(bsdar->s_sn);
557         bsdar->as = NULL;
558         bsdar->s_so = NULL;
559         bsdar->s_sn = NULL;
560 }
561
562 /*
563  * Fault in the buffer prior to writing as a workaround for poor performance
564  * due to interaction with kernel fs deadlock avoidance code. See the comment
565  * above vn_io_fault_doio() in sys/kern/vfs_vnops.c for details of the issue.
566  */
567 static void
568 prefault_buffer(const char *buf, size_t s)
569 {
570         volatile const char *p;
571         size_t page_size;
572
573         if (s == 0)
574                 return;
575         page_size = sysconf(_SC_PAGESIZE);
576         for (p = buf; p < buf + s; p += page_size)
577                 *p;
578         /*
579          * Ensure we touch the last page as well, in case the buffer is not
580          * page-aligned.
581          */
582         *(volatile const char *)(buf + s - 1);
583 }
584
585 /*
586  * Wrapper for archive_write_data().
587  */
588 static void
589 write_data(struct bsdar *bsdar, struct archive *a, const void *buf, size_t s)
590 {
591         ssize_t written;
592
593         prefault_buffer(buf, s);
594         while (s > 0) {
595                 written = archive_write_data(a, buf, s);
596                 if (written < 0)
597                         bsdar_errc(bsdar, EX_SOFTWARE, 0, "%s",
598                             archive_error_string(a));
599                 buf = (const char *)buf + written;
600                 s -= written;
601         }
602 }
603
604 /*
605  * Write the resulting archive members.
606  */
607 static void
608 write_objs(struct bsdar *bsdar)
609 {
610         struct ar_obj           *obj;
611         struct archive          *a;
612         struct archive_entry    *entry;
613         size_t s_sz;            /* size of archive symbol table. */
614         size_t pm_sz;           /* size of pseudo members */
615         int                      i, nr;
616
617         if (elf_version(EV_CURRENT) == EV_NONE)
618                 bsdar_errc(bsdar, EX_SOFTWARE, 0,
619                     "ELF library initialization failed: %s", elf_errmsg(-1));
620
621         bsdar->rela_off = 0;
622
623         /* Create archive symbol table and archive string table, if need. */
624         TAILQ_FOREACH(obj, &bsdar->v_obj, objs) {
625                 if (!(bsdar->options & AR_SS) && obj->maddr != NULL)
626                         create_symtab_entry(bsdar, obj->maddr, obj->size);
627                 if (strlen(obj->name) > _MAXNAMELEN_SVR4)
628                         add_to_ar_str_table(bsdar, obj->name);
629                 bsdar->rela_off += _ARHDR_LEN + obj->size + obj->size % 2;
630                 if (bsdar->rela_off > UINT32_MAX)
631                         bsdar_errc(bsdar, EX_SOFTWARE, 0,
632                             "Symbol table offset overflow");
633         }
634
635         /*
636          * Pad the symbol name string table. It is treated specially because
637          * symbol name table should be padded by a '\0', not the common '\n'
638          * for other members. The size of sn table includes the pad bit.
639          */
640         if (bsdar->s_cnt != 0 && bsdar->s_sn_sz % 2 != 0)
641                 bsdar->s_sn[bsdar->s_sn_sz++] = '\0';
642
643         /*
644          * Archive string table is padded by a "\n" as the normal members.
645          * The difference is that the size of archive string table counts
646          * in the pad bit, while normal members' size fileds do not.
647          */
648         if (bsdar->as != NULL && bsdar->as_sz % 2 != 0)
649                 bsdar->as[bsdar->as_sz++] = '\n';
650
651         /*
652          * If there is a symbol table, calculate the size of pseudo members,
653          * convert previously stored relative offsets to absolute ones, and
654          * then make them Big Endian.
655          *
656          * absolute_offset = htobe32(relative_offset + size_of_pseudo_members)
657          */
658
659         if (bsdar->s_cnt != 0) {
660                 s_sz = (bsdar->s_cnt + 1) * sizeof(uint32_t) + bsdar->s_sn_sz;
661                 pm_sz = _ARMAG_LEN + (_ARHDR_LEN + s_sz);
662                 if (bsdar->as != NULL)
663                         pm_sz += _ARHDR_LEN + bsdar->as_sz;
664                 for (i = 0; (size_t)i < bsdar->s_cnt; i++) {
665                         if (*(bsdar->s_so + i) > UINT32_MAX - pm_sz)
666                                 bsdar_errc(bsdar, EX_SOFTWARE, 0,
667                                     "Symbol table offset overflow");
668                         *(bsdar->s_so + i) = htobe32(*(bsdar->s_so + i) +
669                             pm_sz);
670                 }
671         }
672
673         if ((a = archive_write_new()) == NULL)
674                 bsdar_errc(bsdar, EX_SOFTWARE, 0, "archive_write_new failed");
675
676         archive_write_set_format_ar_svr4(a);
677
678         AC(archive_write_open_filename(a, bsdar->filename));
679
680         /*
681          * write the archive symbol table, if there is one.
682          * If options -s is explicitly specified or we are invoked
683          * as ranlib, write the symbol table even if it is empty.
684          */
685         if ((bsdar->s_cnt != 0 && !(bsdar->options & AR_SS)) ||
686             bsdar->options & AR_S) {
687                 entry = archive_entry_new();
688                 if (entry == NULL)
689                         bsdar_errc(bsdar, EX_SOFTWARE, 0,
690                             "archive_entry_new failed");
691                 archive_entry_copy_pathname(entry, "/");
692                 if ((bsdar->options & AR_D) == 0)
693                         archive_entry_set_mtime(entry, time(NULL), 0);
694                 archive_entry_set_size(entry, (bsdar->s_cnt + 1) *
695                     sizeof(uint32_t) + bsdar->s_sn_sz);
696                 AC(archive_write_header(a, entry));
697                 nr = htobe32(bsdar->s_cnt);
698                 write_data(bsdar, a, &nr, sizeof(uint32_t));
699                 write_data(bsdar, a, bsdar->s_so, sizeof(uint32_t) *
700                     bsdar->s_cnt);
701                 write_data(bsdar, a, bsdar->s_sn, bsdar->s_sn_sz);
702                 archive_entry_free(entry);
703         }
704
705         /* write the archive string table, if any. */
706         if (bsdar->as != NULL) {
707                 entry = archive_entry_new();
708                 if (entry == NULL)
709                         bsdar_errc(bsdar, EX_SOFTWARE, 0,
710                             "archive_entry_new failed");
711                 archive_entry_copy_pathname(entry, "//");
712                 archive_entry_set_size(entry, bsdar->as_sz);
713                 AC(archive_write_header(a, entry));
714                 write_data(bsdar, a, bsdar->as, bsdar->as_sz);
715                 archive_entry_free(entry);
716         }
717
718         /* write normal members. */
719         TAILQ_FOREACH(obj, &bsdar->v_obj, objs) {
720                 entry = archive_entry_new();
721                 if (entry == NULL)
722                         bsdar_errc(bsdar, EX_SOFTWARE, 0,
723                             "archive_entry_new failed");
724                 archive_entry_copy_pathname(entry, obj->name);
725                 archive_entry_set_uid(entry, obj->uid);
726                 archive_entry_set_gid(entry, obj->gid);
727                 archive_entry_set_mode(entry, obj->md);
728                 archive_entry_set_size(entry, obj->size);
729                 archive_entry_set_mtime(entry, obj->mtime, 0);
730                 archive_entry_set_dev(entry, obj->dev);
731                 archive_entry_set_ino(entry, obj->ino);
732                 archive_entry_set_filetype(entry, AE_IFREG);
733                 AC(archive_write_header(a, entry));
734                 write_data(bsdar, a, obj->maddr, obj->size);
735                 archive_entry_free(entry);
736         }
737
738         AC(archive_write_close(a));
739         AC(archive_write_free(a));
740 }
741
742 /*
743  * Extract global symbols from ELF binary members.
744  */
745 static void
746 create_symtab_entry(struct bsdar *bsdar, void *maddr, size_t size)
747 {
748         Elf             *e;
749         Elf_Scn         *scn;
750         GElf_Shdr        shdr;
751         GElf_Sym         sym;
752         Elf_Data        *data;
753         char            *name;
754         size_t           n, shstrndx;
755         int              elferr, tabndx, len, i;
756
757         if ((e = elf_memory(maddr, size)) == NULL) {
758                 bsdar_warnc(bsdar, 0, "elf_memory() failed: %s",
759                      elf_errmsg(-1));
760                 return;
761         }
762         if (elf_kind(e) != ELF_K_ELF) {
763                 /* Silently ignore non-elf member. */
764                 elf_end(e);
765                 return;
766         }
767         if (elf_getshstrndx(e, &shstrndx) == 0) {
768                 bsdar_warnc(bsdar, EX_SOFTWARE, 0, "elf_getshstrndx failed: %s",
769                      elf_errmsg(-1));
770                 elf_end(e);
771                 return;
772         }
773
774         tabndx = -1;
775         scn = NULL;
776         while ((scn = elf_nextscn(e, scn)) != NULL) {
777                 if (gelf_getshdr(scn, &shdr) != &shdr) {
778                         bsdar_warnc(bsdar, 0,
779                             "elf_getshdr failed: %s", elf_errmsg(-1));
780                         continue;
781                 }
782                 if ((name = elf_strptr(e, shstrndx, shdr.sh_name)) == NULL) {
783                         bsdar_warnc(bsdar, 0,
784                             "elf_strptr failed: %s", elf_errmsg(-1));
785                         continue;
786                 }
787                 if (strcmp(name, ".strtab") == 0) {
788                         tabndx = elf_ndxscn(scn);
789                         break;
790                 }
791         }
792         elferr = elf_errno();
793         if (elferr != 0)
794                 bsdar_warnc(bsdar, 0, "elf_nextscn failed: %s",
795                      elf_errmsg(elferr));
796         if (tabndx == -1) {
797                 bsdar_warnc(bsdar, 0, "can't find .strtab section");
798                 elf_end(e);
799                 return;
800         }
801
802         scn = NULL;
803         while ((scn = elf_nextscn(e, scn)) != NULL) {
804                 if (gelf_getshdr(scn, &shdr) != &shdr) {
805                         bsdar_warnc(bsdar, EX_SOFTWARE, 0,
806                             "elf_getshdr failed: %s", elf_errmsg(-1));
807                         continue;
808                 }
809                 if (shdr.sh_type != SHT_SYMTAB)
810                         continue;
811
812                 data = NULL;
813                 n = 0;
814                 while (n < shdr.sh_size &&
815                     (data = elf_getdata(scn, data)) != NULL) {
816                         len = data->d_size / shdr.sh_entsize;
817                         for (i = 0; i < len; i++) {
818                                 if (gelf_getsym(data, i, &sym) != &sym) {
819                                         bsdar_warnc(bsdar, EX_SOFTWARE, 0,
820                                             "gelf_getsym failed: %s",
821                                              elf_errmsg(-1));
822                                         continue;
823                                 }
824
825                                 /* keep only global or weak symbols */
826                                 if (GELF_ST_BIND(sym.st_info) != STB_GLOBAL &&
827                                     GELF_ST_BIND(sym.st_info) != STB_WEAK)
828                                         continue;
829
830                                 /* keep only defined symbols */
831                                 if (sym.st_shndx == SHN_UNDEF)
832                                         continue;
833
834                                 if ((name = elf_strptr(e, tabndx,
835                                     sym.st_name)) == NULL) {
836                                         bsdar_warnc(bsdar, EX_SOFTWARE, 0,
837                                             "elf_strptr failed: %s",
838                                              elf_errmsg(-1));
839                                         continue;
840                                 }
841
842                                 add_to_ar_sym_table(bsdar, name);
843                         }
844                 }
845         }
846         elferr = elf_errno();
847         if (elferr != 0)
848                 bsdar_warnc(bsdar, EX_SOFTWARE, 0, "elf_nextscn failed: %s",
849                      elf_errmsg(elferr));
850
851         elf_end(e);
852 }
853
854 /*
855  * Append to the archive string table buffer.
856  */
857 static void
858 add_to_ar_str_table(struct bsdar *bsdar, const char *name)
859 {
860
861         if (bsdar->as == NULL) {
862                 bsdar->as_cap = _INIT_AS_CAP;
863                 bsdar->as_sz = 0;
864                 if ((bsdar->as = malloc(bsdar->as_cap)) == NULL)
865                         bsdar_errc(bsdar, EX_SOFTWARE, errno, "malloc failed");
866         }
867
868         /*
869          * The space required for holding one member name in as table includes:
870          * strlen(name) + (1 for '/') + (1 for '\n') + (possibly 1 for padding).
871          */
872         while (bsdar->as_sz + strlen(name) + 3 > bsdar->as_cap) {
873                 bsdar->as_cap *= 2;
874                 bsdar->as = realloc(bsdar->as, bsdar->as_cap);
875                 if (bsdar->as == NULL)
876                         bsdar_errc(bsdar, EX_SOFTWARE, errno, "realloc failed");
877         }
878         strncpy(&bsdar->as[bsdar->as_sz], name, strlen(name));
879         bsdar->as_sz += strlen(name);
880         bsdar->as[bsdar->as_sz++] = '/';
881         bsdar->as[bsdar->as_sz++] = '\n';
882 }
883
884 /*
885  * Append to the archive symbol table buffer.
886  */
887 static void
888 add_to_ar_sym_table(struct bsdar *bsdar, const char *name)
889 {
890
891         if (bsdar->s_so == NULL) {
892                 if ((bsdar->s_so = malloc(_INIT_SYMOFF_CAP)) ==
893                     NULL)
894                         bsdar_errc(bsdar, EX_SOFTWARE, errno, "malloc failed");
895                 bsdar->s_so_cap = _INIT_SYMOFF_CAP;
896                 bsdar->s_cnt = 0;
897         }
898
899         if (bsdar->s_sn == NULL) {
900                 if ((bsdar->s_sn = malloc(_INIT_SYMNAME_CAP)) == NULL)
901                         bsdar_errc(bsdar, EX_SOFTWARE, errno, "malloc failed");
902                 bsdar->s_sn_cap = _INIT_SYMNAME_CAP;
903                 bsdar->s_sn_sz = 0;
904         }
905
906         if (bsdar->s_cnt * sizeof(uint32_t) >= bsdar->s_so_cap) {
907                 bsdar->s_so_cap *= 2;
908                 bsdar->s_so = realloc(bsdar->s_so, bsdar->s_so_cap);
909                 if (bsdar->s_so == NULL)
910                         bsdar_errc(bsdar, EX_SOFTWARE, errno, "realloc failed");
911         }
912         bsdar->s_so[bsdar->s_cnt] = bsdar->rela_off;
913         bsdar->s_cnt++;
914
915         /*
916          * The space required for holding one symbol name in sn table includes:
917          * strlen(name) + (1 for '\n') + (possibly 1 for padding).
918          */
919         while (bsdar->s_sn_sz + strlen(name) + 2 > bsdar->s_sn_cap) {
920                 bsdar->s_sn_cap *= 2;
921                 bsdar->s_sn = realloc(bsdar->s_sn, bsdar->s_sn_cap);
922                 if (bsdar->s_sn == NULL)
923                         bsdar_errc(bsdar, EX_SOFTWARE, errno, "realloc failed");
924         }
925         strncpy(&bsdar->s_sn[bsdar->s_sn_sz], name, strlen(name));
926         bsdar->s_sn_sz += strlen(name);
927         bsdar->s_sn[bsdar->s_sn_sz++] = '\0';
928 }