Extract usage information into a separate file.
[oweals/busybox.git] / modutils / insmod.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini insmod implementation for busybox
4  *
5  * Copyright (C) 1999,2000 by Lineo, inc.
6  * Written by Erik Andersen <andersen@lineo.com>
7  * and Ron Alder <alder@lineo.com>
8  *
9  * Based almost entirely on the Linux modutils-2.3.11 implementation.
10  *   Copyright 1996, 1997 Linux International.
11  *   New implementation contributed by Richard Henderson <rth@tamu.edu>
12  *   Based on original work by Bjorn Ekwall <bj0rn@blox.se>
13  *   Restructured (and partly rewritten) by:
14  *   Björn Ekwall <bj0rn@blox.se> February 1999
15  *
16  * This program is free software; you can redistribute it and/or modify
17  * it under the terms of the GNU General Public License as published by
18  * the Free Software Foundation; either version 2 of the License, or
19  * (at your option) any later version.
20  *
21  * This program is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
24  * General Public License for more details.
25  *
26  * You should have received a copy of the GNU General Public License
27  * along with this program; if not, write to the Free Software
28  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
29  *
30  */
31
32 #include "internal.h"
33 #include <stdlib.h>
34 #include <stdio.h>
35 #include <stddef.h>
36 #include <errno.h>
37 #include <unistd.h>
38 #include <dirent.h>
39 #include <ctype.h>
40 #include <assert.h>
41 #include <getopt.h>
42 #include <sys/utsname.h>
43
44 //----------------------------------------------------------------------------
45 //--------modutils module.h, lines 45-242
46 //----------------------------------------------------------------------------
47
48 /* Definitions for the Linux module syscall interface.
49    Copyright 1996, 1997 Linux International.
50
51    Contributed by Richard Henderson <rth@tamu.edu>
52
53    This file is part of the Linux modutils.
54
55    This program is free software; you can redistribute it and/or modify it
56    under the terms of the GNU General Public License as published by the
57    Free Software Foundation; either version 2 of the License, or (at your
58    option) any later version.
59
60    This program is distributed in the hope that it will be useful, but
61    WITHOUT ANY WARRANTY; without even the implied warranty of
62    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
63    General Public License for more details.
64
65    You should have received a copy of the GNU General Public License
66    along with this program; if not, write to the Free Software Foundation,
67    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
68
69
70 #ifndef MODUTILS_MODULE_H
71 #define MODUTILS_MODULE_H 1
72
73 #ident "$Id: insmod.c,v 1.18 2000/07/16 20:57:15 kraai Exp $"
74
75 /* This file contains the structures used by the 2.0 and 2.1 kernels.
76    We do not use the kernel headers directly because we do not wish
77    to be dependant on a particular kernel version to compile insmod.  */
78
79
80 /*======================================================================*/
81 /* The structures used by Linux 2.0.  */
82
83 /* The symbol format used by get_kernel_syms(2).  */
84 struct old_kernel_sym
85 {
86   unsigned long value;
87   char name[60];
88 };
89
90 struct old_module_ref
91 {
92   unsigned long module;         /* kernel addresses */
93   unsigned long next;
94 };
95
96 struct old_module_symbol
97 {
98   unsigned long addr;
99   unsigned long name;
100 };
101
102 struct old_symbol_table
103 {
104   int size;                     /* total, including string table!!! */
105   int n_symbols;
106   int n_refs;
107   struct old_module_symbol symbol[0]; /* actual size defined by n_symbols */
108   struct old_module_ref ref[0]; /* actual size defined by n_refs */
109 };
110
111 struct old_mod_routines
112 {
113   unsigned long init;
114   unsigned long cleanup;
115 };
116
117 struct old_module
118 {
119   unsigned long next;
120   unsigned long ref;            /* the list of modules that refer to me */
121   unsigned long symtab;
122   unsigned long name;
123   int size;                     /* size of module in pages */
124   unsigned long addr;           /* address of module */
125   int state;
126   unsigned long cleanup;        /* cleanup routine */
127 };
128
129 /* Sent to init_module(2) or'ed into the code size parameter.  */
130 #define OLD_MOD_AUTOCLEAN 0x40000000 /* big enough, but no sign problems... */
131
132 int get_kernel_syms(struct old_kernel_sym *);
133 int old_sys_init_module(const char *name, char *code, unsigned codesize,
134                         struct old_mod_routines *, struct old_symbol_table *);
135
136 /*======================================================================*/
137 /* For sizeof() which are related to the module platform and not to the
138    environment isnmod is running in, use sizeof_xx instead of sizeof(xx).  */
139
140 #define tgt_sizeof_char         sizeof(char)
141 #define tgt_sizeof_short        sizeof(short)
142 #define tgt_sizeof_int          sizeof(int)
143 #define tgt_sizeof_long         sizeof(long)
144 #define tgt_sizeof_char_p       sizeof(char *)
145 #define tgt_sizeof_void_p       sizeof(void *)
146 #define tgt_long                long
147
148 #if defined(__sparc__) && !defined(__sparc_v9__) && defined(ARCH_sparc64)
149 #undef tgt_sizeof_long
150 #undef tgt_sizeof_char_p
151 #undef tgt_sizeof_void_p
152 #undef tgt_long
153 #define tgt_sizeof_long         8
154 #define tgt_sizeof_char_p       8
155 #define tgt_sizeof_void_p       8
156 #define tgt_long                long long
157 #endif
158
159 /*======================================================================*/
160 /* The structures used in Linux 2.1.  */
161
162 /* Note: new_module_symbol does not use tgt_long intentionally */
163 struct new_module_symbol
164 {
165   unsigned long value;
166   unsigned long name;
167 };
168
169 struct new_module_persist;
170
171 struct new_module_ref
172 {
173   unsigned tgt_long dep;                /* kernel addresses */
174   unsigned tgt_long ref;
175   unsigned tgt_long next_ref;
176 };
177
178 struct new_module
179 {
180   unsigned tgt_long size_of_struct;     /* == sizeof(module) */
181   unsigned tgt_long next;
182   unsigned tgt_long name;
183   unsigned tgt_long size;
184
185   tgt_long usecount;
186   unsigned tgt_long flags;              /* AUTOCLEAN et al */
187
188   unsigned nsyms;
189   unsigned ndeps;
190
191   unsigned tgt_long syms;
192   unsigned tgt_long deps;
193   unsigned tgt_long refs;
194   unsigned tgt_long init;
195   unsigned tgt_long cleanup;
196   unsigned tgt_long ex_table_start;
197   unsigned tgt_long ex_table_end;
198 #ifdef __alpha__
199   unsigned tgt_long gp;
200 #endif
201   /* Everything after here is extension.  */
202   unsigned tgt_long persist_start;
203   unsigned tgt_long persist_end;
204   unsigned tgt_long can_unload;
205   unsigned tgt_long runsize;
206 };
207
208 struct new_module_info
209 {
210   unsigned long addr;
211   unsigned long size;
212   unsigned long flags;
213            long usecount;
214 };
215
216 /* Bits of module.flags.  */
217 #define NEW_MOD_RUNNING         1
218 #define NEW_MOD_DELETED         2
219 #define NEW_MOD_AUTOCLEAN       4
220 #define NEW_MOD_VISITED         8
221 #define NEW_MOD_USED_ONCE       16
222
223 int new_sys_init_module(const char *name, const struct new_module *);
224 int query_module(const char *name, int which, void *buf, size_t bufsize,
225                  size_t *ret);
226
227 /* Values for query_module's which.  */
228
229 #define QM_MODULES      1
230 #define QM_DEPS         2
231 #define QM_REFS         3
232 #define QM_SYMBOLS      4
233 #define QM_INFO         5
234
235 /*======================================================================*/
236 /* The system calls unchanged between 2.0 and 2.1.  */
237
238 unsigned long create_module(const char *, size_t);
239 int delete_module(const char *);
240
241
242 #endif /* module.h */
243
244 //----------------------------------------------------------------------------
245 //--------end of modutils module.h
246 //----------------------------------------------------------------------------
247
248
249
250 //----------------------------------------------------------------------------
251 //--------modutils obj.h, lines 253-462
252 //----------------------------------------------------------------------------
253
254 /* Elf object file loading and relocation routines.
255    Copyright 1996, 1997 Linux International.
256
257    Contributed by Richard Henderson <rth@tamu.edu>
258
259    This file is part of the Linux modutils.
260
261    This program is free software; you can redistribute it and/or modify it
262    under the terms of the GNU General Public License as published by the
263    Free Software Foundation; either version 2 of the License, or (at your
264    option) any later version.
265
266    This program is distributed in the hope that it will be useful, but
267    WITHOUT ANY WARRANTY; without even the implied warranty of
268    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
269    General Public License for more details.
270
271    You should have received a copy of the GNU General Public License
272    along with this program; if not, write to the Free Software Foundation,
273    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
274
275
276 #ifndef MODUTILS_OBJ_H
277 #define MODUTILS_OBJ_H 1
278
279 #ident "$Id: insmod.c,v 1.18 2000/07/16 20:57:15 kraai Exp $"
280
281 /* The relocatable object is manipulated using elfin types.  */
282
283 #include <stdio.h>
284 #include <elf.h>
285
286
287 /* Machine-specific elf macros for i386 et al.  */
288
289 #define ELFCLASSM       ELFCLASS32
290 #define ELFDATAM        ELFDATA2LSB
291
292 #define MATCH_MACHINE(x)  (x == EM_386 || x == EM_486)
293
294 #define SHT_RELM        SHT_REL
295 #define Elf32_RelM      Elf32_Rel
296
297
298 #ifndef ElfW
299 # if ELFCLASSM == ELFCLASS32
300 #  define ElfW(x)  Elf32_ ## x
301 #  define ELFW(x)  ELF32_ ## x
302 # else
303 #  define ElfW(x)  Elf64_ ## x
304 #  define ELFW(x)  ELF64_ ## x
305 # endif
306 #endif
307
308 /* For some reason this is missing from libc5.  */
309 #ifndef ELF32_ST_INFO
310 # define ELF32_ST_INFO(bind, type)       (((bind) << 4) + ((type) & 0xf))
311 #endif
312
313 #ifndef ELF64_ST_INFO
314 # define ELF64_ST_INFO(bind, type)       (((bind) << 4) + ((type) & 0xf))
315 #endif
316
317 struct obj_string_patch;
318 struct obj_symbol_patch;
319
320 struct obj_section
321 {
322   ElfW(Shdr) header;
323   const char *name;
324   char *contents;
325   struct obj_section *load_next;
326   int idx;
327 };
328
329 struct obj_symbol
330 {
331   struct obj_symbol *next;      /* hash table link */
332   const char *name;
333   unsigned long value;
334   unsigned long size;
335   int secidx;                   /* the defining section index/module */
336   int info;
337   int ksymidx;                  /* for export to the kernel symtab */
338   int referenced;               /* actually used in the link */
339 };
340
341 /* Hardcode the hash table size.  We shouldn't be needing so many
342    symbols that we begin to degrade performance, and we get a big win
343    by giving the compiler a constant divisor.  */
344
345 #define HASH_BUCKETS  521
346
347 struct obj_file
348 {
349   ElfW(Ehdr) header;
350   ElfW(Addr) baseaddr;
351   struct obj_section **sections;
352   struct obj_section *load_order;
353   struct obj_section **load_order_search_start;
354   struct obj_string_patch *string_patches;
355   struct obj_symbol_patch *symbol_patches;
356   int (*symbol_cmp)(const char *, const char *);
357   unsigned long (*symbol_hash)(const char *);
358   unsigned long local_symtab_size;
359   struct obj_symbol **local_symtab;
360   struct obj_symbol *symtab[HASH_BUCKETS];
361 };
362
363 enum obj_reloc
364 {
365   obj_reloc_ok,
366   obj_reloc_overflow,
367   obj_reloc_dangerous,
368   obj_reloc_unhandled
369 };
370
371 struct obj_string_patch
372 {
373   struct obj_string_patch *next;
374   int reloc_secidx;
375   ElfW(Addr) reloc_offset;
376   ElfW(Addr) string_offset;
377 };
378
379 struct obj_symbol_patch
380 {
381   struct obj_symbol_patch *next;
382   int reloc_secidx;
383   ElfW(Addr) reloc_offset;
384   struct obj_symbol *sym;
385 };
386
387
388 /* Generic object manipulation routines.  */
389
390 unsigned long obj_elf_hash(const char *);
391
392 unsigned long obj_elf_hash_n(const char *, unsigned long len);
393
394 struct obj_symbol *obj_add_symbol (struct obj_file *f, const char *name,
395                                    unsigned long symidx, int info, int secidx,
396                                    ElfW(Addr) value, unsigned long size);
397
398 struct obj_symbol *obj_find_symbol (struct obj_file *f,
399                                          const char *name);
400
401 ElfW(Addr) obj_symbol_final_value(struct obj_file *f,
402                                   struct obj_symbol *sym);
403
404 void obj_set_symbol_compare(struct obj_file *f,
405                             int (*cmp)(const char *, const char *),
406                             unsigned long (*hash)(const char *));
407
408 struct obj_section *obj_find_section (struct obj_file *f,
409                                            const char *name);
410
411 void obj_insert_section_load_order (struct obj_file *f,
412                                     struct obj_section *sec);
413
414 struct obj_section *obj_create_alloced_section (struct obj_file *f,
415                                                 const char *name,
416                                                 unsigned long align,
417                                                 unsigned long size);
418
419 struct obj_section *obj_create_alloced_section_first (struct obj_file *f,
420                                                       const char *name,
421                                                       unsigned long align,
422                                                       unsigned long size);
423
424 void *obj_extend_section (struct obj_section *sec, unsigned long more);
425
426 int obj_string_patch(struct obj_file *f, int secidx, ElfW(Addr) offset,
427                      const char *string);
428
429 int obj_symbol_patch(struct obj_file *f, int secidx, ElfW(Addr) offset,
430                      struct obj_symbol *sym);
431
432 int obj_check_undefineds(struct obj_file *f);
433
434 void obj_allocate_commons(struct obj_file *f);
435
436 unsigned long obj_load_size (struct obj_file *f);
437
438 int obj_relocate (struct obj_file *f, ElfW(Addr) base);
439
440 struct obj_file *obj_load(FILE *f);
441
442 int obj_create_image (struct obj_file *f, char *image);
443
444 /* Architecture specific manipulation routines.  */
445
446 struct obj_file *arch_new_file (void);
447
448 struct obj_section *arch_new_section (void);
449
450 struct obj_symbol *arch_new_symbol (void);
451
452 enum obj_reloc arch_apply_relocation (struct obj_file *f,
453                                       struct obj_section *targsec,
454                                       struct obj_section *symsec,
455                                       struct obj_symbol *sym,
456                                       ElfW(RelM) *rel, ElfW(Addr) value);
457
458 int arch_create_got (struct obj_file *f);
459
460 struct new_module;
461 int arch_init_module (struct obj_file *f, struct new_module *);
462
463 #endif /* obj.h */
464 //----------------------------------------------------------------------------
465 //--------end of modutils obj.h
466 //----------------------------------------------------------------------------
467
468
469
470
471
472 #define _PATH_MODULES   "/lib/modules"
473 #define STRVERSIONLEN   32
474
475 #if !defined(BB_FEATURE_INSMOD_NEW_KERNEL) && !defined(BB_FEATURE_INSMOD_OLD_KERNEL)
476 #error "Must have ether BB_FEATURE_INSMOD_NEW_KERNEL or BB_FEATURE_INSMOD_OLD_KERNEL defined"
477 #endif
478
479 /*======================================================================*/
480
481 int flag_force_load = 0;
482 int flag_autoclean = 0;
483 int flag_verbose = 0;
484 int flag_export = 1;
485
486
487 /*======================================================================*/
488
489 struct i386_got_entry {
490         int offset;
491         unsigned offset_done:1;
492         unsigned reloc_done:1;
493 };
494
495 struct i386_file {
496         struct obj_file root;
497         struct obj_section *got;
498 };
499
500 struct i386_symbol {
501         struct obj_symbol root;
502         struct i386_got_entry gotent;
503 };
504
505
506
507 struct external_module {
508         const char *name;
509         ElfW(Addr) addr;
510         int used;
511         size_t nsyms;
512         struct new_module_symbol *syms;
513 };
514
515 struct new_module_symbol *ksyms;
516 size_t nksyms;
517
518 struct external_module *ext_modules;
519 int n_ext_modules;
520 int n_ext_modules_used;
521
522
523
524 /* Some firendly syscalls to cheer everyone's day...  */
525 #define __NR_new_sys_init_module  __NR_init_module
526 _syscall2(int, new_sys_init_module, const char *, name,
527                   const struct new_module *, info)
528 #define __NR_old_sys_init_module  __NR_init_module
529 _syscall5(int, old_sys_init_module, const char *, name, char *, code,
530                   unsigned, codesize, struct old_mod_routines *, routines,
531                   struct old_symbol_table *, symtab)
532 #ifndef __NR_query_module
533 #define __NR_query_module     167
534 #endif
535 _syscall5(int, query_module, const char *, name, int, which,
536                 void *, buf, size_t, bufsize, size_t*, ret);
537 #ifndef BB_RMMOD
538 _syscall1(int, delete_module, const char *, name)
539 #else
540 extern int delete_module(const char *);
541 #endif
542
543 #if defined(__i386__) || defined(__m68k__) || defined(__arm__)
544 /* Jump through hoops to fixup error return codes */
545 #define __NR__create_module  __NR_create_module
546 static inline _syscall2(long, _create_module, const char *, name, size_t,
547                                                 size)
548 unsigned long create_module(const char *name, size_t size)
549 {
550         long ret = _create_module(name, size);
551
552         if (ret == -1 && errno > 125) {
553                 ret = -errno;
554                 errno = 0;
555         }
556         return ret;
557 }
558 #else
559 _syscall2(unsigned long, create_module, const char *, name, size_t, size)
560 #endif
561 static char m_filename[BUFSIZ + 1] = "\0";
562 static char m_fullName[BUFSIZ + 1] = "\0";
563
564 /*======================================================================*/
565
566 void *xrealloc(void *old, size_t size)
567 {
568         void *ptr = realloc(old, size);
569         if (!ptr) {
570                 perror("Out of memory");
571                 exit(1);
572         }
573         return ptr;
574 }
575
576
577 static int findNamedModule(const char *fileName, struct stat *statbuf,
578                                                    void *userDate)
579 {
580         char *fullName = (char *) userDate;
581
582
583         if (fullName[0] == '\0')
584                 return (FALSE);
585         else {
586                 char *tmp = strrchr(fileName, '/');
587
588                 if (tmp == NULL)
589                         tmp = (char *) fileName;
590                 else
591                         tmp++;
592                 if (check_wildcard_match(tmp, fullName) == TRUE) {
593                         /* Stop searching if we find a match */
594                         memcpy(m_filename, fileName, strlen(fileName));
595                         return (FALSE);
596                 }
597         }
598         return (TRUE);
599 }
600
601
602 /*======================================================================*/
603
604 struct obj_file *arch_new_file(void)
605 {
606         struct i386_file *f;
607         f = xmalloc(sizeof(*f));
608         f->got = NULL;
609         return &f->root;
610 }
611
612 struct obj_section *arch_new_section(void)
613 {
614         return xmalloc(sizeof(struct obj_section));
615 }
616
617 struct obj_symbol *arch_new_symbol(void)
618 {
619         struct i386_symbol *sym;
620         sym = xmalloc(sizeof(*sym));
621         memset(&sym->gotent, 0, sizeof(sym->gotent));
622         return &sym->root;
623 }
624 enum obj_reloc
625 arch_apply_relocation(struct obj_file *f,
626                                           struct obj_section *targsec,
627                                           struct obj_section *symsec,
628                                           struct obj_symbol *sym,
629                                           Elf32_Rel * rel, Elf32_Addr v)
630 {
631         struct i386_file *ifile = (struct i386_file *) f;
632         struct i386_symbol *isym = (struct i386_symbol *) sym;
633
634         Elf32_Addr *loc = (Elf32_Addr *) (targsec->contents + rel->r_offset);
635         Elf32_Addr dot = targsec->header.sh_addr + rel->r_offset;
636         Elf32_Addr got = ifile->got ? ifile->got->header.sh_addr : 0;
637
638         enum obj_reloc ret = obj_reloc_ok;
639
640         switch (ELF32_R_TYPE(rel->r_info)) {
641         case R_386_NONE:
642                 break;
643
644         case R_386_32:
645                 *loc += v;
646                 break;
647
648         case R_386_PLT32:
649         case R_386_PC32:
650                 *loc += v - dot;
651                 break;
652
653         case R_386_GLOB_DAT:
654         case R_386_JMP_SLOT:
655                 *loc = v;
656                 break;
657
658         case R_386_RELATIVE:
659                 *loc += f->baseaddr;
660                 break;
661
662         case R_386_GOTPC:
663                 assert(got != 0);
664                 *loc += got - dot;
665                 break;
666
667         case R_386_GOT32:
668                 assert(isym != NULL);
669                 if (!isym->gotent.reloc_done) {
670                         isym->gotent.reloc_done = 1;
671                         *(Elf32_Addr *) (ifile->got->contents + isym->gotent.offset) =
672                                 v;
673                 }
674                 *loc += isym->gotent.offset;
675                 break;
676
677         case R_386_GOTOFF:
678                 assert(got != 0);
679                 *loc += v - got;
680                 break;
681
682         default:
683                 ret = obj_reloc_unhandled;
684                 break;
685         }
686
687         return ret;
688 }
689
690 int arch_create_got(struct obj_file *f)
691 {
692         struct i386_file *ifile = (struct i386_file *) f;
693         int i, n, offset = 0, gotneeded = 0;
694
695         n = ifile->root.header.e_shnum;
696         for (i = 0; i < n; ++i) {
697                 struct obj_section *relsec, *symsec, *strsec;
698                 Elf32_Rel *rel, *relend;
699                 Elf32_Sym *symtab;
700                 const char *strtab;
701
702                 relsec = ifile->root.sections[i];
703                 if (relsec->header.sh_type != SHT_REL)
704                         continue;
705
706                 symsec = ifile->root.sections[relsec->header.sh_link];
707                 strsec = ifile->root.sections[symsec->header.sh_link];
708
709                 rel = (Elf32_Rel *) relsec->contents;
710                 relend = rel + (relsec->header.sh_size / sizeof(Elf32_Rel));
711                 symtab = (Elf32_Sym *) symsec->contents;
712                 strtab = (const char *) strsec->contents;
713
714                 for (; rel < relend; ++rel) {
715                         Elf32_Sym *extsym;
716                         struct i386_symbol *intsym;
717                         const char *name;
718
719                         switch (ELF32_R_TYPE(rel->r_info)) {
720                         case R_386_GOTPC:
721                         case R_386_GOTOFF:
722                                 gotneeded = 1;
723                         default:
724                                 continue;
725
726                         case R_386_GOT32:
727                                 break;
728                         }
729
730                         extsym = &symtab[ELF32_R_SYM(rel->r_info)];
731                         if (extsym->st_name)
732                                 name = strtab + extsym->st_name;
733                         else
734                                 name = f->sections[extsym->st_shndx]->name;
735                         intsym =
736                                 (struct i386_symbol *) obj_find_symbol(&ifile->root, name);
737
738                         if (!intsym->gotent.offset_done) {
739                                 intsym->gotent.offset_done = 1;
740                                 intsym->gotent.offset = offset;
741                                 offset += 4;
742                         }
743                 }
744         }
745
746         if (offset > 0 || gotneeded)
747                 ifile->got =
748                         obj_create_alloced_section(&ifile->root, ".got", 4, offset);
749
750         return 1;
751 }
752
753 int arch_init_module(struct obj_file *f, struct new_module *mod)
754 {
755         return 1;
756 }
757
758
759 /*======================================================================*/
760
761 /* Standard ELF hash function.  */
762 inline unsigned long obj_elf_hash_n(const char *name, unsigned long n)
763 {
764         unsigned long h = 0;
765         unsigned long g;
766         unsigned char ch;
767
768         while (n > 0) {
769                 ch = *name++;
770                 h = (h << 4) + ch;
771                 if ((g = (h & 0xf0000000)) != 0) {
772                         h ^= g >> 24;
773                         h &= ~g;
774                 }
775                 n--;
776         }
777         return h;
778 }
779
780 unsigned long obj_elf_hash(const char *name)
781 {
782         return obj_elf_hash_n(name, strlen(name));
783 }
784
785 #ifdef BB_FEATURE_INSMOD_VERSION_CHECKING
786 /* Get the kernel version in the canonical integer form.  */
787
788 static int get_kernel_version(char str[STRVERSIONLEN])
789 {
790         struct utsname uts_info;
791         char *p, *q;
792         int a, b, c;
793
794         if (uname(&uts_info) < 0)
795                 return -1;
796         strncpy(str, uts_info.release, STRVERSIONLEN);
797         p = uts_info.release;
798
799         a = strtoul(p, &p, 10);
800         if (*p != '.')
801                 return -1;
802         b = strtoul(p + 1, &p, 10);
803         if (*p != '.')
804                 return -1;
805         c = strtoul(p + 1, &q, 10);
806         if (p + 1 == q)
807                 return -1;
808
809         return a << 16 | b << 8 | c;
810 }
811
812 /* String comparison for non-co-versioned kernel and module.  */
813
814 static int ncv_strcmp(const char *a, const char *b)
815 {
816         size_t alen = strlen(a), blen = strlen(b);
817
818         if (blen == alen + 10 && b[alen] == '_' && b[alen + 1] == 'R')
819                 return strncmp(a, b, alen);
820         else if (alen == blen + 10 && a[blen] == '_' && a[blen + 1] == 'R')
821                 return strncmp(a, b, blen);
822         else
823                 return strcmp(a, b);
824 }
825
826 /* String hashing for non-co-versioned kernel and module.  Here
827    we are simply forced to drop the crc from the hash.  */
828
829 static unsigned long ncv_symbol_hash(const char *str)
830 {
831         size_t len = strlen(str);
832         if (len > 10 && str[len - 10] == '_' && str[len - 9] == 'R')
833                 len -= 10;
834         return obj_elf_hash_n(str, len);
835 }
836
837 void
838 obj_set_symbol_compare(struct obj_file *f,
839                                            int (*cmp) (const char *, const char *),
840                                            unsigned long (*hash) (const char *))
841 {
842         if (cmp)
843                 f->symbol_cmp = cmp;
844         if (hash) {
845                 struct obj_symbol *tmptab[HASH_BUCKETS], *sym, *next;
846                 int i;
847
848                 f->symbol_hash = hash;
849
850                 memcpy(tmptab, f->symtab, sizeof(tmptab));
851                 memset(f->symtab, 0, sizeof(f->symtab));
852
853                 for (i = 0; i < HASH_BUCKETS; ++i)
854                         for (sym = tmptab[i]; sym; sym = next) {
855                                 unsigned long h = hash(sym->name) % HASH_BUCKETS;
856                                 next = sym->next;
857                                 sym->next = f->symtab[h];
858                                 f->symtab[h] = sym;
859                         }
860         }
861 }
862
863 #endif                                                  /* BB_FEATURE_INSMOD_VERSION_CHECKING */
864
865
866 struct obj_symbol *obj_add_symbol(struct obj_file *f, const char *name,
867                                                                   unsigned long symidx, int info,
868                                                                   int secidx, ElfW(Addr) value,
869                                                                   unsigned long size)
870 {
871         struct obj_symbol *sym;
872         unsigned long hash = f->symbol_hash(name) % HASH_BUCKETS;
873         int n_type = ELFW(ST_TYPE) (info);
874         int n_binding = ELFW(ST_BIND) (info);
875
876         for (sym = f->symtab[hash]; sym; sym = sym->next)
877                 if (f->symbol_cmp(sym->name, name) == 0) {
878                         int o_secidx = sym->secidx;
879                         int o_info = sym->info;
880                         int o_type = ELFW(ST_TYPE) (o_info);
881                         int o_binding = ELFW(ST_BIND) (o_info);
882
883                         /* A redefinition!  Is it legal?  */
884
885                         if (secidx == SHN_UNDEF)
886                                 return sym;
887                         else if (o_secidx == SHN_UNDEF)
888                                 goto found;
889                         else if (n_binding == STB_GLOBAL && o_binding == STB_LOCAL) {
890                                 /* Cope with local and global symbols of the same name
891                                    in the same object file, as might have been created
892                                    by ld -r.  The only reason locals are now seen at this
893                                    level at all is so that we can do semi-sensible things
894                                    with parameters.  */
895
896                                 struct obj_symbol *nsym, **p;
897
898                                 nsym = arch_new_symbol();
899                                 nsym->next = sym->next;
900                                 nsym->ksymidx = -1;
901
902                                 /* Excise the old (local) symbol from the hash chain.  */
903                                 for (p = &f->symtab[hash]; *p != sym; p = &(*p)->next)
904                                         continue;
905                                 *p = sym = nsym;
906                                 goto found;
907                         } else if (n_binding == STB_LOCAL) {
908                                 /* Another symbol of the same name has already been defined.
909                                    Just add this to the local table.  */
910                                 sym = arch_new_symbol();
911                                 sym->next = NULL;
912                                 sym->ksymidx = -1;
913                                 f->local_symtab[symidx] = sym;
914                                 goto found;
915                         } else if (n_binding == STB_WEAK)
916                                 return sym;
917                         else if (o_binding == STB_WEAK)
918                                 goto found;
919                         /* Don't unify COMMON symbols with object types the programmer
920                            doesn't expect.  */
921                         else if (secidx == SHN_COMMON
922                                          && (o_type == STT_NOTYPE || o_type == STT_OBJECT))
923                                 return sym;
924                         else if (o_secidx == SHN_COMMON
925                                          && (n_type == STT_NOTYPE || n_type == STT_OBJECT))
926                                 goto found;
927                         else {
928                                 /* Don't report an error if the symbol is coming from
929                                    the kernel or some external module.  */
930                                 if (secidx <= SHN_HIRESERVE)
931                                         errorMsg("%s multiply defined\n", name);
932                                 return sym;
933                         }
934                 }
935
936         /* Completely new symbol.  */
937         sym = arch_new_symbol();
938         sym->next = f->symtab[hash];
939         f->symtab[hash] = sym;
940         sym->ksymidx = -1;
941
942         if (ELFW(ST_BIND) (info) == STB_LOCAL)
943                 f->local_symtab[symidx] = sym;
944
945   found:
946         sym->name = name;
947         sym->value = value;
948         sym->size = size;
949         sym->secidx = secidx;
950         sym->info = info;
951
952         return sym;
953 }
954
955 struct obj_symbol *obj_find_symbol(struct obj_file *f, const char *name)
956 {
957         struct obj_symbol *sym;
958         unsigned long hash = f->symbol_hash(name) % HASH_BUCKETS;
959
960         for (sym = f->symtab[hash]; sym; sym = sym->next)
961                 if (f->symbol_cmp(sym->name, name) == 0)
962                         return sym;
963
964         return NULL;
965 }
966
967 ElfW(Addr)
968         obj_symbol_final_value(struct obj_file * f, struct obj_symbol * sym)
969 {
970         if (sym) {
971                 if (sym->secidx >= SHN_LORESERVE)
972                         return sym->value;
973
974                 return sym->value + f->sections[sym->secidx]->header.sh_addr;
975         } else {
976                 /* As a special case, a NULL sym has value zero.  */
977                 return 0;
978         }
979 }
980
981 struct obj_section *obj_find_section(struct obj_file *f, const char *name)
982 {
983         int i, n = f->header.e_shnum;
984
985         for (i = 0; i < n; ++i)
986                 if (strcmp(f->sections[i]->name, name) == 0)
987                         return f->sections[i];
988
989         return NULL;
990 }
991
992 static int obj_load_order_prio(struct obj_section *a)
993 {
994         unsigned long af, ac;
995
996         af = a->header.sh_flags;
997
998         ac = 0;
999         if (a->name[0] != '.' || strlen(a->name) != 10 ||
1000                 strcmp(a->name + 5, ".init"))
1001                 ac |= 32;
1002         if (af & SHF_ALLOC)
1003                 ac |= 16;
1004         if (!(af & SHF_WRITE))
1005                 ac |= 8;
1006         if (af & SHF_EXECINSTR)
1007                 ac |= 4;
1008         if (a->header.sh_type != SHT_NOBITS)
1009                 ac |= 2;
1010
1011         return ac;
1012 }
1013
1014 void
1015 obj_insert_section_load_order(struct obj_file *f, struct obj_section *sec)
1016 {
1017         struct obj_section **p;
1018         int prio = obj_load_order_prio(sec);
1019         for (p = f->load_order_search_start; *p; p = &(*p)->load_next)
1020                 if (obj_load_order_prio(*p) < prio)
1021                         break;
1022         sec->load_next = *p;
1023         *p = sec;
1024 }
1025
1026 struct obj_section *obj_create_alloced_section(struct obj_file *f,
1027                                                                                            const char *name,
1028                                                                                            unsigned long align,
1029                                                                                            unsigned long size)
1030 {
1031         int newidx = f->header.e_shnum++;
1032         struct obj_section *sec;
1033
1034         f->sections = xrealloc(f->sections, (newidx + 1) * sizeof(sec));
1035         f->sections[newidx] = sec = arch_new_section();
1036
1037         memset(sec, 0, sizeof(*sec));
1038         sec->header.sh_type = SHT_PROGBITS;
1039         sec->header.sh_flags = SHF_WRITE | SHF_ALLOC;
1040         sec->header.sh_size = size;
1041         sec->header.sh_addralign = align;
1042         sec->name = name;
1043         sec->idx = newidx;
1044         if (size)
1045                 sec->contents = xmalloc(size);
1046
1047         obj_insert_section_load_order(f, sec);
1048
1049         return sec;
1050 }
1051
1052 struct obj_section *obj_create_alloced_section_first(struct obj_file *f,
1053                                                                                                          const char *name,
1054                                                                                                          unsigned long align,
1055                                                                                                          unsigned long size)
1056 {
1057         int newidx = f->header.e_shnum++;
1058         struct obj_section *sec;
1059
1060         f->sections = xrealloc(f->sections, (newidx + 1) * sizeof(sec));
1061         f->sections[newidx] = sec = arch_new_section();
1062
1063         memset(sec, 0, sizeof(*sec));
1064         sec->header.sh_type = SHT_PROGBITS;
1065         sec->header.sh_flags = SHF_WRITE | SHF_ALLOC;
1066         sec->header.sh_size = size;
1067         sec->header.sh_addralign = align;
1068         sec->name = name;
1069         sec->idx = newidx;
1070         if (size)
1071                 sec->contents = xmalloc(size);
1072
1073         sec->load_next = f->load_order;
1074         f->load_order = sec;
1075         if (f->load_order_search_start == &f->load_order)
1076                 f->load_order_search_start = &sec->load_next;
1077
1078         return sec;
1079 }
1080
1081 void *obj_extend_section(struct obj_section *sec, unsigned long more)
1082 {
1083         unsigned long oldsize = sec->header.sh_size;
1084         sec->contents = xrealloc(sec->contents, sec->header.sh_size += more);
1085         return sec->contents + oldsize;
1086 }
1087
1088
1089
1090 /* Conditionally add the symbols from the given symbol set to the
1091    new module.  */
1092
1093 static int
1094 add_symbols_from(
1095                                  struct obj_file *f,
1096                                  int idx, struct new_module_symbol *syms, size_t nsyms)
1097 {
1098         struct new_module_symbol *s;
1099         size_t i;
1100         int used = 0;
1101
1102         for (i = 0, s = syms; i < nsyms; ++i, ++s) {
1103
1104                 /* Only add symbols that are already marked external.  If we
1105                    override locals we may cause problems for argument initialization.
1106                    We will also create a false dependency on the module.  */
1107                 struct obj_symbol *sym;
1108
1109                 sym = obj_find_symbol(f, (char *) s->name);
1110                 if (sym && !ELFW(ST_BIND) (sym->info) == STB_LOCAL) {
1111                         sym = obj_add_symbol(f, (char *) s->name, -1,
1112                                                                  ELFW(ST_INFO) (STB_GLOBAL, STT_NOTYPE),
1113                                                                  idx, s->value, 0);
1114                         /* Did our symbol just get installed?  If so, mark the
1115                            module as "used".  */
1116                         if (sym->secidx == idx)
1117                                 used = 1;
1118                 }
1119         }
1120
1121         return used;
1122 }
1123
1124 static void add_kernel_symbols(struct obj_file *f)
1125 {
1126         struct external_module *m;
1127         int i, nused = 0;
1128
1129         /* Add module symbols first.  */
1130
1131         for (i = 0, m = ext_modules; i < n_ext_modules; ++i, ++m)
1132                 if (m->nsyms
1133                         && add_symbols_from(f, SHN_HIRESERVE + 2 + i, m->syms,
1134                                                                 m->nsyms)) m->used = 1, ++nused;
1135
1136         n_ext_modules_used = nused;
1137
1138         /* And finally the symbols from the kernel proper.  */
1139
1140         if (nksyms)
1141                 add_symbols_from(f, SHN_HIRESERVE + 1, ksyms, nksyms);
1142 }
1143
1144 static char *get_modinfo_value(struct obj_file *f, const char *key)
1145 {
1146         struct obj_section *sec;
1147         char *p, *v, *n, *ep;
1148         size_t klen = strlen(key);
1149
1150         sec = obj_find_section(f, ".modinfo");
1151         if (sec == NULL)
1152                 return NULL;
1153         p = sec->contents;
1154         ep = p + sec->header.sh_size;
1155         while (p < ep) {
1156                 v = strchr(p, '=');
1157                 n = strchr(p, '\0');
1158                 if (v) {
1159                         if (p + klen == v && strncmp(p, key, klen) == 0)
1160                                 return v + 1;
1161                 } else {
1162                         if (p + klen == n && strcmp(p, key) == 0)
1163                                 return n;
1164                 }
1165                 p = n + 1;
1166         }
1167
1168         return NULL;
1169 }
1170
1171
1172 /*======================================================================*/
1173 /* Functions relating to module loading in pre 2.1 kernels.  */
1174
1175 static int
1176 old_process_module_arguments(struct obj_file *f, int argc, char **argv)
1177 {
1178         while (argc > 0) {
1179                 char *p, *q;
1180                 struct obj_symbol *sym;
1181                 int *loc;
1182
1183                 p = *argv;
1184                 if ((q = strchr(p, '=')) == NULL) {
1185                         argc--;
1186                         continue;
1187                 }
1188                 *q++ = '\0';
1189
1190                 sym = obj_find_symbol(f, p);
1191
1192                 /* Also check that the parameter was not resolved from the kernel.  */
1193                 if (sym == NULL || sym->secidx > SHN_HIRESERVE) {
1194                         errorMsg("symbol for parameter %s not found\n", p);
1195                         return 0;
1196                 }
1197
1198                 loc = (int *) (f->sections[sym->secidx]->contents + sym->value);
1199
1200                 /* Do C quoting if we begin with a ".  */
1201                 if (*q == '"') {
1202                         char *r, *str;
1203
1204                         str = alloca(strlen(q));
1205                         for (r = str, q++; *q != '"'; ++q, ++r) {
1206                                 if (*q == '\0') {
1207                                         errorMsg("improperly terminated string argument for %s\n", p);
1208                                         return 0;
1209                                 } else if (*q == '\\')
1210                                         switch (*++q) {
1211                                         case 'a':
1212                                                 *r = '\a';
1213                                                 break;
1214                                         case 'b':
1215                                                 *r = '\b';
1216                                                 break;
1217                                         case 'e':
1218                                                 *r = '\033';
1219                                                 break;
1220                                         case 'f':
1221                                                 *r = '\f';
1222                                                 break;
1223                                         case 'n':
1224                                                 *r = '\n';
1225                                                 break;
1226                                         case 'r':
1227                                                 *r = '\r';
1228                                                 break;
1229                                         case 't':
1230                                                 *r = '\t';
1231                                                 break;
1232
1233                                         case '0':
1234                                         case '1':
1235                                         case '2':
1236                                         case '3':
1237                                         case '4':
1238                                         case '5':
1239                                         case '6':
1240                                         case '7':
1241                                                 {
1242                                                         int c = *q - '0';
1243                                                         if (q[1] >= '0' && q[1] <= '7') {
1244                                                                 c = (c * 8) + *++q - '0';
1245                                                                 if (q[1] >= '0' && q[1] <= '7')
1246                                                                         c = (c * 8) + *++q - '0';
1247                                                         }
1248                                                         *r = c;
1249                                                 }
1250                                                 break;
1251
1252                                         default:
1253                                                 *r = *q;
1254                                                 break;
1255                                 } else
1256                                         *r = *q;
1257                         }
1258                         *r = '\0';
1259                         obj_string_patch(f, sym->secidx, sym->value, str);
1260                 } else if (*q >= '0' && *q <= '9') {
1261                         do
1262                                 *loc++ = strtoul(q, &q, 0);
1263                         while (*q++ == ',');
1264                 } else {
1265                         char *contents = f->sections[sym->secidx]->contents;
1266                         char *loc = contents + sym->value;
1267                         char *r;                        /* To search for commas */
1268
1269                         /* Break the string with comas */
1270                         while ((r = strchr(q, ',')) != (char *) NULL) {
1271                                 *r++ = '\0';
1272                                 obj_string_patch(f, sym->secidx, loc - contents, q);
1273                                 loc += sizeof(char *);
1274                                 q = r;
1275                         }
1276
1277                         /* last part */
1278                         obj_string_patch(f, sym->secidx, loc - contents, q);
1279                 }
1280
1281                 argc--, argv++;
1282         }
1283
1284         return 1;
1285 }
1286
1287 #ifdef BB_FEATURE_INSMOD_VERSION_CHECKING
1288 static int old_is_module_checksummed(struct obj_file *f)
1289 {
1290         return obj_find_symbol(f, "Using_Versions") != NULL;
1291 }
1292 /* Get the module's kernel version in the canonical integer form.  */
1293
1294 static int
1295 old_get_module_version(struct obj_file *f, char str[STRVERSIONLEN])
1296 {
1297         struct obj_symbol *sym;
1298         char *p, *q;
1299         int a, b, c;
1300
1301         sym = obj_find_symbol(f, "kernel_version");
1302         if (sym == NULL)
1303                 return -1;
1304
1305         p = f->sections[sym->secidx]->contents + sym->value;
1306         strncpy(str, p, STRVERSIONLEN);
1307
1308         a = strtoul(p, &p, 10);
1309         if (*p != '.')
1310                 return -1;
1311         b = strtoul(p + 1, &p, 10);
1312         if (*p != '.')
1313                 return -1;
1314         c = strtoul(p + 1, &q, 10);
1315         if (p + 1 == q)
1316                 return -1;
1317
1318         return a << 16 | b << 8 | c;
1319 }
1320
1321 #endif   /* BB_FEATURE_INSMOD_VERSION_CHECKING */
1322
1323 #ifdef BB_FEATURE_INSMOD_OLD_KERNEL
1324
1325 /* Fetch all the symbols and divvy them up as appropriate for the modules.  */
1326
1327 static int old_get_kernel_symbols(void)
1328 {
1329         struct old_kernel_sym *ks, *k;
1330         struct new_module_symbol *s;
1331         struct external_module *mod;
1332         int nks, nms, nmod, i;
1333
1334         nks = get_kernel_syms(NULL);
1335         if (nks < 0) {
1336                 errorMsg("get_kernel_syms: %s: %s", m_name, strerror(errno));
1337                 return 0;
1338         }
1339
1340         ks = k = xmalloc(nks * sizeof(*ks));
1341
1342         if (get_kernel_syms(ks) != nks) {
1343                 perror("inconsistency with get_kernel_syms -- is someone else "
1344                            "playing with modules?");
1345                 free(ks);
1346                 return 0;
1347         }
1348
1349         /* Collect the module information.  */
1350
1351         mod = NULL;
1352         nmod = -1;
1353
1354         while (k->name[0] == '#' && k->name[1]) {
1355                 struct old_kernel_sym *k2;
1356                 struct new_module_symbol *s;
1357
1358                 /* Find out how many symbols this module has.  */
1359                 for (k2 = k + 1; k2->name[0] != '#'; ++k2)
1360                         continue;
1361                 nms = k2 - k - 1;
1362
1363                 mod = xrealloc(mod, (++nmod + 1) * sizeof(*mod));
1364                 mod[nmod].name = k->name + 1;
1365                 mod[nmod].addr = k->value;
1366                 mod[nmod].used = 0;
1367                 mod[nmod].nsyms = nms;
1368                 mod[nmod].syms = s = (nms ? xmalloc(nms * sizeof(*s)) : NULL);
1369
1370                 for (i = 0, ++k; i < nms; ++i, ++s, ++k) {
1371                         s->name = (unsigned long) k->name;
1372                         s->value = k->value;
1373                 }
1374
1375                 k = k2;
1376         }
1377
1378         ext_modules = mod;
1379         n_ext_modules = nmod + 1;
1380
1381         /* Now collect the symbols for the kernel proper.  */
1382
1383         if (k->name[0] == '#')
1384                 ++k;
1385
1386         nksyms = nms = nks - (k - ks);
1387         ksyms = s = (nms ? xmalloc(nms * sizeof(*s)) : NULL);
1388
1389         for (i = 0; i < nms; ++i, ++s, ++k) {
1390                 s->name = (unsigned long) k->name;
1391                 s->value = k->value;
1392         }
1393
1394         return 1;
1395 }
1396
1397 /* Return the kernel symbol checksum version, or zero if not used.  */
1398
1399 static int old_is_kernel_checksummed(void)
1400 {
1401         /* Using_Versions is the first symbol.  */
1402         if (nksyms > 0
1403                 && strcmp((char *) ksyms[0].name,
1404                                   "Using_Versions") == 0) return ksyms[0].value;
1405         else
1406                 return 0;
1407 }
1408
1409
1410 static int old_create_mod_use_count(struct obj_file *f)
1411 {
1412         struct obj_section *sec;
1413
1414         sec = obj_create_alloced_section_first(f, ".moduse", sizeof(long),
1415                                                                                    sizeof(long));
1416
1417         obj_add_symbol(f, "mod_use_count_", -1,
1418                                    ELFW(ST_INFO) (STB_LOCAL, STT_OBJECT), sec->idx, 0,
1419                                    sizeof(long));
1420
1421         return 1;
1422 }
1423
1424 static int
1425 old_init_module(const char *m_name, struct obj_file *f,
1426                                 unsigned long m_size)
1427 {
1428         char *image;
1429         struct old_mod_routines routines;
1430         struct old_symbol_table *symtab;
1431         int ret;
1432
1433         /* Create the symbol table */
1434         {
1435                 int nsyms = 0, strsize = 0, total;
1436
1437                 /* Size things first... */
1438                 if (flag_export) {
1439                         int i;
1440                         for (i = 0; i < HASH_BUCKETS; ++i) {
1441                                 struct obj_symbol *sym;
1442                                 for (sym = f->symtab[i]; sym; sym = sym->next)
1443                                         if (ELFW(ST_BIND) (sym->info) != STB_LOCAL
1444                                                 && sym->secidx <= SHN_HIRESERVE) 
1445                                         {
1446                                                 sym->ksymidx = nsyms++;
1447                                                 strsize += strlen(sym->name) + 1;
1448                                         }
1449                         }
1450                 }
1451
1452                 total = (sizeof(struct old_symbol_table)
1453                                  + nsyms * sizeof(struct old_module_symbol)
1454                                  + n_ext_modules_used * sizeof(struct old_module_ref)
1455                                  + strsize);
1456                 symtab = xmalloc(total);
1457                 symtab->size = total;
1458                 symtab->n_symbols = nsyms;
1459                 symtab->n_refs = n_ext_modules_used;
1460
1461                 if (flag_export && nsyms) {
1462                         struct old_module_symbol *ksym;
1463                         char *str;
1464                         int i;
1465
1466                         ksym = symtab->symbol;
1467                         str = ((char *) ksym + nsyms * sizeof(struct old_module_symbol)
1468                                    + n_ext_modules_used * sizeof(struct old_module_ref));
1469
1470                         for (i = 0; i < HASH_BUCKETS; ++i) {
1471                                 struct obj_symbol *sym;
1472                                 for (sym = f->symtab[i]; sym; sym = sym->next)
1473                                         if (sym->ksymidx >= 0) {
1474                                                 ksym->addr = obj_symbol_final_value(f, sym);
1475                                                 ksym->name =
1476                                                         (unsigned long) str - (unsigned long) symtab;
1477
1478                                                 str = stpcpy(str, sym->name) + 1;
1479                                                 ksym++;
1480                                         }
1481                         }
1482                 }
1483
1484                 if (n_ext_modules_used) {
1485                         struct old_module_ref *ref;
1486                         int i;
1487
1488                         ref = (struct old_module_ref *)
1489                                 ((char *) symtab->symbol + nsyms * sizeof(struct old_module_symbol));
1490
1491                         for (i = 0; i < n_ext_modules; ++i)
1492                                 if (ext_modules[i].used)
1493                                         ref++->module = ext_modules[i].addr;
1494                 }
1495         }
1496
1497         /* Fill in routines.  */
1498
1499         routines.init =
1500                 obj_symbol_final_value(f, obj_find_symbol(f, "init_module"));
1501         routines.cleanup =
1502                 obj_symbol_final_value(f, obj_find_symbol(f, "cleanup_module"));
1503
1504         /* Whew!  All of the initialization is complete.  Collect the final
1505            module image and give it to the kernel.  */
1506
1507         image = xmalloc(m_size);
1508         obj_create_image(f, image);
1509
1510         /* image holds the complete relocated module, accounting correctly for
1511            mod_use_count.  However the old module kernel support assume that
1512            it is receiving something which does not contain mod_use_count.  */
1513         ret = old_sys_init_module(m_name, image + sizeof(long),
1514                                                           m_size | (flag_autoclean ? OLD_MOD_AUTOCLEAN
1515                                                                                 : 0), &routines, symtab);
1516         if (ret)
1517                 errorMsg("init_module: %s: %s", m_name, strerror(errno));
1518
1519         free(image);
1520         free(symtab);
1521
1522         return ret == 0;
1523 }
1524
1525 #else
1526
1527 #define old_create_mod_use_count(x) TRUE
1528 #define old_init_module(x, y, z) TRUE
1529
1530 #endif                                                  /* BB_FEATURE_INSMOD_OLD_KERNEL */
1531
1532
1533
1534 /*======================================================================*/
1535 /* Functions relating to module loading after 2.1.18.  */
1536
1537 static int
1538 new_process_module_arguments(struct obj_file *f, int argc, char **argv)
1539 {
1540         while (argc > 0) {
1541                 char *p, *q, *key;
1542                 struct obj_symbol *sym;
1543                 char *contents, *loc;
1544                 int min, max, n;
1545
1546                 p = *argv;
1547                 if ((q = strchr(p, '=')) == NULL) {
1548                         argc--;
1549                         continue;
1550                 }
1551
1552                 key = alloca(q - p + 6);
1553                 memcpy(key, "parm_", 5);
1554                 memcpy(key + 5, p, q - p);
1555                 key[q - p + 5] = 0;
1556
1557                 p = get_modinfo_value(f, key);
1558                 key += 5;
1559                 if (p == NULL) {
1560                         errorMsg("invalid parameter %s\n", key);
1561                         return 0;
1562                 }
1563
1564                 sym = obj_find_symbol(f, key);
1565
1566                 /* Also check that the parameter was not resolved from the kernel.  */
1567                 if (sym == NULL || sym->secidx > SHN_HIRESERVE) {
1568                         errorMsg("symbol for parameter %s not found\n", key);
1569                         return 0;
1570                 }
1571
1572                 if (isdigit(*p)) {
1573                         min = strtoul(p, &p, 10);
1574                         if (*p == '-')
1575                                 max = strtoul(p + 1, &p, 10);
1576                         else
1577                                 max = min;
1578                 } else
1579                         min = max = 1;
1580
1581                 contents = f->sections[sym->secidx]->contents;
1582                 loc = contents + sym->value;
1583                 n = (*++q != '\0');
1584
1585                 while (1) {
1586                         if ((*p == 's') || (*p == 'c')) {
1587                                 char *str;
1588
1589                                 /* Do C quoting if we begin with a ", else slurp the lot.  */
1590                                 if (*q == '"') {
1591                                         char *r;
1592
1593                                         str = alloca(strlen(q));
1594                                         for (r = str, q++; *q != '"'; ++q, ++r) {
1595                                                 if (*q == '\0') {
1596                                                         errorMsg("improperly terminated string argument for %s\n",
1597                                                                         key);
1598                                                         return 0;
1599                                                 } else if (*q == '\\')
1600                                                         switch (*++q) {
1601                                                         case 'a':
1602                                                                 *r = '\a';
1603                                                                 break;
1604                                                         case 'b':
1605                                                                 *r = '\b';
1606                                                                 break;
1607                                                         case 'e':
1608                                                                 *r = '\033';
1609                                                                 break;
1610                                                         case 'f':
1611                                                                 *r = '\f';
1612                                                                 break;
1613                                                         case 'n':
1614                                                                 *r = '\n';
1615                                                                 break;
1616                                                         case 'r':
1617                                                                 *r = '\r';
1618                                                                 break;
1619                                                         case 't':
1620                                                                 *r = '\t';
1621                                                                 break;
1622
1623                                                         case '0':
1624                                                         case '1':
1625                                                         case '2':
1626                                                         case '3':
1627                                                         case '4':
1628                                                         case '5':
1629                                                         case '6':
1630                                                         case '7':
1631                                                                 {
1632                                                                         int c = *q - '0';
1633                                                                         if (q[1] >= '0' && q[1] <= '7') {
1634                                                                                 c = (c * 8) + *++q - '0';
1635                                                                                 if (q[1] >= '0' && q[1] <= '7')
1636                                                                                         c = (c * 8) + *++q - '0';
1637                                                                         }
1638                                                                         *r = c;
1639                                                                 }
1640                                                                 break;
1641
1642                                                         default:
1643                                                                 *r = *q;
1644                                                                 break;
1645                                                 } else
1646                                                         *r = *q;
1647                                         }
1648                                         *r = '\0';
1649                                         ++q;
1650                                 } else {
1651                                         char *r;
1652
1653                                         /* In this case, the string is not quoted. We will break
1654                                            it using the coma (like for ints). If the user wants to
1655                                            include comas in a string, he just has to quote it */
1656
1657                                         /* Search the next coma */
1658                                         r = strchr(q, ',');
1659
1660                                         /* Found ? */
1661                                         if (r != (char *) NULL) {
1662                                                 /* Recopy the current field */
1663                                                 str = alloca(r - q + 1);
1664                                                 memcpy(str, q, r - q);
1665
1666                                                 /* I don't know if it is usefull, as the previous case
1667                                                    doesn't null terminate the string ??? */
1668                                                 str[r - q] = '\0';
1669
1670                                                 /* Keep next fields */
1671                                                 q = r;
1672                                         } else {
1673                                                 /* last string */
1674                                                 str = q;
1675                                                 q = "";
1676                                         }
1677                                 }
1678
1679                                 if (*p == 's') {
1680                                         /* Normal string */
1681                                         obj_string_patch(f, sym->secidx, loc - contents, str);
1682                                         loc += tgt_sizeof_char_p;
1683                                 } else {
1684                                         /* Array of chars (in fact, matrix !) */
1685                                         unsigned long charssize;        /* size of each member */
1686
1687                                         /* Get the size of each member */
1688                                         /* Probably we should do that outside the loop ? */
1689                                         if (!isdigit(*(p + 1))) {
1690                                                 errorMsg("parameter type 'c' for %s must be followed by"
1691                                                                 " the maximum size\n", key);
1692                                                 return 0;
1693                                         }
1694                                         charssize = strtoul(p + 1, (char **) NULL, 10);
1695
1696                                         /* Check length */
1697                                         if (strlen(str) >= charssize) {
1698                                                 errorMsg("string too long for %s (max %ld)\n", key,
1699                                                                 charssize - 1);
1700                                                 return 0;
1701                                         }
1702
1703                                         /* Copy to location */
1704                                         strcpy((char *) loc, str);
1705                                         loc += charssize;
1706                                 }
1707                         } else {
1708                                 long v = strtoul(q, &q, 0);
1709                                 switch (*p) {
1710                                 case 'b':
1711                                         *loc++ = v;
1712                                         break;
1713                                 case 'h':
1714                                         *(short *) loc = v;
1715                                         loc += tgt_sizeof_short;
1716                                         break;
1717                                 case 'i':
1718                                         *(int *) loc = v;
1719                                         loc += tgt_sizeof_int;
1720                                         break;
1721                                 case 'l':
1722                                         *(long *) loc = v;
1723                                         loc += tgt_sizeof_long;
1724                                         break;
1725
1726                                 default:
1727                                         errorMsg("unknown parameter type '%c' for %s\n", *p, key);
1728                                         return 0;
1729                                 }
1730                         }
1731
1732                   retry_end_of_value:
1733                         switch (*q) {
1734                         case '\0':
1735                                 goto end_of_arg;
1736
1737                         case ' ':
1738                         case '\t':
1739                         case '\n':
1740                         case '\r':
1741                                 ++q;
1742                                 goto retry_end_of_value;
1743
1744                         case ',':
1745                                 if (++n > max) {
1746                                         errorMsg("too many values for %s (max %d)\n", key, max);
1747                                         return 0;
1748                                 }
1749                                 ++q;
1750                                 break;
1751
1752                         default:
1753                                 errorMsg("invalid argument syntax for %s\n", key);
1754                                 return 0;
1755                         }
1756                 }
1757
1758           end_of_arg:
1759                 if (n < min) {
1760                         errorMsg("too few values for %s (min %d)\n", key, min);
1761                         return 0;
1762                 }
1763
1764                 argc--, argv++;
1765         }
1766
1767         return 1;
1768 }
1769
1770 #ifdef BB_FEATURE_INSMOD_VERSION_CHECKING
1771 static int new_is_module_checksummed(struct obj_file *f)
1772 {
1773         const char *p = get_modinfo_value(f, "using_checksums");
1774         if (p)
1775                 return atoi(p);
1776         else
1777                 return 0;
1778 }
1779
1780 /* Get the module's kernel version in the canonical integer form.  */
1781
1782 static int
1783 new_get_module_version(struct obj_file *f, char str[STRVERSIONLEN])
1784 {
1785         char *p, *q;
1786         int a, b, c;
1787
1788         p = get_modinfo_value(f, "kernel_version");
1789         if (p == NULL)
1790                 return -1;
1791         strncpy(str, p, STRVERSIONLEN);
1792
1793         a = strtoul(p, &p, 10);
1794         if (*p != '.')
1795                 return -1;
1796         b = strtoul(p + 1, &p, 10);
1797         if (*p != '.')
1798                 return -1;
1799         c = strtoul(p + 1, &q, 10);
1800         if (p + 1 == q)
1801                 return -1;
1802
1803         return a << 16 | b << 8 | c;
1804 }
1805
1806 #endif   /* BB_FEATURE_INSMOD_VERSION_CHECKING */
1807
1808
1809 #ifdef BB_FEATURE_INSMOD_NEW_KERNEL
1810
1811 /* Fetch the loaded modules, and all currently exported symbols.  */
1812
1813 static int new_get_kernel_symbols(void)
1814 {
1815         char *module_names, *mn;
1816         struct external_module *modules, *m;
1817         struct new_module_symbol *syms, *s;
1818         size_t ret, bufsize, nmod, nsyms, i, j;
1819
1820         /* Collect the loaded modules.  */
1821
1822         module_names = xmalloc(bufsize = 256);
1823   retry_modules_load:
1824         if (query_module(NULL, QM_MODULES, module_names, bufsize, &ret)) {
1825                 if (errno == ENOSPC) {
1826                         module_names = xrealloc(module_names, bufsize = ret);
1827                         goto retry_modules_load;
1828                 }
1829                 errorMsg("QM_MODULES: %s", strerror(errno));
1830                 return 0;
1831         }
1832
1833         n_ext_modules = nmod = ret;
1834         ext_modules = modules = xmalloc(nmod * sizeof(*modules));
1835         memset(modules, 0, nmod * sizeof(*modules));
1836
1837         /* Collect the modules' symbols.  */
1838
1839         for (i = 0, mn = module_names, m = modules;
1840                  i < nmod; ++i, ++m, mn += strlen(mn) + 1) {
1841                 struct new_module_info info;
1842
1843                 if (query_module(mn, QM_INFO, &info, sizeof(info), &ret)) {
1844                         if (errno == ENOENT) {
1845                                 /* The module was removed out from underneath us.  */
1846                                 continue;
1847                         }
1848                         errorMsg("query_module: QM_INFO: %s: %s", mn, strerror(errno));
1849                         return 0;
1850                 }
1851
1852                 syms = xmalloc(bufsize = 1024);
1853           retry_mod_sym_load:
1854                 if (query_module(mn, QM_SYMBOLS, syms, bufsize, &ret)) {
1855                         switch (errno) {
1856                         case ENOSPC:
1857                                 syms = xrealloc(syms, bufsize = ret);
1858                                 goto retry_mod_sym_load;
1859                         case ENOENT:
1860                                 /* The module was removed out from underneath us.  */
1861                                 continue;
1862                         default:
1863                                 errorMsg("query_module: QM_SYMBOLS: %s: %s", mn, strerror(errno));
1864                                 return 0;
1865                         }
1866                 }
1867                 nsyms = ret;
1868
1869                 m->name = mn;
1870                 m->addr = info.addr;
1871                 m->nsyms = nsyms;
1872                 m->syms = syms;
1873
1874                 for (j = 0, s = syms; j < nsyms; ++j, ++s) {
1875                         s->name += (unsigned long) syms;
1876                 }
1877         }
1878
1879         /* Collect the kernel's symbols.  */
1880
1881         syms = xmalloc(bufsize = 16 * 1024);
1882   retry_kern_sym_load:
1883         if (query_module(NULL, QM_SYMBOLS, syms, bufsize, &ret)) {
1884                 if (errno == ENOSPC) {
1885                         syms = xrealloc(syms, bufsize = ret);
1886                         goto retry_kern_sym_load;
1887                 }
1888                 errorMsg("kernel: QM_SYMBOLS: %s", strerror(errno));
1889                 return 0;
1890         }
1891         nksyms = nsyms = ret;
1892         ksyms = syms;
1893
1894         for (j = 0, s = syms; j < nsyms; ++j, ++s) {
1895                 s->name += (unsigned long) syms;
1896         }
1897         return 1;
1898 }
1899
1900
1901 /* Return the kernel symbol checksum version, or zero if not used.  */
1902
1903 static int new_is_kernel_checksummed(void)
1904 {
1905         struct new_module_symbol *s;
1906         size_t i;
1907
1908         /* Using_Versions is not the first symbol, but it should be in there.  */
1909
1910         for (i = 0, s = ksyms; i < nksyms; ++i, ++s)
1911                 if (strcmp((char *) s->name, "Using_Versions") == 0)
1912                         return s->value;
1913
1914         return 0;
1915 }
1916
1917
1918 static int new_create_this_module(struct obj_file *f, const char *m_name)
1919 {
1920         struct obj_section *sec;
1921
1922         sec = obj_create_alloced_section_first(f, ".this", tgt_sizeof_long,
1923                                                                                    sizeof(struct new_module));
1924         memset(sec->contents, 0, sizeof(struct new_module));
1925
1926         obj_add_symbol(f, "__this_module", -1,
1927                                    ELFW(ST_INFO) (STB_LOCAL, STT_OBJECT), sec->idx, 0,
1928                                    sizeof(struct new_module));
1929
1930         obj_string_patch(f, sec->idx, offsetof(struct new_module, name),
1931                                          m_name);
1932
1933         return 1;
1934 }
1935
1936
1937 static int new_create_module_ksymtab(struct obj_file *f)
1938 {
1939         struct obj_section *sec;
1940         int i;
1941
1942         /* We must always add the module references.  */
1943
1944         if (n_ext_modules_used) {
1945                 struct new_module_ref *dep;
1946                 struct obj_symbol *tm;
1947
1948                 sec = obj_create_alloced_section(f, ".kmodtab", tgt_sizeof_void_p,
1949                                                                                  (sizeof(struct new_module_ref)
1950                                                                                   * n_ext_modules_used));
1951                 if (!sec)
1952                         return 0;
1953
1954                 tm = obj_find_symbol(f, "__this_module");
1955                 dep = (struct new_module_ref *) sec->contents;
1956                 for (i = 0; i < n_ext_modules; ++i)
1957                         if (ext_modules[i].used) {
1958                                 dep->dep = ext_modules[i].addr;
1959                                 obj_symbol_patch(f, sec->idx,
1960                                                                  (char *) &dep->ref - sec->contents, tm);
1961                                 dep->next_ref = 0;
1962                                 ++dep;
1963                         }
1964         }
1965
1966         if (flag_export && !obj_find_section(f, "__ksymtab")) {
1967                 size_t nsyms;
1968                 int *loaded;
1969
1970                 sec =
1971                         obj_create_alloced_section(f, "__ksymtab", tgt_sizeof_void_p,
1972                                                                            0);
1973
1974                 /* We don't want to export symbols residing in sections that
1975                    aren't loaded.  There are a number of these created so that
1976                    we make sure certain module options don't appear twice.  */
1977
1978                 loaded = alloca(sizeof(int) * (i = f->header.e_shnum));
1979                 while (--i >= 0)
1980                         loaded[i] = (f->sections[i]->header.sh_flags & SHF_ALLOC) != 0;
1981
1982                 for (nsyms = i = 0; i < HASH_BUCKETS; ++i) {
1983                         struct obj_symbol *sym;
1984                         for (sym = f->symtab[i]; sym; sym = sym->next)
1985                                 if (ELFW(ST_BIND) (sym->info) != STB_LOCAL
1986                                         && sym->secidx <= SHN_HIRESERVE
1987                                         && (sym->secidx >= SHN_LORESERVE
1988                                                 || loaded[sym->secidx])) {
1989                                         ElfW(Addr) ofs = nsyms * 2 * tgt_sizeof_void_p;
1990
1991                                         obj_symbol_patch(f, sec->idx, ofs, sym);
1992                                         obj_string_patch(f, sec->idx, ofs + tgt_sizeof_void_p,
1993                                                                          sym->name);
1994
1995                                         nsyms++;
1996                                 }
1997                 }
1998
1999                 obj_extend_section(sec, nsyms * 2 * tgt_sizeof_char_p);
2000         }
2001
2002         return 1;
2003 }
2004
2005
2006 static int
2007 new_init_module(const char *m_name, struct obj_file *f,
2008                                 unsigned long m_size)
2009 {
2010         struct new_module *module;
2011         struct obj_section *sec;
2012         void *image;
2013         int ret;
2014         tgt_long m_addr;
2015
2016         sec = obj_find_section(f, ".this");
2017         module = (struct new_module *) sec->contents;
2018         m_addr = sec->header.sh_addr;
2019
2020         module->size_of_struct = sizeof(*module);
2021         module->size = m_size;
2022         module->flags = flag_autoclean ? NEW_MOD_AUTOCLEAN : 0;
2023
2024         sec = obj_find_section(f, "__ksymtab");
2025         if (sec && sec->header.sh_size) {
2026                 module->syms = sec->header.sh_addr;
2027                 module->nsyms = sec->header.sh_size / (2 * tgt_sizeof_char_p);
2028         }
2029
2030         if (n_ext_modules_used) {
2031                 sec = obj_find_section(f, ".kmodtab");
2032                 module->deps = sec->header.sh_addr;
2033                 module->ndeps = n_ext_modules_used;
2034         }
2035
2036         module->init =
2037                 obj_symbol_final_value(f, obj_find_symbol(f, "init_module"));
2038         module->cleanup =
2039                 obj_symbol_final_value(f, obj_find_symbol(f, "cleanup_module"));
2040
2041         sec = obj_find_section(f, "__ex_table");
2042         if (sec) {
2043                 module->ex_table_start = sec->header.sh_addr;
2044                 module->ex_table_end = sec->header.sh_addr + sec->header.sh_size;
2045         }
2046
2047         sec = obj_find_section(f, ".text.init");
2048         if (sec) {
2049                 module->runsize = sec->header.sh_addr - m_addr;
2050         }
2051         sec = obj_find_section(f, ".data.init");
2052         if (sec) {
2053                 if (!module->runsize ||
2054                         module->runsize > sec->header.sh_addr - m_addr)
2055                                 module->runsize = sec->header.sh_addr - m_addr;
2056         }
2057
2058         if (!arch_init_module(f, module))
2059                 return 0;
2060
2061         /* Whew!  All of the initialization is complete.  Collect the final
2062            module image and give it to the kernel.  */
2063
2064         image = xmalloc(m_size);
2065         obj_create_image(f, image);
2066
2067         ret = new_sys_init_module(m_name, (struct new_module *) image);
2068         if (ret)
2069                 errorMsg("init_module: %s: %s", m_name, strerror(errno));
2070
2071         free(image);
2072
2073         return ret == 0;
2074 }
2075
2076 #else
2077
2078 #define new_init_module(x, y, z) TRUE
2079 #define new_create_this_module(x, y) 0
2080 #define new_create_module_ksymtab(x)
2081
2082 #endif                                                  /* BB_FEATURE_INSMOD_OLD_KERNEL */
2083
2084
2085 /*======================================================================*/
2086
2087 int
2088 obj_string_patch(struct obj_file *f, int secidx, ElfW(Addr) offset,
2089                                  const char *string)
2090 {
2091         struct obj_string_patch *p;
2092         struct obj_section *strsec;
2093         size_t len = strlen(string) + 1;
2094         char *loc;
2095
2096         p = xmalloc(sizeof(*p));
2097         p->next = f->string_patches;
2098         p->reloc_secidx = secidx;
2099         p->reloc_offset = offset;
2100         f->string_patches = p;
2101
2102         strsec = obj_find_section(f, ".kstrtab");
2103         if (strsec == NULL) {
2104                 strsec = obj_create_alloced_section(f, ".kstrtab", 1, len);
2105                 p->string_offset = 0;
2106                 loc = strsec->contents;
2107         } else {
2108                 p->string_offset = strsec->header.sh_size;
2109                 loc = obj_extend_section(strsec, len);
2110         }
2111         memcpy(loc, string, len);
2112
2113         return 1;
2114 }
2115
2116 int
2117 obj_symbol_patch(struct obj_file *f, int secidx, ElfW(Addr) offset,
2118                                  struct obj_symbol *sym)
2119 {
2120         struct obj_symbol_patch *p;
2121
2122         p = xmalloc(sizeof(*p));
2123         p->next = f->symbol_patches;
2124         p->reloc_secidx = secidx;
2125         p->reloc_offset = offset;
2126         p->sym = sym;
2127         f->symbol_patches = p;
2128
2129         return 1;
2130 }
2131
2132 int obj_check_undefineds(struct obj_file *f)
2133 {
2134         unsigned long i;
2135         int ret = 1;
2136
2137         for (i = 0; i < HASH_BUCKETS; ++i) {
2138                 struct obj_symbol *sym;
2139                 for (sym = f->symtab[i]; sym; sym = sym->next)
2140                         if (sym->secidx == SHN_UNDEF) {
2141                                 if (ELFW(ST_BIND) (sym->info) == STB_WEAK) {
2142                                         sym->secidx = SHN_ABS;
2143                                         sym->value = 0;
2144                                 } else {
2145                                         errorMsg("unresolved symbol %s\n", sym->name);
2146                                         ret = 0;
2147                                 }
2148                         }
2149         }
2150
2151         return ret;
2152 }
2153
2154 void obj_allocate_commons(struct obj_file *f)
2155 {
2156         struct common_entry {
2157                 struct common_entry *next;
2158                 struct obj_symbol *sym;
2159         } *common_head = NULL;
2160
2161         unsigned long i;
2162
2163         for (i = 0; i < HASH_BUCKETS; ++i) {
2164                 struct obj_symbol *sym;
2165                 for (sym = f->symtab[i]; sym; sym = sym->next)
2166                         if (sym->secidx == SHN_COMMON) {
2167                                 /* Collect all COMMON symbols and sort them by size so as to
2168                                    minimize space wasted by alignment requirements.  */
2169                                 {
2170                                         struct common_entry **p, *n;
2171                                         for (p = &common_head; *p; p = &(*p)->next)
2172                                                 if (sym->size <= (*p)->sym->size)
2173                                                         break;
2174
2175                                         n = alloca(sizeof(*n));
2176                                         n->next = *p;
2177                                         n->sym = sym;
2178                                         *p = n;
2179                                 }
2180                         }
2181         }
2182
2183         for (i = 1; i < f->local_symtab_size; ++i) {
2184                 struct obj_symbol *sym = f->local_symtab[i];
2185                 if (sym && sym->secidx == SHN_COMMON) {
2186                         struct common_entry **p, *n;
2187                         for (p = &common_head; *p; p = &(*p)->next)
2188                                 if (sym == (*p)->sym)
2189                                         break;
2190                                 else if (sym->size < (*p)->sym->size) {
2191                                         n = alloca(sizeof(*n));
2192                                         n->next = *p;
2193                                         n->sym = sym;
2194                                         *p = n;
2195                                         break;
2196                                 }
2197                 }
2198         }
2199
2200         if (common_head) {
2201                 /* Find the bss section.  */
2202                 for (i = 0; i < f->header.e_shnum; ++i)
2203                         if (f->sections[i]->header.sh_type == SHT_NOBITS)
2204                                 break;
2205
2206                 /* If for some reason there hadn't been one, create one.  */
2207                 if (i == f->header.e_shnum) {
2208                         struct obj_section *sec;
2209
2210                         f->sections = xrealloc(f->sections, (i + 1) * sizeof(sec));
2211                         f->sections[i] = sec = arch_new_section();
2212                         f->header.e_shnum = i + 1;
2213
2214                         memset(sec, 0, sizeof(*sec));
2215                         sec->header.sh_type = SHT_PROGBITS;
2216                         sec->header.sh_flags = SHF_WRITE | SHF_ALLOC;
2217                         sec->name = ".bss";
2218                         sec->idx = i;
2219                 }
2220
2221                 /* Allocate the COMMONS.  */
2222                 {
2223                         ElfW(Addr) bss_size = f->sections[i]->header.sh_size;
2224                         ElfW(Addr) max_align = f->sections[i]->header.sh_addralign;
2225                         struct common_entry *c;
2226
2227                         for (c = common_head; c; c = c->next) {
2228                                 ElfW(Addr) align = c->sym->value;
2229
2230                                 if (align > max_align)
2231                                         max_align = align;
2232                                 if (bss_size & (align - 1))
2233                                         bss_size = (bss_size | (align - 1)) + 1;
2234
2235                                 c->sym->secidx = i;
2236                                 c->sym->value = bss_size;
2237
2238                                 bss_size += c->sym->size;
2239                         }
2240
2241                         f->sections[i]->header.sh_size = bss_size;
2242                         f->sections[i]->header.sh_addralign = max_align;
2243                 }
2244         }
2245
2246         /* For the sake of patch relocation and parameter initialization,
2247            allocate zeroed data for NOBITS sections now.  Note that after
2248            this we cannot assume NOBITS are really empty.  */
2249         for (i = 0; i < f->header.e_shnum; ++i) {
2250                 struct obj_section *s = f->sections[i];
2251                 if (s->header.sh_type == SHT_NOBITS) {
2252                         s->contents = memset(xmalloc(s->header.sh_size),
2253                                                                  0, s->header.sh_size);
2254                         s->header.sh_type = SHT_PROGBITS;
2255                 }
2256         }
2257 }
2258
2259 unsigned long obj_load_size(struct obj_file *f)
2260 {
2261         unsigned long dot = 0;
2262         struct obj_section *sec;
2263
2264         /* Finalize the positions of the sections relative to one another.  */
2265
2266         for (sec = f->load_order; sec; sec = sec->load_next) {
2267                 ElfW(Addr) align;
2268
2269                 align = sec->header.sh_addralign;
2270                 if (align && (dot & (align - 1)))
2271                         dot = (dot | (align - 1)) + 1;
2272
2273                 sec->header.sh_addr = dot;
2274                 dot += sec->header.sh_size;
2275         }
2276
2277         return dot;
2278 }
2279
2280 int obj_relocate(struct obj_file *f, ElfW(Addr) base)
2281 {
2282         int i, n = f->header.e_shnum;
2283         int ret = 1;
2284
2285         /* Finalize the addresses of the sections.  */
2286
2287         f->baseaddr = base;
2288         for (i = 0; i < n; ++i)
2289                 f->sections[i]->header.sh_addr += base;
2290
2291         /* And iterate over all of the relocations.  */
2292
2293         for (i = 0; i < n; ++i) {
2294                 struct obj_section *relsec, *symsec, *targsec, *strsec;
2295                 ElfW(RelM) * rel, *relend;
2296                 ElfW(Sym) * symtab;
2297                 const char *strtab;
2298
2299                 relsec = f->sections[i];
2300                 if (relsec->header.sh_type != SHT_RELM)
2301                         continue;
2302
2303                 symsec = f->sections[relsec->header.sh_link];
2304                 targsec = f->sections[relsec->header.sh_info];
2305                 strsec = f->sections[symsec->header.sh_link];
2306
2307                 rel = (ElfW(RelM) *) relsec->contents;
2308                 relend = rel + (relsec->header.sh_size / sizeof(ElfW(RelM)));
2309                 symtab = (ElfW(Sym) *) symsec->contents;
2310                 strtab = (const char *) strsec->contents;
2311
2312                 for (; rel < relend; ++rel) {
2313                         ElfW(Addr) value = 0;
2314                         struct obj_symbol *intsym = NULL;
2315                         unsigned long symndx;
2316                         ElfW(Sym) * extsym = 0;
2317                         const char *errmsg;
2318
2319                         /* Attempt to find a value to use for this relocation.  */
2320
2321                         symndx = ELFW(R_SYM) (rel->r_info);
2322                         if (symndx) {
2323                                 /* Note we've already checked for undefined symbols.  */
2324
2325                                 extsym = &symtab[symndx];
2326                                 if (ELFW(ST_BIND) (extsym->st_info) == STB_LOCAL) {
2327                                         /* Local symbols we look up in the local table to be sure
2328                                            we get the one that is really intended.  */
2329                                         intsym = f->local_symtab[symndx];
2330                                 } else {
2331                                         /* Others we look up in the hash table.  */
2332                                         const char *name;
2333                                         if (extsym->st_name)
2334                                                 name = strtab + extsym->st_name;
2335                                         else
2336                                                 name = f->sections[extsym->st_shndx]->name;
2337                                         intsym = obj_find_symbol(f, name);
2338                                 }
2339
2340                                 value = obj_symbol_final_value(f, intsym);
2341                                 intsym->referenced = 1;
2342                         }
2343 #if SHT_RELM == SHT_RELA
2344 #if defined(__alpha__) && defined(AXP_BROKEN_GAS)
2345                         /* Work around a nasty GAS bug, that is fixed as of 2.7.0.9.  */
2346                         if (!extsym || !extsym->st_name ||
2347                                 ELFW(ST_BIND) (extsym->st_info) != STB_LOCAL)
2348 #endif
2349                                 value += rel->r_addend;
2350 #endif
2351
2352                         /* Do it! */
2353                         switch (arch_apply_relocation
2354                                         (f, targsec, symsec, intsym, rel, value)) {
2355                         case obj_reloc_ok:
2356                                 break;
2357
2358                         case obj_reloc_overflow:
2359                                 errmsg = "Relocation overflow";
2360                                 goto bad_reloc;
2361                         case obj_reloc_dangerous:
2362                                 errmsg = "Dangerous relocation";
2363                                 goto bad_reloc;
2364                         case obj_reloc_unhandled:
2365                                 errmsg = "Unhandled relocation";
2366                           bad_reloc:
2367                                 if (extsym) {
2368                                         errorMsg("%s of type %ld for %s\n", errmsg,
2369                                                         (long) ELFW(R_TYPE) (rel->r_info),
2370                                                         strtab + extsym->st_name);
2371                                 } else {
2372                                         errorMsg("%s of type %ld\n", errmsg,
2373                                                         (long) ELFW(R_TYPE) (rel->r_info));
2374                                 }
2375                                 ret = 0;
2376                                 break;
2377                         }
2378                 }
2379         }
2380
2381         /* Finally, take care of the patches.  */
2382
2383         if (f->string_patches) {
2384                 struct obj_string_patch *p;
2385                 struct obj_section *strsec;
2386                 ElfW(Addr) strsec_base;
2387                 strsec = obj_find_section(f, ".kstrtab");
2388                 strsec_base = strsec->header.sh_addr;
2389
2390                 for (p = f->string_patches; p; p = p->next) {
2391                         struct obj_section *targsec = f->sections[p->reloc_secidx];
2392                         *(ElfW(Addr) *) (targsec->contents + p->reloc_offset)
2393                                 = strsec_base + p->string_offset;
2394                 }
2395         }
2396
2397         if (f->symbol_patches) {
2398                 struct obj_symbol_patch *p;
2399
2400                 for (p = f->symbol_patches; p; p = p->next) {
2401                         struct obj_section *targsec = f->sections[p->reloc_secidx];
2402                         *(ElfW(Addr) *) (targsec->contents + p->reloc_offset)
2403                                 = obj_symbol_final_value(f, p->sym);
2404                 }
2405         }
2406
2407         return ret;
2408 }
2409
2410 int obj_create_image(struct obj_file *f, char *image)
2411 {
2412         struct obj_section *sec;
2413         ElfW(Addr) base = f->baseaddr;
2414
2415         for (sec = f->load_order; sec; sec = sec->load_next) {
2416                 char *secimg;
2417
2418                 if (sec->header.sh_size == 0)
2419                         continue;
2420
2421                 secimg = image + (sec->header.sh_addr - base);
2422
2423                 /* Note that we allocated data for NOBITS sections earlier.  */
2424                 memcpy(secimg, sec->contents, sec->header.sh_size);
2425         }
2426
2427         return 1;
2428 }
2429
2430 /*======================================================================*/
2431
2432 struct obj_file *obj_load(FILE * fp)
2433 {
2434         struct obj_file *f;
2435         ElfW(Shdr) * section_headers;
2436         int shnum, i;
2437         char *shstrtab;
2438
2439         /* Read the file header.  */
2440
2441         f = arch_new_file();
2442         memset(f, 0, sizeof(*f));
2443         f->symbol_cmp = strcmp;
2444         f->symbol_hash = obj_elf_hash;
2445         f->load_order_search_start = &f->load_order;
2446
2447         fseek(fp, 0, SEEK_SET);
2448         if (fread(&f->header, sizeof(f->header), 1, fp) != 1) {
2449                 errorMsg("error reading ELF header: %s", strerror(errno));
2450                 return NULL;
2451         }
2452
2453         if (f->header.e_ident[EI_MAG0] != ELFMAG0
2454                 || f->header.e_ident[EI_MAG1] != ELFMAG1
2455                 || f->header.e_ident[EI_MAG2] != ELFMAG2
2456                 || f->header.e_ident[EI_MAG3] != ELFMAG3) {
2457                 errorMsg("not an ELF file\n");
2458                 return NULL;
2459         }
2460         if (f->header.e_ident[EI_CLASS] != ELFCLASSM
2461                 || f->header.e_ident[EI_DATA] != ELFDATAM
2462                 || f->header.e_ident[EI_VERSION] != EV_CURRENT
2463                 || !MATCH_MACHINE(f->header.e_machine)) {
2464                 errorMsg("ELF file not for this architecture\n");
2465                 return NULL;
2466         }
2467         if (f->header.e_type != ET_REL) {
2468                 errorMsg("ELF file not a relocatable object\n");
2469                 return NULL;
2470         }
2471
2472         /* Read the section headers.  */
2473
2474         if (f->header.e_shentsize != sizeof(ElfW(Shdr))) {
2475                 errorMsg("section header size mismatch: %lu != %lu\n",
2476                                 (unsigned long) f->header.e_shentsize,
2477                                 (unsigned long) sizeof(ElfW(Shdr)));
2478                 return NULL;
2479         }
2480
2481         shnum = f->header.e_shnum;
2482         f->sections = xmalloc(sizeof(struct obj_section *) * shnum);
2483         memset(f->sections, 0, sizeof(struct obj_section *) * shnum);
2484
2485         section_headers = alloca(sizeof(ElfW(Shdr)) * shnum);
2486         fseek(fp, f->header.e_shoff, SEEK_SET);
2487         if (fread(section_headers, sizeof(ElfW(Shdr)), shnum, fp) != shnum) {
2488                 errorMsg("error reading ELF section headers: %s", strerror(errno));
2489                 return NULL;
2490         }
2491
2492         /* Read the section data.  */
2493
2494         for (i = 0; i < shnum; ++i) {
2495                 struct obj_section *sec;
2496
2497                 f->sections[i] = sec = arch_new_section();
2498                 memset(sec, 0, sizeof(*sec));
2499
2500                 sec->header = section_headers[i];
2501                 sec->idx = i;
2502
2503                 switch (sec->header.sh_type) {
2504                 case SHT_NULL:
2505                 case SHT_NOTE:
2506                 case SHT_NOBITS:
2507                         /* ignore */
2508                         break;
2509
2510                 case SHT_PROGBITS:
2511                 case SHT_SYMTAB:
2512                 case SHT_STRTAB:
2513                 case SHT_RELM:
2514                         if (sec->header.sh_size > 0) {
2515                                 sec->contents = xmalloc(sec->header.sh_size);
2516                                 fseek(fp, sec->header.sh_offset, SEEK_SET);
2517                                 if (fread(sec->contents, sec->header.sh_size, 1, fp) != 1) {
2518                                         errorMsg("error reading ELF section data: %s", strerror(errno));
2519                                         return NULL;
2520                                 }
2521                         } else {
2522                                 sec->contents = NULL;
2523                         }
2524                         break;
2525
2526 #if SHT_RELM == SHT_REL
2527                 case SHT_RELA:
2528                         errorMsg("RELA relocations not supported on this architecture\n");
2529                         return NULL;
2530 #else
2531                 case SHT_REL:
2532                         errorMsg("REL relocations not supported on this architecture\n");
2533                         return NULL;
2534 #endif
2535
2536                 default:
2537                         if (sec->header.sh_type >= SHT_LOPROC) {
2538                                 /* Assume processor specific section types are debug
2539                                    info and can safely be ignored.  If this is ever not
2540                                    the case (Hello MIPS?), don't put ifdefs here but
2541                                    create an arch_load_proc_section().  */
2542                                 break;
2543                         }
2544
2545                         errorMsg("can't handle sections of type %ld\n",
2546                                         (long) sec->header.sh_type);
2547                         return NULL;
2548                 }
2549         }
2550
2551         /* Do what sort of interpretation as needed by each section.  */
2552
2553         shstrtab = f->sections[f->header.e_shstrndx]->contents;
2554
2555         for (i = 0; i < shnum; ++i) {
2556                 struct obj_section *sec = f->sections[i];
2557                 sec->name = shstrtab + sec->header.sh_name;
2558         }
2559
2560         for (i = 0; i < shnum; ++i) {
2561                 struct obj_section *sec = f->sections[i];
2562
2563                 if (sec->header.sh_flags & SHF_ALLOC)
2564                         obj_insert_section_load_order(f, sec);
2565
2566                 switch (sec->header.sh_type) {
2567                 case SHT_SYMTAB:
2568                         {
2569                                 unsigned long nsym, j;
2570                                 char *strtab;
2571                                 ElfW(Sym) * sym;
2572
2573                                 if (sec->header.sh_entsize != sizeof(ElfW(Sym))) {
2574                                         errorMsg("symbol size mismatch: %lu != %lu\n",
2575                                                         (unsigned long) sec->header.sh_entsize,
2576                                                         (unsigned long) sizeof(ElfW(Sym)));
2577                                         return NULL;
2578                                 }
2579
2580                                 nsym = sec->header.sh_size / sizeof(ElfW(Sym));
2581                                 strtab = f->sections[sec->header.sh_link]->contents;
2582                                 sym = (ElfW(Sym) *) sec->contents;
2583
2584                                 /* Allocate space for a table of local symbols.  */
2585                                 j = f->local_symtab_size = sec->header.sh_info;
2586                                 f->local_symtab = xmalloc(j *=
2587                                                                                   sizeof(struct obj_symbol *));
2588                                 memset(f->local_symtab, 0, j);
2589
2590                                 /* Insert all symbols into the hash table.  */
2591                                 for (j = 1, ++sym; j < nsym; ++j, ++sym) {
2592                                         const char *name;
2593                                         if (sym->st_name)
2594                                                 name = strtab + sym->st_name;
2595                 else
2596                                                 name = f->sections[sym->st_shndx]->name;
2597
2598                                         obj_add_symbol(f, name, j, sym->st_info, sym->st_shndx,
2599                                                                    sym->st_value, sym->st_size);
2600                 }
2601         }
2602                         break;
2603
2604                 case SHT_RELM:
2605                         if (sec->header.sh_entsize != sizeof(ElfW(RelM))) {
2606                                 errorMsg("relocation entry size mismatch: %lu != %lu\n",
2607                                                 (unsigned long) sec->header.sh_entsize,
2608                                                 (unsigned long) sizeof(ElfW(RelM)));
2609                                 return NULL;
2610                         }
2611                         break;
2612                 }
2613         }
2614
2615         return f;
2616 }
2617
2618 static void hide_special_symbols(struct obj_file *f)
2619 {
2620         static const char *const specials[] = {
2621                 "cleanup_module",
2622                 "init_module",
2623                 "kernel_version",
2624                 NULL
2625         };
2626
2627         struct obj_symbol *sym;
2628         const char *const *p;
2629
2630         for (p = specials; *p; ++p)
2631                 if ((sym = obj_find_symbol(f, *p)) != NULL)
2632                         sym->info =
2633                                 ELFW(ST_INFO) (STB_LOCAL, ELFW(ST_TYPE) (sym->info));
2634 }
2635
2636
2637
2638 extern int insmod_main( int argc, char **argv)
2639 {
2640         int k_crcs;
2641         int k_new_syscalls;
2642         int len;
2643         char *tmp;
2644         unsigned long m_size;
2645         ElfW(Addr) m_addr;
2646         FILE *fp;
2647         struct obj_file *f;
2648         char m_name[BUFSIZ + 1] = "\0";
2649         int exit_status = FALSE;
2650         int m_has_modinfo;
2651 #ifdef BB_FEATURE_INSMOD_VERSION_CHECKING
2652         int k_version;
2653         char k_strversion[STRVERSIONLEN];
2654         char m_strversion[STRVERSIONLEN];
2655         int m_version;
2656         int m_crcs;
2657 #endif
2658
2659
2660         if (argc <= 1) {
2661                 usage(insmod_usage);
2662         }
2663
2664         /* Parse any options */
2665         while (--argc > 0 && **(++argv) == '-') {
2666                 while (*(++(*argv))) {
2667                         switch (**argv) {
2668                         case 'f':                       /* force loading */
2669                                 flag_force_load = 1;
2670                                 break;
2671                         case 'k':                       /* module loaded by kerneld, auto-cleanable */
2672                                 flag_autoclean = 1;
2673                                 break;
2674                         case 'v':                       /* verbose output */
2675                                 flag_verbose = 1;
2676                                 break;
2677                         case 'x':                       /* do not export externs */
2678                                 flag_export = 0;
2679                                 break;
2680                         default:
2681                                 usage(insmod_usage);
2682                         }
2683                 }
2684         }
2685
2686         if (argc <= 0) {
2687                 usage(insmod_usage);
2688         }
2689         /* Grab the module name */
2690         if ((tmp = strrchr(*argv, '/')) != NULL) {
2691                 tmp++;
2692         } else {
2693                 tmp = *argv;
2694         }
2695         len = strlen(tmp);
2696
2697         if (len > 2 && tmp[len - 2] == '.' && tmp[len - 1] == 'o')
2698                 len -= 2;
2699         memcpy(m_name, tmp, len);
2700         strcpy(m_fullName, m_name);
2701         strcat(m_fullName, ".o");
2702
2703         /* Get a filedesc for the module */
2704         if ((fp = fopen(*argv, "r")) == NULL) {
2705                 /* Hmpf.  Could not open it. Search through _PATH_MODULES to find a module named m_name */
2706                 if (recursiveAction(_PATH_MODULES, TRUE, FALSE, FALSE,
2707                                                         findNamedModule, 0, m_fullName) == TRUE) 
2708                 {
2709                         if (m_filename[0] == '\0'
2710                                 || ((fp = fopen(m_filename, "r")) == NULL)) 
2711                         {
2712                                 errorMsg("No module named '%s' found in '%s'\n", m_fullName, _PATH_MODULES);
2713                                 exit(FALSE);
2714                         }
2715                 }
2716         } else
2717                 memcpy(m_filename, *argv, strlen(*argv));
2718
2719
2720         if ((f = obj_load(fp)) == NULL) {
2721                 perror("Could not load the module\n");
2722                 exit(FALSE);
2723         }
2724
2725         if (get_modinfo_value(f, "kernel_version") == NULL)
2726                 m_has_modinfo = 0;
2727         else
2728                 m_has_modinfo = 1;
2729
2730 #ifdef BB_FEATURE_INSMOD_VERSION_CHECKING
2731         /* Version correspondence?  */
2732
2733         k_version = get_kernel_version(k_strversion);
2734         if (m_has_modinfo) {
2735                 m_version = new_get_module_version(f, m_strversion);
2736         } else {
2737                 m_version = old_get_module_version(f, m_strversion);
2738                 if (m_version == -1) {
2739                         errorMsg("couldn't find the kernel version the module was "
2740                                         "compiled for\n");
2741                         goto out;
2742                 }
2743         }
2744
2745         if (strncmp(k_strversion, m_strversion, STRVERSIONLEN) != 0) {
2746                 if (flag_force_load) {
2747                         errorMsg("Warning: kernel-module version mismatch\n"
2748                                         "\t%s was compiled for kernel version %s\n"
2749                                         "\twhile this kernel is version %s\n",
2750                                         m_filename, m_strversion, k_strversion);
2751                 } else {
2752                         errorMsg("kernel-module version mismatch\n"
2753                                         "\t%s was compiled for kernel version %s\n"
2754                                         "\twhile this kernel is version %s.\n",
2755                                         m_filename, m_strversion, k_strversion);
2756                         goto out;
2757                 }
2758         }
2759         k_crcs = 0;
2760 #endif                                                  /* BB_FEATURE_INSMOD_VERSION_CHECKING */
2761
2762         k_new_syscalls = !query_module(NULL, 0, NULL, 0, NULL);
2763
2764         if (k_new_syscalls) {
2765 #ifdef BB_FEATURE_INSMOD_NEW_KERNEL
2766                 if (!new_get_kernel_symbols())
2767                         goto out;
2768                 k_crcs = new_is_kernel_checksummed();
2769 #else
2770                 errorMsg("Not configured to support new kernels\n");
2771                 goto out;
2772 #endif
2773         } else {
2774 #ifdef BB_FEATURE_INSMOD_OLD_KERNEL
2775                 if (!old_get_kernel_symbols())
2776                         goto out;
2777                 k_crcs = old_is_kernel_checksummed();
2778 #else
2779                 errorMsg("Not configured to support old kernels\n");
2780                 goto out;
2781 #endif
2782         }
2783
2784 #ifdef BB_FEATURE_INSMOD_VERSION_CHECKING
2785         if (m_has_modinfo)
2786                 m_crcs = new_is_module_checksummed(f);
2787         else
2788                 m_crcs = old_is_module_checksummed(f);
2789
2790         if (m_crcs != k_crcs)
2791                 obj_set_symbol_compare(f, ncv_strcmp, ncv_symbol_hash);
2792 #endif                                                  /* BB_FEATURE_INSMOD_VERSION_CHECKING */
2793
2794         /* Let the module know about the kernel symbols.  */
2795         add_kernel_symbols(f);
2796
2797         /* Allocate common symbols, symbol tables, and string tables.  */
2798
2799         if (k_new_syscalls 
2800                 ? !new_create_this_module(f, m_name)
2801                 : !old_create_mod_use_count(f)) 
2802         {
2803                 goto out;
2804         }
2805
2806         if (!obj_check_undefineds(f)) {
2807                 goto out;
2808         }
2809         obj_allocate_commons(f);
2810
2811         if (optind < argc) {
2812                 if (m_has_modinfo
2813                         ? !new_process_module_arguments(f, argc - optind, argv + optind) 
2814                         : !old_process_module_arguments(f, argc - optind, argv + optind)) 
2815                 {
2816                         goto out;
2817                 }
2818         }
2819
2820         arch_create_got(f);
2821         hide_special_symbols(f);
2822
2823         if (k_new_syscalls)
2824                 new_create_module_ksymtab(f);
2825
2826         /* Find current size of the module */
2827         m_size = obj_load_size(f);
2828
2829
2830         errno = 0;
2831         m_addr = create_module(m_name, m_size);
2832         switch (errno) {
2833         case 0:
2834                 break;
2835         case EEXIST:
2836                 errorMsg("A module named %s already exists\n", m_name);
2837                 goto out;
2838         case ENOMEM:
2839                 errorMsg("Can't allocate kernel memory for module; needed %lu bytes\n",
2840                                 m_size);
2841                 goto out;
2842         default:
2843                 errorMsg("create_module: %s: %s", m_name, strerror(errno));
2844                 goto out;
2845         }
2846
2847         if (!obj_relocate(f, m_addr)) {
2848                 delete_module(m_name);
2849                 goto out;
2850         }
2851
2852         if (k_new_syscalls 
2853                 ? !new_init_module(m_name, f, m_size)
2854                 : !old_init_module(m_name, f, m_size)) 
2855         {
2856                 delete_module(m_name);
2857                 goto out;
2858         }
2859
2860         exit_status = TRUE;
2861
2862 out:
2863         fclose(fp);
2864         return(exit_status);
2865 }