1/* vi: set sw=4 ts=4: */
2/*
3 * Mini insmod implementation for busybox
4 *
5 * This version of insmod supports x86, ARM, SH3/4, powerpc, m68k,
6 * and MIPS.
7 *
8 *
9 * Copyright (C) 1999,2000,2001 by Lineo, inc.
10 * Written by Erik Andersen <andersen@lineo.com>
11 * and Ron Alder <alder@lineo.com>
12 *
13 * Modified by Bryan Rittmeyer <bryan@ixiacom.com> to support SH4
14 * and (theoretically) SH3. I have only tested SH4 in little endian mode.
15 *
16 * Modified by Alcove, Julien Gaulmin <julien.gaulmin@alcove.fr> and
17 * Nicolas Ferre <nicolas.ferre@alcove.fr> to support ARM7TDMI.  Only
18 * very minor changes required to also work with StrongArm and presumably
19 * all ARM based systems.
20 *
21 * Magnus Damm <damm@opensource.se> added PowerPC support 20-Feb-2001.
22 *   PowerPC specific code stolen from modutils-2.3.16,
23 *   written by Paul Mackerras, Copyright 1996, 1997 Linux International.
24 *   I've only tested the code on mpc8xx platforms in big-endian mode.
25 *   Did some cleanup and added BB_USE_xxx_ENTRIES...
26 *
27 * Quinn Jensen <jensenq@lineo.com> added MIPS support 23-Feb-2001.
28 *   based on modutils-2.4.2
29 *   MIPS specific support for Elf loading and relocation.
30 *   Copyright 1996, 1997 Linux International.
31 *   Contributed by Ralf Baechle <ralf@gnu.ai.mit.edu>
32 *
33 * Based almost entirely on the Linux modutils-2.3.11 implementation.
34 *   Copyright 1996, 1997 Linux International.
35 *   New implementation contributed by Richard Henderson <rth@tamu.edu>
36 *   Based on original work by Bjorn Ekwall <bj0rn@blox.se>
37 *   Restructured (and partly rewritten) by:
38 *   Bj�rn Ekwall <bj0rn@blox.se> February 1999
39 *
40 * This program is free software; you can redistribute it and/or modify
41 * it under the terms of the GNU General Public License as published by
42 * the Free Software Foundation; either version 2 of the License, or
43 * (at your option) any later version.
44 *
45 * This program is distributed in the hope that it will be useful,
46 * but WITHOUT ANY WARRANTY; without even the implied warranty of
47 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
48 * General Public License for more details.
49 *
50 * You should have received a copy of the GNU General Public License
51 * along with this program; if not, write to the Free Software
52 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
53 *
54 */
55
56#include <stdlib.h>
57#include <stdio.h>
58#include <stddef.h>
59#include <errno.h>
60#include <unistd.h>
61#include <dirent.h>
62#include <ctype.h>
63#include <assert.h>
64#include <string.h>
65#include <getopt.h>
66#include <sys/utsname.h>
67#include "busybox.h"
68
69#ifdef BB_FEATURE_NEW_MODULE_INTERFACE
70# define new_sys_init_module	init_module
71#else
72# define old_sys_init_module	init_module
73#endif
74
75#ifdef BB_FEATURE_INSMOD_LOADINKMEM
76#define LOADBITS 0
77#else
78#define LOADBITS 1
79#endif
80
81#if defined(__powerpc__)
82#define BB_USE_PLT_ENTRIES
83#define BB_PLT_ENTRY_SIZE 16
84#endif
85
86#if defined(__arm__)
87#define BB_USE_PLT_ENTRIES
88#define BB_PLT_ENTRY_SIZE 8
89#define BB_USE_GOT_ENTRIES
90#define BB_GOT_ENTRY_SIZE 8
91#endif
92
93#if defined(__sh__)
94#define BB_USE_GOT_ENTRIES
95#define BB_GOT_ENTRY_SIZE 4
96#endif
97
98#if defined(__i386__)
99#define BB_USE_GOT_ENTRIES
100#define BB_GOT_ENTRY_SIZE 4
101#endif
102
103#if defined(__mips__)
104// neither used
105#endif
106
107//----------------------------------------------------------------------------
108//--------modutils module.h, lines 45-242
109//----------------------------------------------------------------------------
110
111/* Definitions for the Linux module syscall interface.
112   Copyright 1996, 1997 Linux International.
113
114   Contributed by Richard Henderson <rth@tamu.edu>
115
116   This file is part of the Linux modutils.
117
118   This program is free software; you can redistribute it and/or modify it
119   under the terms of the GNU General Public License as published by the
120   Free Software Foundation; either version 2 of the License, or (at your
121   option) any later version.
122
123   This program is distributed in the hope that it will be useful, but
124   WITHOUT ANY WARRANTY; without even the implied warranty of
125   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
126   General Public License for more details.
127
128   You should have received a copy of the GNU General Public License
129   along with this program; if not, write to the Free Software Foundation,
130   Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
131
132
133#ifndef MODUTILS_MODULE_H
134static const int MODUTILS_MODULE_H = 1;
135
136#ident "$Id: insmod.c,v 1.1.1.1 2008/10/15 03:28:32 james26_jang Exp $"
137
138/* This file contains the structures used by the 2.0 and 2.1 kernels.
139   We do not use the kernel headers directly because we do not wish
140   to be dependant on a particular kernel version to compile insmod.  */
141
142
143/*======================================================================*/
144/* The structures used by Linux 2.0.  */
145
146/* The symbol format used by get_kernel_syms(2).  */
147struct old_kernel_sym
148{
149  unsigned long value;
150  char name[60];
151};
152
153struct old_module_ref
154{
155  unsigned long module;		/* kernel addresses */
156  unsigned long next;
157};
158
159struct old_module_symbol
160{
161  unsigned long addr;
162  unsigned long name;
163};
164
165struct old_symbol_table
166{
167  int size;			/* total, including string table!!! */
168  int n_symbols;
169  int n_refs;
170  struct old_module_symbol symbol[0]; /* actual size defined by n_symbols */
171  struct old_module_ref ref[0];	/* actual size defined by n_refs */
172};
173
174struct old_mod_routines
175{
176  unsigned long init;
177  unsigned long cleanup;
178};
179
180struct old_module
181{
182  unsigned long next;
183  unsigned long ref;		/* the list of modules that refer to me */
184  unsigned long symtab;
185  unsigned long name;
186  int size;			/* size of module in pages */
187  unsigned long addr;		/* address of module */
188  int state;
189  unsigned long cleanup;	/* cleanup routine */
190};
191
192/* Sent to init_module(2) or'ed into the code size parameter.  */
193static const int OLD_MOD_AUTOCLEAN = 0x40000000; /* big enough, but no sign problems... */
194
195int get_kernel_syms(struct old_kernel_sym *);
196int old_sys_init_module(const char *name, char *code, unsigned codesize,
197			struct old_mod_routines *, struct old_symbol_table *);
198
199/*======================================================================*/
200/* For sizeof() which are related to the module platform and not to the
201   environment isnmod is running in, use sizeof_xx instead of sizeof(xx).  */
202
203#define tgt_sizeof_char		sizeof(char)
204#define tgt_sizeof_short	sizeof(short)
205#define tgt_sizeof_int		sizeof(int)
206#define tgt_sizeof_long		sizeof(long)
207#define tgt_sizeof_char_p	sizeof(char *)
208#define tgt_sizeof_void_p	sizeof(void *)
209#define tgt_long		long
210
211#if defined(__sparc__) && !defined(__sparc_v9__) && defined(ARCH_sparc64)
212#undef tgt_sizeof_long
213#undef tgt_sizeof_char_p
214#undef tgt_sizeof_void_p
215#undef tgt_long
216static const int tgt_sizeof_long = 8;
217static const int tgt_sizeof_char_p = 8;
218static const int tgt_sizeof_void_p = 8;
219#define tgt_long		long long
220#endif
221
222/*======================================================================*/
223/* The structures used in Linux 2.1.  */
224
225/* Note: new_module_symbol does not use tgt_long intentionally */
226struct new_module_symbol
227{
228  unsigned long value;
229  unsigned long name;
230};
231
232struct new_module_persist;
233
234struct new_module_ref
235{
236  unsigned tgt_long dep;		/* kernel addresses */
237  unsigned tgt_long ref;
238  unsigned tgt_long next_ref;
239};
240
241struct new_module
242{
243  unsigned tgt_long size_of_struct;	/* == sizeof(module) */
244  unsigned tgt_long next;
245  unsigned tgt_long name;
246  unsigned tgt_long size;
247
248  tgt_long usecount;
249  unsigned tgt_long flags;		/* AUTOCLEAN et al */
250
251  unsigned nsyms;
252  unsigned ndeps;
253
254  unsigned tgt_long syms;
255  unsigned tgt_long deps;
256  unsigned tgt_long refs;
257  unsigned tgt_long init;
258  unsigned tgt_long cleanup;
259  unsigned tgt_long ex_table_start;
260  unsigned tgt_long ex_table_end;
261#ifdef __alpha__
262  unsigned tgt_long gp;
263#endif
264  /* Everything after here is extension.  */
265  unsigned tgt_long persist_start;
266  unsigned tgt_long persist_end;
267  unsigned tgt_long can_unload;
268  unsigned tgt_long runsize;
269#ifdef BB_FEATURE_NEW_MODULE_INTERFACE
270  const char *kallsyms_start;     /* All symbols for kernel debugging */
271  const char *kallsyms_end;
272  const char *archdata_start;     /* arch specific data for module */
273  const char *archdata_end;
274  const char *kernel_data;        /* Reserved for kernel internal use */
275#endif
276};
277
278#define ARCHDATA_SEC_NAME "__archdata"
279#define KALLSYMS_SEC_NAME "__kallsyms"
280
281
282struct new_module_info
283{
284  unsigned long addr;
285  unsigned long size;
286  unsigned long flags;
287	   long usecount;
288};
289
290/* Bits of module.flags.  */
291static const int NEW_MOD_RUNNING = 1;
292static const int NEW_MOD_DELETED = 2;
293static const int NEW_MOD_AUTOCLEAN = 4;
294static const int NEW_MOD_VISITED = 8;
295static const int NEW_MOD_USED_ONCE = 16;
296
297int new_sys_init_module(const char *name, const struct new_module *);
298int query_module(const char *name, int which, void *buf, size_t bufsize,
299		 size_t *ret);
300
301/* Values for query_module's which.  */
302
303static const int QM_MODULES = 1;
304static const int QM_DEPS = 2;
305static const int QM_REFS = 3;
306static const int QM_SYMBOLS = 4;
307static const int QM_INFO = 5;
308
309/*======================================================================*/
310/* The system calls unchanged between 2.0 and 2.1.  */
311
312unsigned long create_module(const char *, size_t);
313int delete_module(const char *);
314
315
316#endif /* module.h */
317
318//----------------------------------------------------------------------------
319//--------end of modutils module.h
320//----------------------------------------------------------------------------
321
322
323
324//----------------------------------------------------------------------------
325//--------modutils obj.h, lines 253-462
326//----------------------------------------------------------------------------
327
328/* Elf object file loading and relocation routines.
329   Copyright 1996, 1997 Linux International.
330
331   Contributed by Richard Henderson <rth@tamu.edu>
332
333   This file is part of the Linux modutils.
334
335   This program is free software; you can redistribute it and/or modify it
336   under the terms of the GNU General Public License as published by the
337   Free Software Foundation; either version 2 of the License, or (at your
338   option) any later version.
339
340   This program is distributed in the hope that it will be useful, but
341   WITHOUT ANY WARRANTY; without even the implied warranty of
342   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
343   General Public License for more details.
344
345   You should have received a copy of the GNU General Public License
346   along with this program; if not, write to the Free Software Foundation,
347   Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
348
349
350#ifndef MODUTILS_OBJ_H
351static const int MODUTILS_OBJ_H = 1;
352
353#ident "$Id: insmod.c,v 1.1.1.1 2008/10/15 03:28:32 james26_jang Exp $"
354
355/* The relocatable object is manipulated using elfin types.  */
356
357#include <stdio.h>
358#include <elf.h>
359
360
361/* Machine-specific elf macros for i386 et al.  */
362
363/* the SH changes have only been tested on the SH4 in =little endian= mode */
364/* I'm not sure about big endian, so let's warn: */
365
366#if (defined(__SH4__) || defined(__SH3__)) && defined(__BIG_ENDIAN__)
367#error insmod.c may require changes for use on big endian SH4/SH3
368#endif
369
370/* it may or may not work on the SH1/SH2... So let's error on those
371   also */
372#if (defined(__sh__) && (!(defined(__SH3__) || defined(__SH4__))))
373#error insmod.c may require changes for non-SH3/SH4 use
374#endif
375
376#define ELFCLASSM	ELFCLASS32
377
378#if (defined(__mc68000__))
379#define ELFDATAM	ELFDATA2MSB
380#endif
381
382
383
384#if defined(__sh__)
385
386#define MATCH_MACHINE(x) (x == EM_SH)
387#define SHT_RELM	SHT_RELA
388#define Elf32_RelM	Elf32_Rela
389#define ELFDATAM	ELFDATA2LSB
390
391#elif defined(__arm__)
392
393#define MATCH_MACHINE(x) (x == EM_ARM)
394#define SHT_RELM	SHT_REL
395#define Elf32_RelM	Elf32_Rel
396#define ELFDATAM	ELFDATA2LSB
397
398#elif defined(__powerpc__)
399
400#define MATCH_MACHINE(x) (x == EM_PPC)
401#define SHT_RELM	SHT_RELA
402#define Elf32_RelM	Elf32_Rela
403#define ELFDATAM    ELFDATA2MSB
404
405#elif defined(__mips__)
406
407/* Account for ELF spec changes.  */
408#ifndef EM_MIPS_RS3_LE
409#ifdef EM_MIPS_RS4_BE
410#define EM_MIPS_RS3_LE	EM_MIPS_RS4_BE
411#else
412#define EM_MIPS_RS3_LE	10
413#endif
414#endif /* !EM_MIPS_RS3_LE */
415
416#define MATCH_MACHINE(x) (x == EM_MIPS || x == EM_MIPS_RS3_LE)
417#define SHT_RELM	SHT_REL
418#define Elf32_RelM	Elf32_Rel
419#ifdef __MIPSEB__
420#define ELFDATAM        ELFDATA2MSB
421#endif
422#ifdef __MIPSEL__
423#define ELFDATAM        ELFDATA2LSB
424#endif
425
426#elif defined(__i386__)
427
428/* presumably we can use these for anything but the SH and ARM*/
429/* this is the previous behavior, but it does result in
430   insmod.c being broken on anything except i386 */
431#ifndef EM_486
432#define MATCH_MACHINE(x)  (x == EM_386)
433#else
434#define MATCH_MACHINE(x)  (x == EM_386 || x == EM_486)
435#endif
436
437#define SHT_RELM	SHT_REL
438#define Elf32_RelM	Elf32_Rel
439#define ELFDATAM	ELFDATA2LSB
440
441#elif defined(__mc68000__)
442
443#define MATCH_MACHINE(x)	(x == EM_68K)
444#define SHT_RELM			SHT_RELA
445#define Elf32_RelM			Elf32_Rela
446
447#else
448#error Sorry, but insmod.c does not yet support this architecture...
449#endif
450
451#ifndef ElfW
452# if ELFCLASSM == ELFCLASS32
453#  define ElfW(x)  Elf32_ ## x
454#  define ELFW(x)  ELF32_ ## x
455# else
456#  define ElfW(x)  Elf64_ ## x
457#  define ELFW(x)  ELF64_ ## x
458# endif
459#endif
460
461/* For some reason this is missing from libc5.  */
462#ifndef ELF32_ST_INFO
463# define ELF32_ST_INFO(bind, type)       (((bind) << 4) + ((type) & 0xf))
464#endif
465
466#ifndef ELF64_ST_INFO
467# define ELF64_ST_INFO(bind, type)       (((bind) << 4) + ((type) & 0xf))
468#endif
469
470struct obj_string_patch;
471struct obj_symbol_patch;
472
473struct obj_section
474{
475  ElfW(Shdr) header;
476  const char *name;
477  char *contents;
478  struct obj_section *load_next;
479  int idx;
480};
481
482struct obj_symbol
483{
484  struct obj_symbol *next;	/* hash table link */
485  const char *name;
486  unsigned long value;
487  unsigned long size;
488  int secidx;			/* the defining section index/module */
489  int info;
490  int ksymidx;			/* for export to the kernel symtab */
491  int referenced;		/* actually used in the link */
492};
493
494/* Hardcode the hash table size.  We shouldn't be needing so many
495   symbols that we begin to degrade performance, and we get a big win
496   by giving the compiler a constant divisor.  */
497
498#define HASH_BUCKETS  521
499
500struct obj_file
501{
502  ElfW(Ehdr) header;
503  ElfW(Addr) baseaddr;
504  struct obj_section **sections;
505  struct obj_section *load_order;
506  struct obj_section **load_order_search_start;
507  struct obj_string_patch *string_patches;
508  struct obj_symbol_patch *symbol_patches;
509  int (*symbol_cmp)(const char *, const char *);
510  unsigned long (*symbol_hash)(const char *);
511  unsigned long local_symtab_size;
512  struct obj_symbol **local_symtab;
513  struct obj_symbol *symtab[HASH_BUCKETS];
514};
515
516enum obj_reloc
517{
518  obj_reloc_ok,
519  obj_reloc_overflow,
520  obj_reloc_dangerous,
521  obj_reloc_unhandled
522};
523
524struct obj_string_patch
525{
526  struct obj_string_patch *next;
527  int reloc_secidx;
528  ElfW(Addr) reloc_offset;
529  ElfW(Addr) string_offset;
530};
531
532struct obj_symbol_patch
533{
534  struct obj_symbol_patch *next;
535  int reloc_secidx;
536  ElfW(Addr) reloc_offset;
537  struct obj_symbol *sym;
538};
539
540
541/* Generic object manipulation routines.  */
542
543static unsigned long obj_elf_hash(const char *);
544
545static unsigned long obj_elf_hash_n(const char *, unsigned long len);
546
547static struct obj_symbol *obj_find_symbol (struct obj_file *f,
548					 const char *name);
549
550static ElfW(Addr) obj_symbol_final_value(struct obj_file *f,
551				  struct obj_symbol *sym);
552
553#ifdef BB_FEATURE_INSMOD_VERSION_CHECKING
554static void obj_set_symbol_compare(struct obj_file *f,
555			    int (*cmp)(const char *, const char *),
556			    unsigned long (*hash)(const char *));
557#endif
558
559static struct obj_section *obj_find_section (struct obj_file *f,
560					   const char *name);
561
562static void obj_insert_section_load_order (struct obj_file *f,
563				    struct obj_section *sec);
564
565static struct obj_section *obj_create_alloced_section (struct obj_file *f,
566						const char *name,
567						unsigned long align,
568						unsigned long size);
569
570static struct obj_section *obj_create_alloced_section_first (struct obj_file *f,
571						      const char *name,
572						      unsigned long align,
573						      unsigned long size);
574
575static void *obj_extend_section (struct obj_section *sec, unsigned long more);
576
577static int obj_string_patch(struct obj_file *f, int secidx, ElfW(Addr) offset,
578		     const char *string);
579
580static int obj_symbol_patch(struct obj_file *f, int secidx, ElfW(Addr) offset,
581		     struct obj_symbol *sym);
582
583static int obj_check_undefineds(struct obj_file *f);
584
585static void obj_allocate_commons(struct obj_file *f);
586
587static unsigned long obj_load_size (struct obj_file *f);
588
589static int obj_relocate (struct obj_file *f, ElfW(Addr) base);
590
591static struct obj_file *obj_load(FILE *f, int loadprogbits);
592
593static int obj_create_image (struct obj_file *f, char *image);
594
595/* Architecture specific manipulation routines.  */
596
597static struct obj_file *arch_new_file (void);
598
599static struct obj_section *arch_new_section (void);
600
601static struct obj_symbol *arch_new_symbol (void);
602
603static enum obj_reloc arch_apply_relocation (struct obj_file *f,
604				      struct obj_section *targsec,
605				      struct obj_section *symsec,
606				      struct obj_symbol *sym,
607				      ElfW(RelM) *rel, ElfW(Addr) value);
608
609static int arch_create_got (struct obj_file *f);
610
611static int arch_init_module (struct obj_file *f, struct new_module *);
612
613#endif /* obj.h */
614//----------------------------------------------------------------------------
615//--------end of modutils obj.h
616//----------------------------------------------------------------------------
617
618
619
620
621
622#define _PATH_MODULES	"/lib/modules"
623static const int STRVERSIONLEN = 32;
624
625/*======================================================================*/
626
627static int flag_force_load = 0;
628static int flag_autoclean = 0;
629static int flag_verbose = 0;
630static int flag_export = 1;
631
632
633/*======================================================================*/
634
635/* previously, these were named i386_* but since we could be
636   compiling for the sh, I've renamed them to the more general
637   arch_* These structures are the same between the x86 and SH,
638   and we can't support anything else right now anyway. In the
639   future maybe they should be #if defined'd */
640
641/* Done ;-) */
642
643
644
645#if defined(BB_USE_PLT_ENTRIES)
646struct arch_plt_entry
647{
648  int offset;
649  int allocated:1;
650  int inited:1;                /* has been set up */
651};
652#endif
653
654#if defined(BB_USE_GOT_ENTRIES)
655struct arch_got_entry {
656	int offset;
657	unsigned offset_done:1;
658	unsigned reloc_done:1;
659};
660#endif
661
662#if defined(__mips__)
663struct mips_hi16
664{
665  struct mips_hi16 *next;
666  Elf32_Addr *addr;
667  Elf32_Addr value;
668};
669#endif
670
671struct arch_file {
672	struct obj_file root;
673#if defined(BB_USE_PLT_ENTRIES)
674	struct obj_section *plt;
675#endif
676#if defined(BB_USE_GOT_ENTRIES)
677	struct obj_section *got;
678#endif
679#if defined(__mips__)
680	struct mips_hi16 *mips_hi16_list;
681#endif
682};
683
684struct arch_symbol {
685	struct obj_symbol root;
686#if defined(BB_USE_PLT_ENTRIES)
687	struct arch_plt_entry pltent;
688#endif
689#if defined(BB_USE_GOT_ENTRIES)
690	struct arch_got_entry gotent;
691#endif
692};
693
694
695struct external_module {
696	const char *name;
697	ElfW(Addr) addr;
698	int used;
699	size_t nsyms;
700	struct new_module_symbol *syms;
701};
702
703static struct new_module_symbol *ksyms;
704static size_t nksyms;
705
706static struct external_module *ext_modules;
707static int n_ext_modules;
708static int n_ext_modules_used;
709extern int delete_module(const char *);
710
711static char m_filename[FILENAME_MAX + 1];
712static char m_fullName[FILENAME_MAX + 1];
713
714
715
716/*======================================================================*/
717
718
719static int check_module_name_match(const char *filename, struct stat *statbuf,
720						   void *userdata)
721{
722	char *fullname = (char *) userdata;
723
724	if (fullname[0] == '\0')
725		return (FALSE);
726	else {
727		char *tmp, *tmp1 = strdup(filename);
728		tmp = get_last_path_component(tmp1);
729		if (strcmp(tmp, fullname) == 0) {
730			free(tmp1);
731			/* Stop searching if we find a match */
732			safe_strncpy(m_filename, filename, sizeof(m_filename));
733			return (TRUE);
734		}
735		free(tmp1);
736	}
737	return (FALSE);
738}
739
740
741/*======================================================================*/
742
743static struct obj_file *arch_new_file(void)
744{
745	struct arch_file *f;
746	f = xmalloc(sizeof(*f));
747
748#if defined(BB_USE_PLT_ENTRIES)
749	f->plt = NULL;
750#endif
751#if defined(BB_USE_GOT_ENTRIES)
752	f->got = NULL;
753#endif
754#if defined(__mips__)
755	f->mips_hi16_list = NULL;
756#endif
757
758	return &f->root;
759}
760
761static struct obj_section *arch_new_section(void)
762{
763	return xmalloc(sizeof(struct obj_section));
764}
765
766static struct obj_symbol *arch_new_symbol(void)
767{
768	struct arch_symbol *sym;
769	sym = xmalloc(sizeof(*sym));
770
771#if defined(BB_USE_PLT_ENTRIES)
772	memset(&sym->pltent, 0, sizeof(sym->pltent));
773#endif
774#if defined(BB_USE_GOT_ENTRIES)
775	memset(&sym->gotent, 0, sizeof(sym->gotent));
776#endif
777
778	return &sym->root;
779}
780
781static enum obj_reloc
782arch_apply_relocation(struct obj_file *f,
783					  struct obj_section *targsec,
784					  struct obj_section *symsec,
785					  struct obj_symbol *sym,
786				      ElfW(RelM) *rel, ElfW(Addr) v)
787{
788	struct arch_file *ifile = (struct arch_file *) f;
789#if !(defined(__mips__))
790	struct arch_symbol *isym = (struct arch_symbol *) sym;
791#endif
792
793	ElfW(Addr) *loc = (ElfW(Addr) *) (targsec->contents + rel->r_offset);
794	ElfW(Addr) dot = targsec->header.sh_addr + rel->r_offset;
795#if defined(BB_USE_GOT_ENTRIES)
796	ElfW(Addr) got = ifile->got ? ifile->got->header.sh_addr : 0;
797#endif
798#if defined(BB_USE_PLT_ENTRIES)
799	ElfW(Addr) plt = ifile->plt ? ifile->plt->header.sh_addr : 0;
800	struct arch_plt_entry *pe;
801	unsigned long *ip;
802#endif
803	enum obj_reloc ret = obj_reloc_ok;
804
805	switch (ELF32_R_TYPE(rel->r_info)) {
806
807/* even though these constants seem to be the same for
808   the i386 and the sh, we "#if define" them for clarity
809   and in case that ever changes */
810#if defined(__sh__)
811	case R_SH_NONE:
812#elif defined(__arm__)
813	case R_ARM_NONE:
814#elif defined(__i386__)
815	case R_386_NONE:
816#elif defined(__mc68000__)
817	case R_68K_NONE:
818#elif defined(__powerpc__)
819	case R_PPC_NONE:
820#elif defined(__mips__)
821	case R_MIPS_NONE:
822#endif
823		break;
824
825#if defined(__sh__)
826	case R_SH_DIR32:
827#elif defined(__arm__)
828	case R_ARM_ABS32:
829#elif defined(__i386__)
830	case R_386_32:
831#elif defined(__mc68000__)
832	case R_68K_32:
833#elif defined(__powerpc__)
834	case R_PPC_ADDR32:
835#elif defined(__mips__)
836	case R_MIPS_32:
837#endif
838		*loc += v;
839		break;
840#if defined(__mc68000__)
841    case R_68K_8:
842		if (v > 0xff)
843		ret = obj_reloc_overflow;
844		*(char *)loc = v;
845		break;
846    case R_68K_16:
847		if (v > 0xffff)
848		ret = obj_reloc_overflow;
849		*(short *)loc = v;
850		break;
851#endif /* __mc68000__   */
852
853#if defined(__powerpc__)
854	case R_PPC_ADDR16_HA:
855		*(unsigned short *)loc = (v + 0x8000) >> 16;
856		break;
857
858	case R_PPC_ADDR16_HI:
859		*(unsigned short *)loc = v >> 16;
860		break;
861
862	case R_PPC_ADDR16_LO:
863		*(unsigned short *)loc = v;
864		break;
865#endif
866
867#if defined(__mips__)
868	case R_MIPS_26:
869		if (v % 4)
870			ret = obj_reloc_dangerous;
871		if ((v & 0xf0000000) != ((dot + 4) & 0xf0000000))
872			ret = obj_reloc_overflow;
873		*loc =
874		    (*loc & ~0x03ffffff) | ((*loc + (v >> 2)) &
875					    0x03ffffff);
876		break;
877
878	case R_MIPS_HI16:
879		{
880			struct mips_hi16 *n;
881
882			/* We cannot relocate this one now because we don't know the value
883			   of the carry we need to add.  Save the information, and let LO16
884			   do the actual relocation.  */
885			n = (struct mips_hi16 *) xmalloc(sizeof *n);
886			n->addr = loc;
887			n->value = v;
888			n->next = ifile->mips_hi16_list;
889			ifile->mips_hi16_list = n;
890	       		break;
891		}
892
893	case R_MIPS_LO16:
894		{
895			unsigned long insnlo = *loc;
896			Elf32_Addr val, vallo;
897
898			/* Sign extend the addend we extract from the lo insn.  */
899			vallo = ((insnlo & 0xffff) ^ 0x8000) - 0x8000;
900
901			if (ifile->mips_hi16_list != NULL) {
902				struct mips_hi16 *l;
903
904				l = ifile->mips_hi16_list;
905				while (l != NULL) {
906					struct mips_hi16 *next;
907					unsigned long insn;
908
909					/* The value for the HI16 had best be the same. */
910					assert(v == l->value);
911
912					/* Do the HI16 relocation.  Note that we actually don't
913					   need to know anything about the LO16 itself, except where
914					   to find the low 16 bits of the addend needed by the LO16.  */
915					insn = *l->addr;
916					val =
917					    ((insn & 0xffff) << 16) +
918					    vallo;
919					val += v;
920
921					/* Account for the sign extension that will happen in the
922					   low bits.  */
923					val =
924					    ((val >> 16) +
925					     ((val & 0x8000) !=
926					      0)) & 0xffff;
927
928					insn = (insn & ~0xffff) | val;
929					*l->addr = insn;
930
931					next = l->next;
932					free(l);
933					l = next;
934				}
935
936				ifile->mips_hi16_list = NULL;
937			}
938
939			/* Ok, we're done with the HI16 relocs.  Now deal with the LO16.  */
940			val = v + vallo;
941			insnlo = (insnlo & ~0xffff) | (val & 0xffff);
942			*loc = insnlo;
943			break;
944		}
945#endif
946
947#if defined(__arm__)
948#elif defined(__sh__)
949        case R_SH_REL32:
950		*loc += v - dot;
951		break;
952#elif defined(__i386__)
953	case R_386_PLT32:
954	case R_386_PC32:
955		*loc += v - dot;
956		break;
957#elif defined(__mc68000__)
958    case R_68K_PC8:
959		v -= dot;
960		if ((Elf32_Sword)v > 0x7f || (Elf32_Sword)v < -(Elf32_Sword)0x80)
961		ret = obj_reloc_overflow;
962		*(char *)loc = v;
963    break;
964		case R_68K_PC16:
965		v -= dot;
966		if ((Elf32_Sword)v > 0x7fff || (Elf32_Sword)v < -(Elf32_Sword)0x8000)
967		ret = obj_reloc_overflow;
968		*(short *)loc = v;
969		break;
970    case R_68K_PC32:
971		*(int *)loc = v - dot;
972		break;
973#elif defined(__powerpc__)
974	case R_PPC_REL32:
975		*loc = v - dot;
976		break;
977#endif
978
979#if defined(__sh__)
980        case R_SH_PLT32:
981                *loc = v - dot;
982                break;
983#elif defined(__i386__)
984#endif
985
986#if defined(BB_USE_PLT_ENTRIES)
987
988#if defined(__arm__)
989    case R_ARM_PC24:
990    case R_ARM_PLT32:
991#endif
992#if defined(__powerpc__)
993	case R_PPC_REL24:
994#endif
995      /* find the plt entry and initialize it if necessary */
996      assert(isym != NULL);
997
998      pe = (struct arch_plt_entry*) &isym->pltent;
999
1000      if (! pe->inited) {
1001	  	ip = (unsigned long *) (ifile->plt->contents + pe->offset);
1002
1003		/* generate some machine code */
1004
1005#if defined(__arm__)
1006	  	ip[0] = 0xe51ff004;			/* ldr pc,[pc,#-4] */
1007	  	ip[1] = v;				/* sym@ */
1008#endif
1009#if defined(__powerpc__)
1010	  ip[0] = 0x3d600000 + ((v + 0x8000) >> 16);  /* lis r11,sym@ha */
1011	  ip[1] = 0x396b0000 + (v & 0xffff);	      /* addi r11,r11,sym@l */
1012	  ip[2] = 0x7d6903a6;			      /* mtctr r11 */
1013	  ip[3] = 0x4e800420;			      /* bctr */
1014#endif
1015	  	pe->inited = 1;
1016	  }
1017
1018      /* relative distance to target */
1019      v -= dot;
1020      /* if the target is too far away.... */
1021      if ((int)v < -0x02000000 || (int)v >= 0x02000000) {
1022	    /* go via the plt */
1023	    v = plt + pe->offset - dot;
1024	  }
1025      if (v & 3)
1026	    ret = obj_reloc_dangerous;
1027
1028      /* merge the offset into the instruction. */
1029#if defined(__arm__)
1030      /* Convert to words. */
1031      v >>= 2;
1032
1033      *loc = (*loc & ~0x00ffffff) | ((v + *loc) & 0x00ffffff);
1034#endif
1035#if defined(__powerpc__)
1036      *loc = (*loc & ~0x03fffffc) | (v & 0x03fffffc);
1037#endif
1038      break;
1039#endif /* BB_USE_PLT_ENTRIES */
1040
1041#if defined(__arm__)
1042#elif defined(__sh__)
1043        case R_SH_GLOB_DAT:
1044        case R_SH_JMP_SLOT:
1045               	*loc = v;
1046                break;
1047#elif defined(__i386__)
1048	case R_386_GLOB_DAT:
1049	case R_386_JMP_SLOT:
1050		*loc = v;
1051		break;
1052#elif defined(__mc68000__)
1053	case R_68K_GLOB_DAT:
1054	case R_68K_JMP_SLOT:
1055		*loc = v;
1056		break;
1057#endif
1058
1059#if defined(__arm__)
1060#elif defined(__sh__)
1061        case R_SH_RELATIVE:
1062	        *loc += f->baseaddr + rel->r_addend;
1063                break;
1064#elif defined(__i386__)
1065        case R_386_RELATIVE:
1066		*loc += f->baseaddr;
1067		break;
1068#elif defined(__mc68000__)
1069    case R_68K_RELATIVE:
1070    	*(int *)loc += f->baseaddr;
1071    	break;
1072#endif
1073
1074#if defined(BB_USE_GOT_ENTRIES)
1075
1076#if !defined(__68k__)
1077#if defined(__sh__)
1078        case R_SH_GOTPC:
1079#elif defined(__arm__)
1080    case R_ARM_GOTPC:
1081#elif defined(__i386__)
1082	case R_386_GOTPC:
1083#endif
1084		assert(got != 0);
1085#if defined(__sh__)
1086		*loc += got - dot + rel->r_addend;;
1087#elif defined(__i386__) || defined(__arm__) || defined(__m68k_)
1088		*loc += got - dot;
1089#endif
1090		break;
1091#endif // __68k__
1092
1093#if defined(__sh__)
1094	case R_SH_GOT32:
1095#elif defined(__arm__)
1096	case R_ARM_GOT32:
1097#elif defined(__i386__)
1098	case R_386_GOT32:
1099#elif defined(__mc68000__)
1100	case R_68K_GOT32:
1101#endif
1102		assert(isym != NULL);
1103        /* needs an entry in the .got: set it, once */
1104		if (!isym->gotent.reloc_done) {
1105			isym->gotent.reloc_done = 1;
1106			*(ElfW(Addr) *) (ifile->got->contents + isym->gotent.offset) = v;
1107		}
1108        /* make the reloc with_respect_to_.got */
1109#if defined(__sh__)
1110		*loc += isym->gotent.offset + rel->r_addend;
1111#elif defined(__i386__) || defined(__arm__) || defined(__mc68000__)
1112		*loc += isym->gotent.offset;
1113#endif
1114		break;
1115
1116    /* address relative to the got */
1117#if !defined(__mc68000__)
1118#if defined(__sh__)
1119	case R_SH_GOTOFF:
1120#elif defined(__arm__)
1121	case R_ARM_GOTOFF:
1122#elif defined(__i386__)
1123	case R_386_GOTOFF:
1124#elif defined(__mc68000__)
1125	case R_68K_GOTOFF:
1126#endif
1127		assert(got != 0);
1128		*loc += v - got;
1129		break;
1130#endif // __mc68000__
1131
1132#endif /* BB_USE_GOT_ENTRIES */
1133
1134	default:
1135        printf("Warning: unhandled reloc %d\n",(int)ELF32_R_TYPE(rel->r_info));
1136		ret = obj_reloc_unhandled;
1137		break;
1138	}
1139
1140	return ret;
1141}
1142
1143static int arch_create_got(struct obj_file *f)
1144{
1145#if defined(BB_USE_GOT_ENTRIES) || defined(BB_USE_PLT_ENTRIES)
1146	struct arch_file *ifile = (struct arch_file *) f;
1147	int i;
1148#if defined(BB_USE_GOT_ENTRIES)
1149	int got_offset = 0, gotneeded = 0;
1150#endif
1151#if defined(BB_USE_PLT_ENTRIES)
1152	int plt_offset = 0, pltneeded = 0;
1153#endif
1154    struct obj_section *relsec, *symsec, *strsec;
1155	ElfW(RelM) *rel, *relend;
1156	ElfW(Sym) *symtab, *extsym;
1157	const char *strtab, *name;
1158	struct arch_symbol *intsym;
1159
1160	for (i = 0; i < f->header.e_shnum; ++i) {
1161		relsec = f->sections[i];
1162		if (relsec->header.sh_type != SHT_RELM)
1163			continue;
1164
1165		symsec = f->sections[relsec->header.sh_link];
1166		strsec = f->sections[symsec->header.sh_link];
1167
1168		rel = (ElfW(RelM) *) relsec->contents;
1169		relend = rel + (relsec->header.sh_size / sizeof(ElfW(RelM)));
1170		symtab = (ElfW(Sym) *) symsec->contents;
1171		strtab = (const char *) strsec->contents;
1172
1173		for (; rel < relend; ++rel) {
1174			extsym = &symtab[ELF32_R_SYM(rel->r_info)];
1175
1176			switch (ELF32_R_TYPE(rel->r_info)) {
1177#if defined(__arm__)
1178			case R_ARM_GOT32:
1179				break;
1180#elif defined(__sh__)
1181			case R_SH_GOT32:
1182				break;
1183#elif defined(__i386__)
1184			case R_386_GOT32:
1185				break;
1186#elif defined(__mc68000__)
1187			case R_68K_GOT32:
1188				break;
1189#endif
1190
1191#if defined(__powerpc__)
1192			case R_PPC_REL24:
1193				pltneeded = 1;
1194				break;
1195#endif
1196
1197#if defined(__arm__)
1198			case R_ARM_PC24:
1199			case R_ARM_PLT32:
1200				pltneeded = 1;
1201				break;
1202
1203			case R_ARM_GOTPC:
1204			case R_ARM_GOTOFF:
1205				gotneeded = 1;
1206				if (got_offset == 0)
1207					got_offset = 4;
1208#elif defined(__sh__)
1209			case R_SH_GOTPC:
1210			case R_SH_GOTOFF:
1211				gotneeded = 1;
1212#elif defined(__i386__)
1213			case R_386_GOTPC:
1214			case R_386_GOTOFF:
1215				gotneeded = 1;
1216#endif
1217
1218			default:
1219				continue;
1220			}
1221
1222			if (extsym->st_name != 0) {
1223				name = strtab + extsym->st_name;
1224			} else {
1225				name = f->sections[extsym->st_shndx]->name;
1226			}
1227			intsym = (struct arch_symbol *) obj_find_symbol(f, name);
1228#if defined(BB_USE_GOT_ENTRIES)
1229			if (!intsym->gotent.offset_done) {
1230				intsym->gotent.offset_done = 1;
1231				intsym->gotent.offset = got_offset;
1232				got_offset += BB_GOT_ENTRY_SIZE;
1233			}
1234#endif
1235#if defined(BB_USE_PLT_ENTRIES)
1236			if (pltneeded && intsym->pltent.allocated == 0) {
1237				intsym->pltent.allocated = 1;
1238				intsym->pltent.offset = plt_offset;
1239				plt_offset += BB_PLT_ENTRY_SIZE;
1240				intsym->pltent.inited = 0;
1241				pltneeded = 0;
1242			}
1243#endif
1244			}
1245		}
1246
1247#if defined(BB_USE_GOT_ENTRIES)
1248	if (got_offset) {
1249		struct obj_section* myrelsec = obj_find_section(f, ".got");
1250
1251		if (myrelsec) {
1252			obj_extend_section(myrelsec, got_offset);
1253		} else {
1254			myrelsec = obj_create_alloced_section(f, ".got",
1255							    BB_GOT_ENTRY_SIZE,
1256							    got_offset);
1257			assert(myrelsec);
1258		}
1259
1260		ifile->got = myrelsec;
1261	}
1262#endif
1263
1264#if defined(BB_USE_PLT_ENTRIES)
1265	if (plt_offset)
1266		ifile->plt = obj_create_alloced_section(f, ".plt",
1267							BB_PLT_ENTRY_SIZE,
1268							plt_offset);
1269#endif
1270#endif
1271	return 1;
1272}
1273
1274static int arch_init_module(struct obj_file *f, struct new_module *mod)
1275{
1276	return 1;
1277}
1278
1279
1280/*======================================================================*/
1281
1282/* Standard ELF hash function.  */
1283static inline unsigned long obj_elf_hash_n(const char *name, unsigned long n)
1284{
1285	unsigned long h = 0;
1286	unsigned long g;
1287	unsigned char ch;
1288
1289	while (n > 0) {
1290		ch = *name++;
1291		h = (h << 4) + ch;
1292		if ((g = (h & 0xf0000000)) != 0) {
1293			h ^= g >> 24;
1294			h &= ~g;
1295		}
1296		n--;
1297	}
1298	return h;
1299}
1300
1301static unsigned long obj_elf_hash(const char *name)
1302{
1303	return obj_elf_hash_n(name, strlen(name));
1304}
1305
1306#ifdef BB_FEATURE_INSMOD_VERSION_CHECKING
1307/* Get the kernel version in the canonical integer form.  */
1308
1309static int get_kernel_version(char str[STRVERSIONLEN])
1310{
1311	struct utsname uts_info;
1312	int kv;
1313
1314	if (uname(&uts_info) < 0)
1315		return -1;
1316	strncpy(str, uts_info.release, STRVERSIONLEN);
1317
1318	kv = get_kernel_revision();
1319	if(kv==0)
1320		return -1;
1321}
1322
1323/* String comparison for non-co-versioned kernel and module.  */
1324
1325static int ncv_strcmp(const char *a, const char *b)
1326{
1327	size_t alen = strlen(a), blen = strlen(b);
1328
1329	if (blen == alen + 10 && b[alen] == '_' && b[alen + 1] == 'R')
1330		return strncmp(a, b, alen);
1331	else if (alen == blen + 10 && a[blen] == '_' && a[blen + 1] == 'R')
1332		return strncmp(a, b, blen);
1333	else
1334		return strcmp(a, b);
1335}
1336
1337/* String hashing for non-co-versioned kernel and module.  Here
1338   we are simply forced to drop the crc from the hash.  */
1339
1340static unsigned long ncv_symbol_hash(const char *str)
1341{
1342	size_t len = strlen(str);
1343	if (len > 10 && str[len - 10] == '_' && str[len - 9] == 'R')
1344		len -= 10;
1345	return obj_elf_hash_n(str, len);
1346}
1347
1348static void
1349obj_set_symbol_compare(struct obj_file *f,
1350					   int (*cmp) (const char *, const char *),
1351					   unsigned long (*hash) (const char *))
1352{
1353	if (cmp)
1354		f->symbol_cmp = cmp;
1355	if (hash) {
1356		struct obj_symbol *tmptab[HASH_BUCKETS], *sym, *next;
1357		int i;
1358
1359		f->symbol_hash = hash;
1360
1361		memcpy(tmptab, f->symtab, sizeof(tmptab));
1362		memset(f->symtab, 0, sizeof(f->symtab));
1363
1364		for (i = 0; i < HASH_BUCKETS; ++i)
1365			for (sym = tmptab[i]; sym; sym = next) {
1366				unsigned long h = hash(sym->name) % HASH_BUCKETS;
1367				next = sym->next;
1368				sym->next = f->symtab[h];
1369				f->symtab[h] = sym;
1370			}
1371	}
1372}
1373
1374#endif							/* BB_FEATURE_INSMOD_VERSION_CHECKING */
1375
1376static struct obj_symbol *
1377obj_add_symbol(struct obj_file *f, const char *name,
1378								  unsigned long symidx, int info,
1379								  int secidx, ElfW(Addr) value,
1380								  unsigned long size)
1381{
1382	struct obj_symbol *sym;
1383	unsigned long hash = f->symbol_hash(name) % HASH_BUCKETS;
1384	int n_type = ELFW(ST_TYPE) (info);
1385	int n_binding = ELFW(ST_BIND) (info);
1386
1387	for (sym = f->symtab[hash]; sym; sym = sym->next)
1388		if (f->symbol_cmp(sym->name, name) == 0) {
1389			int o_secidx = sym->secidx;
1390			int o_info = sym->info;
1391			int o_type = ELFW(ST_TYPE) (o_info);
1392			int o_binding = ELFW(ST_BIND) (o_info);
1393
1394			/* A redefinition!  Is it legal?  */
1395
1396			if (secidx == SHN_UNDEF)
1397				return sym;
1398			else if (o_secidx == SHN_UNDEF)
1399				goto found;
1400			else if (n_binding == STB_GLOBAL && o_binding == STB_LOCAL) {
1401				/* Cope with local and global symbols of the same name
1402				   in the same object file, as might have been created
1403				   by ld -r.  The only reason locals are now seen at this
1404				   level at all is so that we can do semi-sensible things
1405				   with parameters.  */
1406
1407				struct obj_symbol *nsym, **p;
1408
1409				nsym = arch_new_symbol();
1410				nsym->next = sym->next;
1411				nsym->ksymidx = -1;
1412
1413				/* Excise the old (local) symbol from the hash chain.  */
1414				for (p = &f->symtab[hash]; *p != sym; p = &(*p)->next)
1415					continue;
1416				*p = sym = nsym;
1417				goto found;
1418			} else if (n_binding == STB_LOCAL) {
1419				/* Another symbol of the same name has already been defined.
1420				   Just add this to the local table.  */
1421				sym = arch_new_symbol();
1422				sym->next = NULL;
1423				sym->ksymidx = -1;
1424				f->local_symtab[symidx] = sym;
1425				goto found;
1426			} else if (n_binding == STB_WEAK)
1427				return sym;
1428			else if (o_binding == STB_WEAK)
1429				goto found;
1430			/* Don't unify COMMON symbols with object types the programmer
1431			   doesn't expect.  */
1432			else if (secidx == SHN_COMMON
1433					 && (o_type == STT_NOTYPE || o_type == STT_OBJECT))
1434				return sym;
1435			else if (o_secidx == SHN_COMMON
1436					 && (n_type == STT_NOTYPE || n_type == STT_OBJECT))
1437				goto found;
1438			else {
1439				/* Don't report an error if the symbol is coming from
1440				   the kernel or some external module.  */
1441				if (secidx <= SHN_HIRESERVE)
1442					error_msg("%s multiply defined", name);
1443				return sym;
1444			}
1445		}
1446
1447	/* Completely new symbol.  */
1448	sym = arch_new_symbol();
1449	sym->next = f->symtab[hash];
1450	f->symtab[hash] = sym;
1451	sym->ksymidx = -1;
1452
1453	if (ELFW(ST_BIND)(info) == STB_LOCAL && symidx != -1) {
1454		if (symidx >= f->local_symtab_size)
1455			error_msg("local symbol %s with index %ld exceeds local_symtab_size %ld",
1456					name, (long) symidx, (long) f->local_symtab_size);
1457		else
1458			f->local_symtab[symidx] = sym;
1459	}
1460
1461  found:
1462	sym->name = name;
1463	sym->value = value;
1464	sym->size = size;
1465	sym->secidx = secidx;
1466	sym->info = info;
1467
1468	return sym;
1469}
1470
1471static struct obj_symbol *
1472obj_find_symbol(struct obj_file *f, const char *name)
1473{
1474	struct obj_symbol *sym;
1475	unsigned long hash = f->symbol_hash(name) % HASH_BUCKETS;
1476
1477	for (sym = f->symtab[hash]; sym; sym = sym->next)
1478		if (f->symbol_cmp(sym->name, name) == 0)
1479			return sym;
1480
1481	return NULL;
1482}
1483
1484static ElfW(Addr)
1485	obj_symbol_final_value(struct obj_file * f, struct obj_symbol * sym)
1486{
1487	if (sym) {
1488		if (sym->secidx >= SHN_LORESERVE)
1489			return sym->value;
1490
1491		return sym->value + f->sections[sym->secidx]->header.sh_addr;
1492	} else {
1493		/* As a special case, a NULL sym has value zero.  */
1494		return 0;
1495	}
1496}
1497
1498static struct obj_section *obj_find_section(struct obj_file *f, const char *name)
1499{
1500	int i, n = f->header.e_shnum;
1501
1502	for (i = 0; i < n; ++i)
1503		if (strcmp(f->sections[i]->name, name) == 0)
1504			return f->sections[i];
1505
1506	return NULL;
1507}
1508
1509static int obj_load_order_prio(struct obj_section *a)
1510{
1511	unsigned long af, ac;
1512
1513	af = a->header.sh_flags;
1514
1515	ac = 0;
1516	if (a->name[0] != '.' || strlen(a->name) != 10 ||
1517		strcmp(a->name + 5, ".init"))
1518		ac |= 32;
1519	if (af & SHF_ALLOC)
1520		ac |= 16;
1521	if (!(af & SHF_WRITE))
1522		ac |= 8;
1523	if (af & SHF_EXECINSTR)
1524		ac |= 4;
1525	if (a->header.sh_type != SHT_NOBITS)
1526		ac |= 2;
1527
1528	return ac;
1529}
1530
1531static void
1532obj_insert_section_load_order(struct obj_file *f, struct obj_section *sec)
1533{
1534	struct obj_section **p;
1535	int prio = obj_load_order_prio(sec);
1536	for (p = f->load_order_search_start; *p; p = &(*p)->load_next)
1537		if (obj_load_order_prio(*p) < prio)
1538			break;
1539	sec->load_next = *p;
1540	*p = sec;
1541}
1542
1543static struct obj_section *obj_create_alloced_section(struct obj_file *f,
1544											   const char *name,
1545											   unsigned long align,
1546											   unsigned long size)
1547{
1548	int newidx = f->header.e_shnum++;
1549	struct obj_section *sec;
1550
1551	f->sections = xrealloc(f->sections, (newidx + 1) * sizeof(sec));
1552	f->sections[newidx] = sec = arch_new_section();
1553
1554	memset(sec, 0, sizeof(*sec));
1555	sec->header.sh_type = SHT_PROGBITS;
1556	sec->header.sh_flags = SHF_WRITE | SHF_ALLOC;
1557	sec->header.sh_size = size;
1558	sec->header.sh_addralign = align;
1559	sec->name = name;
1560	sec->idx = newidx;
1561	if (size)
1562		sec->contents = xmalloc(size);
1563
1564	obj_insert_section_load_order(f, sec);
1565
1566	return sec;
1567}
1568
1569static struct obj_section *obj_create_alloced_section_first(struct obj_file *f,
1570													 const char *name,
1571													 unsigned long align,
1572													 unsigned long size)
1573{
1574	int newidx = f->header.e_shnum++;
1575	struct obj_section *sec;
1576
1577	f->sections = xrealloc(f->sections, (newidx + 1) * sizeof(sec));
1578	f->sections[newidx] = sec = arch_new_section();
1579
1580	memset(sec, 0, sizeof(*sec));
1581	sec->header.sh_type = SHT_PROGBITS;
1582	sec->header.sh_flags = SHF_WRITE | SHF_ALLOC;
1583	sec->header.sh_size = size;
1584	sec->header.sh_addralign = align;
1585	sec->name = name;
1586	sec->idx = newidx;
1587	if (size)
1588		sec->contents = xmalloc(size);
1589
1590	sec->load_next = f->load_order;
1591	f->load_order = sec;
1592	if (f->load_order_search_start == &f->load_order)
1593		f->load_order_search_start = &sec->load_next;
1594
1595	return sec;
1596}
1597
1598static void *obj_extend_section(struct obj_section *sec, unsigned long more)
1599{
1600	unsigned long oldsize = sec->header.sh_size;
1601	if (more) {
1602		sec->contents = xrealloc(sec->contents, sec->header.sh_size += more);
1603	}
1604	return sec->contents + oldsize;
1605}
1606
1607
1608/* Conditionally add the symbols from the given symbol set to the
1609   new module.  */
1610
1611static int
1612add_symbols_from(
1613				 struct obj_file *f,
1614				 int idx, struct new_module_symbol *syms, size_t nsyms)
1615{
1616	struct new_module_symbol *s;
1617	size_t i;
1618	int used = 0;
1619
1620	for (i = 0, s = syms; i < nsyms; ++i, ++s) {
1621
1622		/* Only add symbols that are already marked external.  If we
1623		   override locals we may cause problems for argument initialization.
1624		   We will also create a false dependency on the module.  */
1625		struct obj_symbol *sym;
1626
1627		sym = obj_find_symbol(f, (char *) s->name);
1628		if (sym && !ELFW(ST_BIND) (sym->info) == STB_LOCAL) {
1629			sym = obj_add_symbol(f, (char *) s->name, -1,
1630								 ELFW(ST_INFO) (STB_GLOBAL, STT_NOTYPE),
1631								 idx, s->value, 0);
1632			/* Did our symbol just get installed?  If so, mark the
1633			   module as "used".  */
1634			if (sym->secidx == idx)
1635				used = 1;
1636		}
1637	}
1638
1639	return used;
1640}
1641
1642static void add_kernel_symbols(struct obj_file *f)
1643{
1644	struct external_module *m;
1645	int i, nused = 0;
1646
1647	/* Add module symbols first.  */
1648
1649	for (i = 0, m = ext_modules; i < n_ext_modules; ++i, ++m)
1650		if (m->nsyms
1651			&& add_symbols_from(f, SHN_HIRESERVE + 2 + i, m->syms,
1652								m->nsyms)) m->used = 1, ++nused;
1653
1654	n_ext_modules_used = nused;
1655
1656	/* And finally the symbols from the kernel proper.  */
1657
1658	if (nksyms)
1659		add_symbols_from(f, SHN_HIRESERVE + 1, ksyms, nksyms);
1660}
1661
1662#if defined(__mips__)
1663int
1664arch_archdata (struct obj_file *f, struct obj_section *archdata_sec)
1665{
1666  struct archdata {
1667    unsigned tgt_long __start___dbe_table;
1668    unsigned tgt_long __stop___dbe_table;
1669  } *ad;
1670  struct obj_section *sec;
1671
1672  if (archdata_sec->contents)
1673    free(archdata_sec->contents);
1674  archdata_sec->header.sh_size = 0;
1675  sec = obj_find_section(f, "__dbe_table");
1676  if (sec) {
1677    ad = (struct archdata *) (archdata_sec->contents) = xmalloc(sizeof(*ad));
1678    memset(ad, 0, sizeof(*ad));
1679    archdata_sec->header.sh_size = sizeof(*ad);
1680    ad->__start___dbe_table = sec->header.sh_addr;
1681    ad->__stop___dbe_table = sec->header.sh_addr + sec->header.sh_size;
1682  }
1683
1684  return 0;
1685}
1686#else
1687#define arch_archdata(f, sec) (0)
1688#endif
1689
1690/* Add an arch data section if the arch wants it. */
1691static int add_archdata(struct obj_file *f,
1692			struct obj_section **sec)
1693{
1694	size_t i;
1695
1696	*sec = NULL;
1697	/* Add an empty archdata section to the module if necessary */
1698	for (i = 0; i < f->header.e_shnum; ++i) {
1699		if (strcmp(f->sections[i]->name, ARCHDATA_SEC_NAME) == 0) {
1700			*sec = f->sections[i];
1701			break;
1702		}
1703	    }
1704	if (!*sec)
1705		*sec = obj_create_alloced_section(f, ARCHDATA_SEC_NAME, 16, 0);
1706
1707	/* Size and populate archdata */
1708	if (arch_archdata(f, *sec))
1709		return(1);
1710	return 0;
1711}
1712
1713static char *get_modinfo_value(struct obj_file *f, const char *key)
1714{
1715	struct obj_section *sec;
1716	char *p, *v, *n, *ep;
1717	size_t klen = strlen(key);
1718
1719	sec = obj_find_section(f, ".modinfo");
1720	if (sec == NULL)
1721		return NULL;
1722	p = sec->contents;
1723	ep = p + sec->header.sh_size;
1724	while (p < ep) {
1725		v = strchr(p, '=');
1726		n = strchr(p, '\0');
1727		if (v) {
1728			if (p + klen == v && strncmp(p, key, klen) == 0)
1729				return v + 1;
1730		} else {
1731			if (p + klen == n && strcmp(p, key) == 0)
1732				return n;
1733		}
1734		p = n + 1;
1735	}
1736
1737	return NULL;
1738}
1739
1740
1741/*======================================================================*/
1742/* Functions relating to module loading in pre 2.1 kernels.  */
1743
1744static int
1745old_process_module_arguments(struct obj_file *f, int argc, char **argv)
1746{
1747	while (argc > 0) {
1748		char *p, *q;
1749		struct obj_symbol *sym;
1750		int *loc;
1751
1752		p = *argv;
1753		if ((q = strchr(p, '=')) == NULL) {
1754			argc--;
1755			continue;
1756                }
1757		*q++ = '\0';
1758
1759		sym = obj_find_symbol(f, p);
1760
1761		/* Also check that the parameter was not resolved from the kernel.  */
1762		if (sym == NULL || sym->secidx > SHN_HIRESERVE) {
1763			error_msg("symbol for parameter %s not found", p);
1764			return 0;
1765		}
1766
1767		loc = (int *) (f->sections[sym->secidx]->contents + sym->value);
1768
1769		/* Do C quoting if we begin with a ".  */
1770		if (*q == '"') {
1771			char *r, *str;
1772
1773			str = alloca(strlen(q));
1774			for (r = str, q++; *q != '"'; ++q, ++r) {
1775				if (*q == '\0') {
1776					error_msg("improperly terminated string argument for %s", p);
1777					return 0;
1778				} else if (*q == '\\')
1779					switch (*++q) {
1780					case 'a':
1781						*r = '\a';
1782						break;
1783					case 'b':
1784						*r = '\b';
1785						break;
1786					case 'e':
1787						*r = '\033';
1788						break;
1789					case 'f':
1790						*r = '\f';
1791						break;
1792					case 'n':
1793						*r = '\n';
1794						break;
1795					case 'r':
1796						*r = '\r';
1797						break;
1798					case 't':
1799						*r = '\t';
1800						break;
1801
1802					case '0':
1803					case '1':
1804					case '2':
1805					case '3':
1806					case '4':
1807					case '5':
1808					case '6':
1809					case '7':
1810						{
1811							int c = *q - '0';
1812							if (q[1] >= '0' && q[1] <= '7') {
1813								c = (c * 8) + *++q - '0';
1814								if (q[1] >= '0' && q[1] <= '7')
1815									c = (c * 8) + *++q - '0';
1816							}
1817							*r = c;
1818						}
1819						break;
1820
1821					default:
1822						*r = *q;
1823						break;
1824				} else
1825					*r = *q;
1826			}
1827			*r = '\0';
1828			obj_string_patch(f, sym->secidx, sym->value, str);
1829		} else if (*q >= '0' && *q <= '9') {
1830			do
1831				*loc++ = strtoul(q, &q, 0);
1832			while (*q++ == ',');
1833		} else {
1834			char *contents = f->sections[sym->secidx]->contents;
1835			char *myloc = contents + sym->value;
1836			char *r;			/* To search for commas */
1837
1838			/* Break the string with comas */
1839			while ((r = strchr(q, ',')) != (char *) NULL) {
1840				*r++ = '\0';
1841				obj_string_patch(f, sym->secidx, myloc - contents, q);
1842				myloc += sizeof(char *);
1843				q = r;
1844			}
1845
1846			/* last part */
1847			obj_string_patch(f, sym->secidx, myloc - contents, q);
1848		}
1849
1850		argc--, argv++;
1851	}
1852
1853	return 1;
1854}
1855
1856#ifdef BB_FEATURE_INSMOD_VERSION_CHECKING
1857static int old_is_module_checksummed(struct obj_file *f)
1858{
1859	return obj_find_symbol(f, "Using_Versions") != NULL;
1860}
1861/* Get the module's kernel version in the canonical integer form.  */
1862
1863static int
1864old_get_module_version(struct obj_file *f, char str[STRVERSIONLEN])
1865{
1866	struct obj_symbol *sym;
1867	char *p, *q;
1868	int a, b, c;
1869
1870	sym = obj_find_symbol(f, "kernel_version");
1871	if (sym == NULL)
1872		return -1;
1873
1874	p = f->sections[sym->secidx]->contents + sym->value;
1875	strncpy(str, p, STRVERSIONLEN);
1876
1877	a = strtoul(p, &p, 10);
1878	if (*p != '.')
1879		return -1;
1880	b = strtoul(p + 1, &p, 10);
1881	if (*p != '.')
1882		return -1;
1883	c = strtoul(p + 1, &q, 10);
1884	if (p + 1 == q)
1885		return -1;
1886
1887	return a << 16 | b << 8 | c;
1888}
1889
1890#endif   /* BB_FEATURE_INSMOD_VERSION_CHECKING */
1891
1892#ifdef BB_FEATURE_OLD_MODULE_INTERFACE
1893
1894/* Fetch all the symbols and divvy them up as appropriate for the modules.  */
1895
1896static int old_get_kernel_symbols(const char *m_name)
1897{
1898	struct old_kernel_sym *ks, *k;
1899	struct new_module_symbol *s;
1900	struct external_module *mod;
1901	int nks, nms, nmod, i;
1902
1903	nks = get_kernel_syms(NULL);
1904	if (nks <= 0) {
1905		if (nks)
1906			perror_msg("get_kernel_syms: %s", m_name);
1907		else
1908			error_msg("No kernel symbols");
1909		return 0;
1910	}
1911
1912	ks = k = xmalloc(nks * sizeof(*ks));
1913
1914	if (get_kernel_syms(ks) != nks) {
1915		perror("inconsistency with get_kernel_syms -- is someone else "
1916			   "playing with modules?");
1917		free(ks);
1918		return 0;
1919	}
1920
1921	/* Collect the module information.  */
1922
1923	mod = NULL;
1924	nmod = -1;
1925
1926	while (k->name[0] == '#' && k->name[1]) {
1927		struct old_kernel_sym *k2;
1928
1929		/* Find out how many symbols this module has.  */
1930		for (k2 = k + 1; k2->name[0] != '#'; ++k2)
1931			continue;
1932		nms = k2 - k - 1;
1933
1934		mod = xrealloc(mod, (++nmod + 1) * sizeof(*mod));
1935		mod[nmod].name = k->name + 1;
1936		mod[nmod].addr = k->value;
1937		mod[nmod].used = 0;
1938		mod[nmod].nsyms = nms;
1939		mod[nmod].syms = s = (nms ? xmalloc(nms * sizeof(*s)) : NULL);
1940
1941		for (i = 0, ++k; i < nms; ++i, ++s, ++k) {
1942			s->name = (unsigned long) k->name;
1943			s->value = k->value;
1944		}
1945
1946		k = k2;
1947	}
1948
1949	ext_modules = mod;
1950	n_ext_modules = nmod + 1;
1951
1952	/* Now collect the symbols for the kernel proper.  */
1953
1954	if (k->name[0] == '#')
1955		++k;
1956
1957	nksyms = nms = nks - (k - ks);
1958	ksyms = s = (nms ? xmalloc(nms * sizeof(*s)) : NULL);
1959
1960	for (i = 0; i < nms; ++i, ++s, ++k) {
1961		s->name = (unsigned long) k->name;
1962		s->value = k->value;
1963	}
1964
1965	return 1;
1966}
1967
1968/* Return the kernel symbol checksum version, or zero if not used.  */
1969
1970static int old_is_kernel_checksummed(void)
1971{
1972	/* Using_Versions is the first symbol.  */
1973	if (nksyms > 0
1974		&& strcmp((char *) ksyms[0].name,
1975				  "Using_Versions") == 0) return ksyms[0].value;
1976	else
1977		return 0;
1978}
1979
1980
1981static int old_create_mod_use_count(struct obj_file *f)
1982{
1983	struct obj_section *sec;
1984
1985	sec = obj_create_alloced_section_first(f, ".moduse", sizeof(long),
1986										   sizeof(long));
1987
1988	obj_add_symbol(f, "mod_use_count_", -1,
1989				   ELFW(ST_INFO) (STB_LOCAL, STT_OBJECT), sec->idx, 0,
1990				   sizeof(long));
1991
1992	return 1;
1993}
1994
1995static int
1996old_init_module(const char *m_name, struct obj_file *f,
1997				unsigned long m_size)
1998{
1999	char *image;
2000	struct old_mod_routines routines;
2001	struct old_symbol_table *symtab;
2002	int ret;
2003
2004	/* Create the symbol table */
2005	{
2006		int nsyms = 0, strsize = 0, total;
2007
2008		/* Size things first... */
2009		if (flag_export) {
2010			int i;
2011			for (i = 0; i < HASH_BUCKETS; ++i) {
2012				struct obj_symbol *sym;
2013				for (sym = f->symtab[i]; sym; sym = sym->next)
2014					if (ELFW(ST_BIND) (sym->info) != STB_LOCAL
2015						&& sym->secidx <= SHN_HIRESERVE)
2016					{
2017						sym->ksymidx = nsyms++;
2018						strsize += strlen(sym->name) + 1;
2019					}
2020			}
2021		}
2022
2023		total = (sizeof(struct old_symbol_table)
2024				 + nsyms * sizeof(struct old_module_symbol)
2025				 + n_ext_modules_used * sizeof(struct old_module_ref)
2026				 + strsize);
2027		symtab = xmalloc(total);
2028		symtab->size = total;
2029		symtab->n_symbols = nsyms;
2030		symtab->n_refs = n_ext_modules_used;
2031
2032		if (flag_export && nsyms) {
2033			struct old_module_symbol *ksym;
2034			char *str;
2035			int i;
2036
2037			ksym = symtab->symbol;
2038			str = ((char *) ksym + nsyms * sizeof(struct old_module_symbol)
2039				   + n_ext_modules_used * sizeof(struct old_module_ref));
2040
2041			for (i = 0; i < HASH_BUCKETS; ++i) {
2042				struct obj_symbol *sym;
2043				for (sym = f->symtab[i]; sym; sym = sym->next)
2044					if (sym->ksymidx >= 0) {
2045						ksym->addr = obj_symbol_final_value(f, sym);
2046						ksym->name =
2047							(unsigned long) str - (unsigned long) symtab;
2048
2049						strcpy(str, sym->name);
2050						str += strlen(sym->name) + 1;
2051						ksym++;
2052					}
2053			}
2054		}
2055
2056		if (n_ext_modules_used) {
2057			struct old_module_ref *ref;
2058			int i;
2059
2060			ref = (struct old_module_ref *)
2061				((char *) symtab->symbol + nsyms * sizeof(struct old_module_symbol));
2062
2063			for (i = 0; i < n_ext_modules; ++i)
2064				if (ext_modules[i].used)
2065					ref++->module = ext_modules[i].addr;
2066		}
2067	}
2068
2069	/* Fill in routines.  */
2070
2071	routines.init =
2072		obj_symbol_final_value(f, obj_find_symbol(f, "init_module"));
2073	routines.cleanup =
2074		obj_symbol_final_value(f, obj_find_symbol(f, "cleanup_module"));
2075
2076	/* Whew!  All of the initialization is complete.  Collect the final
2077	   module image and give it to the kernel.  */
2078
2079	image = xmalloc(m_size);
2080	obj_create_image(f, image);
2081
2082	/* image holds the complete relocated module, accounting correctly for
2083	   mod_use_count.  However the old module kernel support assume that
2084	   it is receiving something which does not contain mod_use_count.  */
2085	ret = old_sys_init_module(m_name, image + sizeof(long),
2086							  m_size | (flag_autoclean ? OLD_MOD_AUTOCLEAN
2087										: 0), &routines, symtab);
2088	if (ret)
2089		perror_msg("init_module: %s", m_name);
2090
2091	free(image);
2092	free(symtab);
2093
2094	return ret == 0;
2095}
2096
2097#else
2098
2099#define old_create_mod_use_count(x) TRUE
2100#define old_init_module(x, y, z) TRUE
2101
2102#endif							/* BB_FEATURE_OLD_MODULE_INTERFACE */
2103
2104
2105
2106/*======================================================================*/
2107/* Functions relating to module loading after 2.1.18.  */
2108
2109static int
2110new_process_module_arguments(struct obj_file *f, int argc, char **argv)
2111{
2112	while (argc > 0) {
2113		char *p, *q, *key;
2114		struct obj_symbol *sym;
2115		char *contents, *loc;
2116		int min, max, n;
2117
2118		p = *argv;
2119		if ((q = strchr(p, '=')) == NULL) {
2120			argc--;
2121			continue;
2122                }
2123
2124		key = alloca(q - p + 6);
2125		memcpy(key, "parm_", 5);
2126		memcpy(key + 5, p, q - p);
2127		key[q - p + 5] = 0;
2128
2129		p = get_modinfo_value(f, key);
2130		key += 5;
2131		if (p == NULL) {
2132			error_msg("invalid parameter %s", key);
2133			return 0;
2134		}
2135
2136		sym = obj_find_symbol(f, key);
2137
2138		/* Also check that the parameter was not resolved from the kernel.  */
2139		if (sym == NULL || sym->secidx > SHN_HIRESERVE) {
2140			error_msg("symbol for parameter %s not found", key);
2141			return 0;
2142		}
2143
2144		if (isdigit(*p)) {
2145			min = strtoul(p, &p, 10);
2146			if (*p == '-')
2147				max = strtoul(p + 1, &p, 10);
2148			else
2149				max = min;
2150		} else
2151			min = max = 1;
2152
2153		contents = f->sections[sym->secidx]->contents;
2154		loc = contents + sym->value;
2155		n = (*++q != '\0');
2156
2157		while (1) {
2158			if ((*p == 's') || (*p == 'c')) {
2159				char *str;
2160
2161				/* Do C quoting if we begin with a ", else slurp the lot.  */
2162				if (*q == '"') {
2163					char *r;
2164
2165					str = alloca(strlen(q));
2166					for (r = str, q++; *q != '"'; ++q, ++r) {
2167						if (*q == '\0') {
2168							error_msg("improperly terminated string argument for %s",
2169									key);
2170							return 0;
2171						} else if (*q == '\\')
2172							switch (*++q) {
2173							case 'a':
2174								*r = '\a';
2175								break;
2176							case 'b':
2177								*r = '\b';
2178								break;
2179							case 'e':
2180								*r = '\033';
2181								break;
2182							case 'f':
2183								*r = '\f';
2184								break;
2185							case 'n':
2186								*r = '\n';
2187								break;
2188							case 'r':
2189								*r = '\r';
2190								break;
2191							case 't':
2192								*r = '\t';
2193								break;
2194
2195							case '0':
2196							case '1':
2197							case '2':
2198							case '3':
2199							case '4':
2200							case '5':
2201							case '6':
2202							case '7':
2203								{
2204									int c = *q - '0';
2205									if (q[1] >= '0' && q[1] <= '7') {
2206										c = (c * 8) + *++q - '0';
2207										if (q[1] >= '0' && q[1] <= '7')
2208											c = (c * 8) + *++q - '0';
2209									}
2210									*r = c;
2211								}
2212								break;
2213
2214							default:
2215								*r = *q;
2216								break;
2217						} else
2218							*r = *q;
2219					}
2220					*r = '\0';
2221					++q;
2222				} else {
2223					char *r;
2224
2225					/* In this case, the string is not quoted. We will break
2226					   it using the coma (like for ints). If the user wants to
2227					   include comas in a string, he just has to quote it */
2228
2229					/* Search the next coma */
2230					r = strchr(q, ',');
2231
2232					/* Found ? */
2233					if (r != (char *) NULL) {
2234						/* Recopy the current field */
2235						str = alloca(r - q + 1);
2236						memcpy(str, q, r - q);
2237
2238						/* I don't know if it is usefull, as the previous case
2239						   doesn't null terminate the string ??? */
2240						str[r - q] = '\0';
2241
2242						/* Keep next fields */
2243						q = r;
2244					} else {
2245						/* last string */
2246						str = q;
2247						q = "";
2248					}
2249				}
2250
2251				if (*p == 's') {
2252					/* Normal string */
2253					obj_string_patch(f, sym->secidx, loc - contents, str);
2254					loc += tgt_sizeof_char_p;
2255				} else {
2256					/* Array of chars (in fact, matrix !) */
2257					unsigned long charssize;	/* size of each member */
2258
2259					/* Get the size of each member */
2260					/* Probably we should do that outside the loop ? */
2261					if (!isdigit(*(p + 1))) {
2262						error_msg("parameter type 'c' for %s must be followed by"
2263								" the maximum size", key);
2264						return 0;
2265					}
2266					charssize = strtoul(p + 1, (char **) NULL, 10);
2267
2268					/* Check length */
2269					if (strlen(str) >= charssize) {
2270						error_msg("string too long for %s (max %ld)", key,
2271								charssize - 1);
2272						return 0;
2273					}
2274
2275					/* Copy to location */
2276					strcpy((char *) loc, str);
2277					loc += charssize;
2278				}
2279			} else {
2280				long v = strtoul(q, &q, 0);
2281				switch (*p) {
2282				case 'b':
2283					*loc++ = v;
2284					break;
2285				case 'h':
2286					*(short *) loc = v;
2287					loc += tgt_sizeof_short;
2288					break;
2289				case 'i':
2290					*(int *) loc = v;
2291					loc += tgt_sizeof_int;
2292					break;
2293				case 'l':
2294					*(long *) loc = v;
2295					loc += tgt_sizeof_long;
2296					break;
2297
2298				default:
2299					error_msg("unknown parameter type '%c' for %s", *p, key);
2300					return 0;
2301				}
2302			}
2303
2304		  retry_end_of_value:
2305			switch (*q) {
2306			case '\0':
2307				goto end_of_arg;
2308
2309			case ' ':
2310			case '\t':
2311			case '\n':
2312			case '\r':
2313				++q;
2314				goto retry_end_of_value;
2315
2316			case ',':
2317				if (++n > max) {
2318					error_msg("too many values for %s (max %d)", key, max);
2319					return 0;
2320				}
2321				++q;
2322				break;
2323
2324			default:
2325				error_msg("invalid argument syntax for %s", key);
2326				return 0;
2327			}
2328		}
2329
2330	  end_of_arg:
2331		if (n < min) {
2332			error_msg("too few values for %s (min %d)", key, min);
2333			return 0;
2334		}
2335
2336		argc--, argv++;
2337	}
2338
2339	return 1;
2340}
2341
2342#ifdef BB_FEATURE_INSMOD_VERSION_CHECKING
2343static int new_is_module_checksummed(struct obj_file *f)
2344{
2345	const char *p = get_modinfo_value(f, "using_checksums");
2346	if (p)
2347		return atoi(p);
2348	else
2349		return 0;
2350}
2351
2352/* Get the module's kernel version in the canonical integer form.  */
2353
2354static int
2355new_get_module_version(struct obj_file *f, char str[STRVERSIONLEN])
2356{
2357	char *p, *q;
2358	int a, b, c;
2359
2360	p = get_modinfo_value(f, "kernel_version");
2361	if (p == NULL)
2362		return -1;
2363	strncpy(str, p, STRVERSIONLEN);
2364
2365	a = strtoul(p, &p, 10);
2366	if (*p != '.')
2367		return -1;
2368	b = strtoul(p + 1, &p, 10);
2369	if (*p != '.')
2370		return -1;
2371	c = strtoul(p + 1, &q, 10);
2372	if (p + 1 == q)
2373		return -1;
2374
2375	return a << 16 | b << 8 | c;
2376}
2377
2378#endif   /* BB_FEATURE_INSMOD_VERSION_CHECKING */
2379
2380
2381#ifdef BB_FEATURE_NEW_MODULE_INTERFACE
2382
2383/* Fetch the loaded modules, and all currently exported symbols.  */
2384
2385static int new_get_kernel_symbols(void)
2386{
2387	char *module_names, *mn;
2388	struct external_module *modules, *m;
2389	struct new_module_symbol *syms, *s;
2390	size_t ret, bufsize, nmod, nsyms, i, j;
2391
2392	/* Collect the loaded modules.  */
2393
2394	module_names = xmalloc(bufsize = 256);
2395  retry_modules_load:
2396	if (query_module(NULL, QM_MODULES, module_names, bufsize, &ret)) {
2397		if (errno == ENOSPC && bufsize < ret) {
2398			module_names = xrealloc(module_names, bufsize = ret);
2399			goto retry_modules_load;
2400		}
2401		perror_msg("QM_MODULES");
2402		return 0;
2403	}
2404
2405	n_ext_modules = nmod = ret;
2406
2407	/* Collect the modules' symbols.  */
2408
2409	if (nmod){
2410		ext_modules = modules = xmalloc(nmod * sizeof(*modules));
2411		memset(modules, 0, nmod * sizeof(*modules));
2412		for (i = 0, mn = module_names, m = modules;
2413			 i < nmod; ++i, ++m, mn += strlen(mn) + 1) {
2414			struct new_module_info info;
2415
2416			if (query_module(mn, QM_INFO, &info, sizeof(info), &ret)) {
2417				if (errno == ENOENT) {
2418					/* The module was removed out from underneath us.  */
2419					continue;
2420				}
2421				perror_msg("query_module: QM_INFO: %s", mn);
2422				return 0;
2423			}
2424
2425			syms = xmalloc(bufsize = 1024);
2426		  retry_mod_sym_load:
2427			if (query_module(mn, QM_SYMBOLS, syms, bufsize, &ret)) {
2428				switch (errno) {
2429				case ENOSPC:
2430					syms = xrealloc(syms, bufsize = ret);
2431					goto retry_mod_sym_load;
2432				case ENOENT:
2433					/* The module was removed out from underneath us.  */
2434					continue;
2435				default:
2436					perror_msg("query_module: QM_SYMBOLS: %s", mn);
2437					return 0;
2438				}
2439			}
2440			nsyms = ret;
2441
2442			m->name = mn;
2443			m->addr = info.addr;
2444			m->nsyms = nsyms;
2445			m->syms = syms;
2446
2447			for (j = 0, s = syms; j < nsyms; ++j, ++s) {
2448				s->name += (unsigned long) syms;
2449			}
2450		}
2451	}
2452
2453	/* Collect the kernel's symbols.  */
2454
2455	syms = xmalloc(bufsize = 16 * 1024);
2456  retry_kern_sym_load:
2457	if (query_module(NULL, QM_SYMBOLS, syms, bufsize, &ret)) {
2458		if (errno == ENOSPC && bufsize < ret) {
2459			syms = xrealloc(syms, bufsize = ret);
2460			goto retry_kern_sym_load;
2461		}
2462		perror_msg("kernel: QM_SYMBOLS");
2463		return 0;
2464	}
2465	nksyms = nsyms = ret;
2466	ksyms = syms;
2467
2468	for (j = 0, s = syms; j < nsyms; ++j, ++s) {
2469		s->name += (unsigned long) syms;
2470	}
2471	return 1;
2472}
2473
2474
2475/* Return the kernel symbol checksum version, or zero if not used.  */
2476
2477static int new_is_kernel_checksummed(void)
2478{
2479	struct new_module_symbol *s;
2480	size_t i;
2481
2482	/* Using_Versions is not the first symbol, but it should be in there.  */
2483
2484	for (i = 0, s = ksyms; i < nksyms; ++i, ++s)
2485		if (strcmp((char *) s->name, "Using_Versions") == 0)
2486			return s->value;
2487
2488	return 0;
2489}
2490
2491
2492static int new_create_this_module(struct obj_file *f, const char *m_name)
2493{
2494	struct obj_section *sec;
2495
2496	sec = obj_create_alloced_section_first(f, ".this", tgt_sizeof_long,
2497										   sizeof(struct new_module));
2498	memset(sec->contents, 0, sizeof(struct new_module));
2499
2500	obj_add_symbol(f, "__this_module", -1,
2501				   ELFW(ST_INFO) (STB_LOCAL, STT_OBJECT), sec->idx, 0,
2502				   sizeof(struct new_module));
2503
2504	obj_string_patch(f, sec->idx, offsetof(struct new_module, name),
2505					 m_name);
2506
2507	return 1;
2508}
2509
2510
2511static int new_create_module_ksymtab(struct obj_file *f)
2512{
2513	struct obj_section *sec;
2514	int i;
2515
2516	/* We must always add the module references.  */
2517
2518	if (n_ext_modules_used) {
2519		struct new_module_ref *dep;
2520		struct obj_symbol *tm;
2521
2522		sec = obj_create_alloced_section(f, ".kmodtab", tgt_sizeof_void_p,
2523										 (sizeof(struct new_module_ref)
2524										  * n_ext_modules_used));
2525		if (!sec)
2526			return 0;
2527
2528		tm = obj_find_symbol(f, "__this_module");
2529		dep = (struct new_module_ref *) sec->contents;
2530		for (i = 0; i < n_ext_modules; ++i)
2531			if (ext_modules[i].used) {
2532				dep->dep = ext_modules[i].addr;
2533				obj_symbol_patch(f, sec->idx,
2534								 (char *) &dep->ref - sec->contents, tm);
2535				dep->next_ref = 0;
2536				++dep;
2537			}
2538	}
2539
2540	if (flag_export && !obj_find_section(f, "__ksymtab")) {
2541		size_t nsyms;
2542		int *loaded;
2543
2544		sec =
2545			obj_create_alloced_section(f, "__ksymtab", tgt_sizeof_void_p,
2546									   0);
2547
2548		/* We don't want to export symbols residing in sections that
2549		   aren't loaded.  There are a number of these created so that
2550		   we make sure certain module options don't appear twice.  */
2551
2552		loaded = alloca(sizeof(int) * (i = f->header.e_shnum));
2553		while (--i >= 0)
2554			loaded[i] = (f->sections[i]->header.sh_flags & SHF_ALLOC) != 0;
2555
2556		for (nsyms = i = 0; i < HASH_BUCKETS; ++i) {
2557			struct obj_symbol *sym;
2558			for (sym = f->symtab[i]; sym; sym = sym->next)
2559				if (ELFW(ST_BIND) (sym->info) != STB_LOCAL
2560					&& sym->secidx <= SHN_HIRESERVE
2561					&& (sym->secidx >= SHN_LORESERVE
2562						|| loaded[sym->secidx])) {
2563					ElfW(Addr) ofs = nsyms * 2 * tgt_sizeof_void_p;
2564
2565					obj_symbol_patch(f, sec->idx, ofs, sym);
2566					obj_string_patch(f, sec->idx, ofs + tgt_sizeof_void_p,
2567									 sym->name);
2568
2569					nsyms++;
2570				}
2571		}
2572
2573		obj_extend_section(sec, nsyms * 2 * tgt_sizeof_char_p);
2574	}
2575
2576	return 1;
2577}
2578
2579
2580static int
2581new_init_module(const char *m_name, struct obj_file *f,
2582				unsigned long m_size)
2583{
2584	struct new_module *module;
2585	struct obj_section *sec;
2586	void *image;
2587	int ret;
2588	tgt_long m_addr;
2589
2590	sec = obj_find_section(f, ".this");
2591	if (!sec || !sec->contents) {
2592		perror_msg_and_die("corrupt module %s?",m_name);
2593	}
2594	module = (struct new_module *) sec->contents;
2595	m_addr = sec->header.sh_addr;
2596
2597	module->size_of_struct = sizeof(*module);
2598	module->size = m_size;
2599	module->flags = flag_autoclean ? NEW_MOD_AUTOCLEAN : 0;
2600
2601	sec = obj_find_section(f, "__ksymtab");
2602	if (sec && sec->header.sh_size) {
2603		module->syms = sec->header.sh_addr;
2604		module->nsyms = sec->header.sh_size / (2 * tgt_sizeof_char_p);
2605	}
2606
2607	if (n_ext_modules_used) {
2608		sec = obj_find_section(f, ".kmodtab");
2609		module->deps = sec->header.sh_addr;
2610		module->ndeps = n_ext_modules_used;
2611	}
2612
2613	module->init =
2614		obj_symbol_final_value(f, obj_find_symbol(f, "init_module"));
2615	module->cleanup =
2616		obj_symbol_final_value(f, obj_find_symbol(f, "cleanup_module"));
2617
2618	sec = obj_find_section(f, "__ex_table");
2619	if (sec) {
2620		module->ex_table_start = sec->header.sh_addr;
2621		module->ex_table_end = sec->header.sh_addr + sec->header.sh_size;
2622	}
2623
2624	sec = obj_find_section(f, ".text.init");
2625	if (sec) {
2626		module->runsize = sec->header.sh_addr - m_addr;
2627	}
2628	sec = obj_find_section(f, ".data.init");
2629	if (sec) {
2630		if (!module->runsize ||
2631			module->runsize > sec->header.sh_addr - m_addr)
2632				module->runsize = sec->header.sh_addr - m_addr;
2633	}
2634	sec = obj_find_section(f, ARCHDATA_SEC_NAME);
2635	if (sec && sec->header.sh_size) {
2636		module->archdata_start = (void*)sec->header.sh_addr;
2637		module->archdata_end = module->archdata_start + sec->header.sh_size;
2638	}
2639	sec = obj_find_section(f, KALLSYMS_SEC_NAME);
2640	if (sec && sec->header.sh_size) {
2641		module->kallsyms_start = (void*)sec->header.sh_addr;
2642		module->kallsyms_end = module->kallsyms_start + sec->header.sh_size;
2643	}
2644
2645	if (!arch_init_module(f, module))
2646		return 0;
2647
2648	/* Whew!  All of the initialization is complete.  Collect the final
2649	   module image and give it to the kernel.  */
2650
2651	image = xmalloc(m_size);
2652	obj_create_image(f, image);
2653
2654	ret = new_sys_init_module(m_name, (struct new_module *) image);
2655	if (ret)
2656		perror_msg("init_module: %s", m_name);
2657
2658	free(image);
2659
2660	return ret == 0;
2661}
2662
2663#else
2664
2665#define new_init_module(x, y, z) TRUE
2666#define new_create_this_module(x, y) 0
2667#define new_create_module_ksymtab(x)
2668#define query_module(v, w, x, y, z) -1
2669
2670#endif							/* BB_FEATURE_NEW_MODULE_INTERFACE */
2671
2672
2673/*======================================================================*/
2674
2675static int
2676obj_string_patch(struct obj_file *f, int secidx, ElfW(Addr) offset,
2677				 const char *string)
2678{
2679	struct obj_string_patch *p;
2680	struct obj_section *strsec;
2681	size_t len = strlen(string) + 1;
2682	char *loc;
2683
2684	p = xmalloc(sizeof(*p));
2685	p->next = f->string_patches;
2686	p->reloc_secidx = secidx;
2687	p->reloc_offset = offset;
2688	f->string_patches = p;
2689
2690	strsec = obj_find_section(f, ".kstrtab");
2691	if (strsec == NULL) {
2692		strsec = obj_create_alloced_section(f, ".kstrtab", 1, len);
2693		p->string_offset = 0;
2694		loc = strsec->contents;
2695	} else {
2696		p->string_offset = strsec->header.sh_size;
2697		loc = obj_extend_section(strsec, len);
2698	}
2699	memcpy(loc, string, len);
2700
2701	return 1;
2702}
2703
2704static int
2705obj_symbol_patch(struct obj_file *f, int secidx, ElfW(Addr) offset,
2706				 struct obj_symbol *sym)
2707{
2708	struct obj_symbol_patch *p;
2709
2710	p = xmalloc(sizeof(*p));
2711	p->next = f->symbol_patches;
2712	p->reloc_secidx = secidx;
2713	p->reloc_offset = offset;
2714	p->sym = sym;
2715	f->symbol_patches = p;
2716
2717	return 1;
2718}
2719
2720static int obj_check_undefineds(struct obj_file *f)
2721{
2722	unsigned long i;
2723	int ret = 1;
2724
2725	for (i = 0; i < HASH_BUCKETS; ++i) {
2726		struct obj_symbol *sym;
2727		for (sym = f->symtab[i]; sym; sym = sym->next)
2728			if (sym->secidx == SHN_UNDEF) {
2729				if (ELFW(ST_BIND) (sym->info) == STB_WEAK) {
2730					sym->secidx = SHN_ABS;
2731					sym->value = 0;
2732				} else {
2733					error_msg("unresolved symbol %s", sym->name);
2734					ret = 0;
2735				}
2736			}
2737	}
2738
2739	return ret;
2740}
2741
2742static void obj_allocate_commons(struct obj_file *f)
2743{
2744	struct common_entry {
2745		struct common_entry *next;
2746		struct obj_symbol *sym;
2747	} *common_head = NULL;
2748
2749	unsigned long i;
2750
2751	for (i = 0; i < HASH_BUCKETS; ++i) {
2752		struct obj_symbol *sym;
2753		for (sym = f->symtab[i]; sym; sym = sym->next)
2754			if (sym->secidx == SHN_COMMON) {
2755				/* Collect all COMMON symbols and sort them by size so as to
2756				   minimize space wasted by alignment requirements.  */
2757				{
2758					struct common_entry **p, *n;
2759					for (p = &common_head; *p; p = &(*p)->next)
2760						if (sym->size <= (*p)->sym->size)
2761							break;
2762
2763					n = alloca(sizeof(*n));
2764					n->next = *p;
2765					n->sym = sym;
2766					*p = n;
2767				}
2768			}
2769	}
2770
2771	for (i = 1; i < f->local_symtab_size; ++i) {
2772		struct obj_symbol *sym = f->local_symtab[i];
2773		if (sym && sym->secidx == SHN_COMMON) {
2774			struct common_entry **p, *n;
2775			for (p = &common_head; *p; p = &(*p)->next)
2776				if (sym == (*p)->sym)
2777					break;
2778				else if (sym->size < (*p)->sym->size) {
2779					n = alloca(sizeof(*n));
2780					n->next = *p;
2781					n->sym = sym;
2782					*p = n;
2783					break;
2784				}
2785		}
2786	}
2787
2788	if (common_head) {
2789		/* Find the bss section.  */
2790		for (i = 0; i < f->header.e_shnum; ++i)
2791			if (f->sections[i]->header.sh_type == SHT_NOBITS)
2792				break;
2793
2794		/* If for some reason there hadn't been one, create one.  */
2795		if (i == f->header.e_shnum) {
2796			struct obj_section *sec;
2797
2798			f->sections = xrealloc(f->sections, (i + 1) * sizeof(sec));
2799			f->sections[i] = sec = arch_new_section();
2800			f->header.e_shnum = i + 1;
2801
2802			memset(sec, 0, sizeof(*sec));
2803			sec->header.sh_type = SHT_PROGBITS;
2804			sec->header.sh_flags = SHF_WRITE | SHF_ALLOC;
2805			sec->name = ".bss";
2806			sec->idx = i;
2807		}
2808
2809		/* Allocate the COMMONS.  */
2810		{
2811			ElfW(Addr) bss_size = f->sections[i]->header.sh_size;
2812			ElfW(Addr) max_align = f->sections[i]->header.sh_addralign;
2813			struct common_entry *c;
2814
2815			for (c = common_head; c; c = c->next) {
2816				ElfW(Addr) align = c->sym->value;
2817
2818				if (align > max_align)
2819					max_align = align;
2820				if (bss_size & (align - 1))
2821					bss_size = (bss_size | (align - 1)) + 1;
2822
2823				c->sym->secidx = i;
2824				c->sym->value = bss_size;
2825
2826				bss_size += c->sym->size;
2827			}
2828
2829			f->sections[i]->header.sh_size = bss_size;
2830			f->sections[i]->header.sh_addralign = max_align;
2831		}
2832	}
2833
2834	/* For the sake of patch relocation and parameter initialization,
2835	   allocate zeroed data for NOBITS sections now.  Note that after
2836	   this we cannot assume NOBITS are really empty.  */
2837	for (i = 0; i < f->header.e_shnum; ++i) {
2838		struct obj_section *s = f->sections[i];
2839		if (s->header.sh_type == SHT_NOBITS) {
2840			if (s->header.sh_size != 0)
2841			s->contents = memset(xmalloc(s->header.sh_size),
2842								 0, s->header.sh_size);
2843			else
2844				s->contents = NULL;
2845
2846			s->header.sh_type = SHT_PROGBITS;
2847		}
2848	}
2849}
2850
2851static unsigned long obj_load_size(struct obj_file *f)
2852{
2853	unsigned long dot = 0;
2854	struct obj_section *sec;
2855
2856	/* Finalize the positions of the sections relative to one another.  */
2857
2858	for (sec = f->load_order; sec; sec = sec->load_next) {
2859		ElfW(Addr) align;
2860
2861		align = sec->header.sh_addralign;
2862		if (align && (dot & (align - 1)))
2863			dot = (dot | (align - 1)) + 1;
2864
2865		sec->header.sh_addr = dot;
2866		dot += sec->header.sh_size;
2867	}
2868
2869	return dot;
2870}
2871
2872static int obj_relocate(struct obj_file *f, ElfW(Addr) base)
2873{
2874	int i, n = f->header.e_shnum;
2875	int ret = 1;
2876
2877	/* Finalize the addresses of the sections.  */
2878
2879	f->baseaddr = base;
2880	for (i = 0; i < n; ++i)
2881		f->sections[i]->header.sh_addr += base;
2882
2883	/* And iterate over all of the relocations.  */
2884
2885	for (i = 0; i < n; ++i) {
2886		struct obj_section *relsec, *symsec, *targsec, *strsec;
2887		ElfW(RelM) * rel, *relend;
2888		ElfW(Sym) * symtab;
2889		const char *strtab;
2890
2891		relsec = f->sections[i];
2892		if (relsec->header.sh_type != SHT_RELM)
2893			continue;
2894
2895		symsec = f->sections[relsec->header.sh_link];
2896		targsec = f->sections[relsec->header.sh_info];
2897		strsec = f->sections[symsec->header.sh_link];
2898
2899		rel = (ElfW(RelM) *) relsec->contents;
2900		relend = rel + (relsec->header.sh_size / sizeof(ElfW(RelM)));
2901		symtab = (ElfW(Sym) *) symsec->contents;
2902		strtab = (const char *) strsec->contents;
2903
2904		for (; rel < relend; ++rel) {
2905			ElfW(Addr) value = 0;
2906			struct obj_symbol *intsym = NULL;
2907			unsigned long symndx;
2908			ElfW(Sym) * extsym = 0;
2909			const char *errmsg;
2910
2911			/* Attempt to find a value to use for this relocation.  */
2912
2913			symndx = ELFW(R_SYM) (rel->r_info);
2914			if (symndx) {
2915				/* Note we've already checked for undefined symbols.  */
2916
2917				extsym = &symtab[symndx];
2918				if (ELFW(ST_BIND) (extsym->st_info) == STB_LOCAL) {
2919					/* Local symbols we look up in the local table to be sure
2920					   we get the one that is really intended.  */
2921					intsym = f->local_symtab[symndx];
2922				} else {
2923					/* Others we look up in the hash table.  */
2924					const char *name;
2925					if (extsym->st_name)
2926						name = strtab + extsym->st_name;
2927					else
2928						name = f->sections[extsym->st_shndx]->name;
2929					intsym = obj_find_symbol(f, name);
2930				}
2931
2932				value = obj_symbol_final_value(f, intsym);
2933				intsym->referenced = 1;
2934			}
2935#if SHT_RELM == SHT_RELA
2936#if defined(__alpha__) && defined(AXP_BROKEN_GAS)
2937			/* Work around a nasty GAS bug, that is fixed as of 2.7.0.9.  */
2938			if (!extsym || !extsym->st_name ||
2939				ELFW(ST_BIND) (extsym->st_info) != STB_LOCAL)
2940#endif
2941				value += rel->r_addend;
2942#endif
2943
2944			/* Do it! */
2945			switch (arch_apply_relocation
2946					(f, targsec, symsec, intsym, rel, value)) {
2947			case obj_reloc_ok:
2948				break;
2949
2950			case obj_reloc_overflow:
2951				errmsg = "Relocation overflow";
2952				goto bad_reloc;
2953			case obj_reloc_dangerous:
2954				errmsg = "Dangerous relocation";
2955				goto bad_reloc;
2956			case obj_reloc_unhandled:
2957				errmsg = "Unhandled relocation";
2958			  bad_reloc:
2959				if (extsym) {
2960					error_msg("%s of type %ld for %s", errmsg,
2961							(long) ELFW(R_TYPE) (rel->r_info),
2962							strtab + extsym->st_name);
2963				} else {
2964					error_msg("%s of type %ld", errmsg,
2965							(long) ELFW(R_TYPE) (rel->r_info));
2966				}
2967				ret = 0;
2968				break;
2969			}
2970		}
2971	}
2972
2973	/* Finally, take care of the patches.  */
2974
2975	if (f->string_patches) {
2976		struct obj_string_patch *p;
2977		struct obj_section *strsec;
2978		ElfW(Addr) strsec_base;
2979		strsec = obj_find_section(f, ".kstrtab");
2980		strsec_base = strsec->header.sh_addr;
2981
2982		for (p = f->string_patches; p; p = p->next) {
2983			struct obj_section *targsec = f->sections[p->reloc_secidx];
2984			*(ElfW(Addr) *) (targsec->contents + p->reloc_offset)
2985				= strsec_base + p->string_offset;
2986		}
2987	}
2988
2989	if (f->symbol_patches) {
2990		struct obj_symbol_patch *p;
2991
2992		for (p = f->symbol_patches; p; p = p->next) {
2993			struct obj_section *targsec = f->sections[p->reloc_secidx];
2994			*(ElfW(Addr) *) (targsec->contents + p->reloc_offset)
2995				= obj_symbol_final_value(f, p->sym);
2996		}
2997	}
2998
2999	return ret;
3000}
3001
3002static int obj_create_image(struct obj_file *f, char *image)
3003{
3004	struct obj_section *sec;
3005	ElfW(Addr) base = f->baseaddr;
3006
3007	for (sec = f->load_order; sec; sec = sec->load_next) {
3008		char *secimg;
3009
3010		if (sec->contents == 0 || sec->header.sh_size == 0)
3011			continue;
3012
3013		secimg = image + (sec->header.sh_addr - base);
3014
3015		/* Note that we allocated data for NOBITS sections earlier.  */
3016		memcpy(secimg, sec->contents, sec->header.sh_size);
3017	}
3018
3019	return 1;
3020}
3021
3022/*======================================================================*/
3023
3024static struct obj_file *obj_load(FILE * fp, int loadprogbits)
3025{
3026	struct obj_file *f;
3027	ElfW(Shdr) * section_headers;
3028	int shnum, i;
3029	char *shstrtab;
3030
3031	/* Read the file header.  */
3032
3033	f = arch_new_file();
3034	memset(f, 0, sizeof(*f));
3035	f->symbol_cmp = strcmp;
3036	f->symbol_hash = obj_elf_hash;
3037	f->load_order_search_start = &f->load_order;
3038
3039	fseek(fp, 0, SEEK_SET);
3040	if (fread(&f->header, sizeof(f->header), 1, fp) != 1) {
3041		perror_msg("error reading ELF header");
3042		return NULL;
3043	}
3044
3045	if (f->header.e_ident[EI_MAG0] != ELFMAG0
3046		|| f->header.e_ident[EI_MAG1] != ELFMAG1
3047		|| f->header.e_ident[EI_MAG2] != ELFMAG2
3048		|| f->header.e_ident[EI_MAG3] != ELFMAG3) {
3049		error_msg("not an ELF file");
3050		return NULL;
3051	}
3052	if (f->header.e_ident[EI_CLASS] != ELFCLASSM
3053		|| f->header.e_ident[EI_DATA] != ELFDATAM
3054		|| f->header.e_ident[EI_VERSION] != EV_CURRENT
3055		|| !MATCH_MACHINE(f->header.e_machine)) {
3056		error_msg("ELF file not for this architecture");
3057		return NULL;
3058	}
3059	if (f->header.e_type != ET_REL) {
3060		error_msg("ELF file not a relocatable object");
3061		return NULL;
3062	}
3063
3064	/* Read the section headers.  */
3065
3066	if (f->header.e_shentsize != sizeof(ElfW(Shdr))) {
3067		error_msg("section header size mismatch: %lu != %lu",
3068				(unsigned long) f->header.e_shentsize,
3069				(unsigned long) sizeof(ElfW(Shdr)));
3070		return NULL;
3071	}
3072
3073	shnum = f->header.e_shnum;
3074	f->sections = xmalloc(sizeof(struct obj_section *) * shnum);
3075	memset(f->sections, 0, sizeof(struct obj_section *) * shnum);
3076
3077	section_headers = alloca(sizeof(ElfW(Shdr)) * shnum);
3078	fseek(fp, f->header.e_shoff, SEEK_SET);
3079	if (fread(section_headers, sizeof(ElfW(Shdr)), shnum, fp) != shnum) {
3080		perror_msg("error reading ELF section headers");
3081		return NULL;
3082	}
3083
3084	/* Read the section data.  */
3085
3086	for (i = 0; i < shnum; ++i) {
3087		struct obj_section *sec;
3088
3089		f->sections[i] = sec = arch_new_section();
3090		memset(sec, 0, sizeof(*sec));
3091
3092		sec->header = section_headers[i];
3093		sec->idx = i;
3094
3095		if(sec->header.sh_size) switch (sec->header.sh_type) {
3096		case SHT_NULL:
3097		case SHT_NOTE:
3098		case SHT_NOBITS:
3099			/* ignore */
3100			break;
3101
3102		case SHT_PROGBITS:
3103#if LOADBITS
3104			if (!loadprogbits) {
3105				sec->contents = NULL;
3106				break;
3107			}
3108#endif
3109		case SHT_SYMTAB:
3110		case SHT_STRTAB:
3111		case SHT_RELM:
3112			if (sec->header.sh_size > 0) {
3113				sec->contents = xmalloc(sec->header.sh_size);
3114				fseek(fp, sec->header.sh_offset, SEEK_SET);
3115				if (fread(sec->contents, sec->header.sh_size, 1, fp) != 1) {
3116					perror_msg("error reading ELF section data");
3117					return NULL;
3118				}
3119			} else {
3120				sec->contents = NULL;
3121			}
3122			break;
3123
3124#if SHT_RELM == SHT_REL
3125		case SHT_RELA:
3126			error_msg("RELA relocations not supported on this architecture");
3127			return NULL;
3128#else
3129		case SHT_REL:
3130			error_msg("REL relocations not supported on this architecture");
3131			return NULL;
3132#endif
3133
3134		default:
3135			if (sec->header.sh_type >= SHT_LOPROC) {
3136				/* Assume processor specific section types are debug
3137				   info and can safely be ignored.  If this is ever not
3138				   the case (Hello MIPS?), don't put ifdefs here but
3139				   create an arch_load_proc_section().  */
3140				break;
3141			}
3142
3143			error_msg("can't handle sections of type %ld",
3144					(long) sec->header.sh_type);
3145			return NULL;
3146		}
3147	}
3148
3149	/* Do what sort of interpretation as needed by each section.  */
3150
3151	shstrtab = f->sections[f->header.e_shstrndx]->contents;
3152
3153	for (i = 0; i < shnum; ++i) {
3154		struct obj_section *sec = f->sections[i];
3155		sec->name = shstrtab + sec->header.sh_name;
3156	}
3157
3158	for (i = 0; i < shnum; ++i) {
3159		struct obj_section *sec = f->sections[i];
3160
3161		/* .modinfo should be contents only but gcc has no attribute for that.
3162		 * The kernel may have marked .modinfo as ALLOC, ignore this bit.
3163		 */
3164		if (strcmp(sec->name, ".modinfo") == 0)
3165			sec->header.sh_flags &= ~SHF_ALLOC;
3166
3167		if (sec->header.sh_flags & SHF_ALLOC)
3168			obj_insert_section_load_order(f, sec);
3169
3170		switch (sec->header.sh_type) {
3171		case SHT_SYMTAB:
3172			{
3173				unsigned long nsym, j;
3174				char *strtab;
3175				ElfW(Sym) * sym;
3176
3177				if (sec->header.sh_entsize != sizeof(ElfW(Sym))) {
3178					error_msg("symbol size mismatch: %lu != %lu",
3179							(unsigned long) sec->header.sh_entsize,
3180							(unsigned long) sizeof(ElfW(Sym)));
3181					return NULL;
3182				}
3183
3184				nsym = sec->header.sh_size / sizeof(ElfW(Sym));
3185				strtab = f->sections[sec->header.sh_link]->contents;
3186				sym = (ElfW(Sym) *) sec->contents;
3187
3188				/* Allocate space for a table of local symbols.  */
3189				j = f->local_symtab_size = sec->header.sh_info;
3190				f->local_symtab = xcalloc(j, sizeof(struct obj_symbol *));
3191
3192				/* Insert all symbols into the hash table.  */
3193				for (j = 1, ++sym; j < nsym; ++j, ++sym) {
3194					const char *name;
3195					if (sym->st_name)
3196						name = strtab + sym->st_name;
3197					else if (sym->st_shndx < shnum)
3198						name = f->sections[sym->st_shndx]->name;
3199					else
3200						continue;
3201					obj_add_symbol(f, name, j, sym->st_info, sym->st_shndx,
3202								   sym->st_value, sym->st_size);
3203				}
3204			}
3205			break;
3206
3207		case SHT_RELM:
3208			if (sec->header.sh_entsize != sizeof(ElfW(RelM))) {
3209				error_msg("relocation entry size mismatch: %lu != %lu",
3210						(unsigned long) sec->header.sh_entsize,
3211						(unsigned long) sizeof(ElfW(RelM)));
3212				return NULL;
3213			}
3214			break;
3215		}
3216	}
3217
3218	return f;
3219}
3220
3221#ifdef BB_FEATURE_INSMOD_LOADINKMEM
3222/*
3223 * load the unloaded sections directly into the memory allocated by
3224 * kernel for the module
3225 */
3226
3227static int obj_load_progbits(FILE * fp, struct obj_file* f)
3228{
3229	char* imagebase = (char*) f->imagebase;
3230	ElfW(Addr) base = f->baseaddr;
3231	struct obj_section* sec;
3232
3233	for (sec = f->load_order; sec; sec = sec->load_next) {
3234
3235		/* section already loaded? */
3236		if (sec->contents != NULL)
3237			continue;
3238
3239		if (sec->header.sh_size == 0)
3240			continue;
3241
3242		sec->contents = imagebase + (sec->header.sh_addr - base);
3243		fseek(fp, sec->header.sh_offset, SEEK_SET);
3244		if (fread(sec->contents, sec->header.sh_size, 1, fp) != 1) {
3245			errorMsg("error reading ELF section data: %s\n", strerror(errno));
3246			return 0;
3247		}
3248
3249	}
3250	return 1;
3251}
3252#endif
3253
3254static void hide_special_symbols(struct obj_file *f)
3255{
3256	static const char *const specials[] = {
3257		"cleanup_module",
3258		"init_module",
3259		"kernel_version",
3260		NULL
3261	};
3262
3263	struct obj_symbol *sym;
3264	const char *const *p;
3265
3266	for (p = specials; *p; ++p)
3267		if ((sym = obj_find_symbol(f, *p)) != NULL)
3268			sym->info =
3269				ELFW(ST_INFO) (STB_LOCAL, ELFW(ST_TYPE) (sym->info));
3270}
3271
3272
3273
3274extern int insmod_main( int argc, char **argv)
3275{
3276	int opt;
3277	int k_crcs;
3278	int k_new_syscalls;
3279	int len;
3280	char *tmp;
3281	unsigned long m_size;
3282	ElfW(Addr) m_addr;
3283	FILE *fp;
3284	struct obj_file *f;
3285	struct obj_section *archdata = NULL;
3286	struct stat st;
3287	char m_name[FILENAME_MAX + 1] = "\0";
3288	int exit_status = EXIT_FAILURE;
3289	int m_has_modinfo;
3290#ifdef BB_FEATURE_INSMOD_VERSION_CHECKING
3291	int k_version;
3292	char k_strversion[STRVERSIONLEN];
3293	char m_strversion[STRVERSIONLEN];
3294	int m_version;
3295	int m_crcs;
3296#endif
3297
3298	/* Parse any options */
3299	while ((opt = getopt(argc, argv, "fkvxLo:")) > 0) {
3300		switch (opt) {
3301			case 'f':			/* force loading */
3302				flag_force_load = 1;
3303				break;
3304			case 'k':			/* module loaded by kerneld, auto-cleanable */
3305				flag_autoclean = 1;
3306				break;
3307			case 'v':			/* verbose output */
3308				flag_verbose = 1;
3309				break;
3310			case 'x':			/* do not export externs */
3311				flag_export = 0;
3312				break;
3313			case 'o':			/* name the output module */
3314				strncpy(m_name, optarg, FILENAME_MAX);
3315				break;
3316			case 'L':			/* Stub warning */
3317				/* This is needed for compatibility with modprobe.
3318				 * In theory, this does locking, but we don't do
3319				 * that.  So be careful and plan your life around not
3320				 * loading the same module 50 times concurrently. */
3321				break;
3322			default:
3323				show_usage();
3324		}
3325	}
3326
3327	if (argv[optind] == NULL) {
3328		show_usage();
3329	}
3330
3331	/* Grab the module name */
3332	if ((tmp = strrchr(argv[optind], '/')) != NULL) {
3333		tmp++;
3334	} else {
3335		tmp = argv[optind];
3336	}
3337	len = strlen(tmp);
3338
3339	if (len > 2 && tmp[len - 2] == '.' && tmp[len - 1] == 'o')
3340		len -= 2;
3341	memcpy(m_fullName, tmp, len);
3342	m_fullName[len]='\0';
3343	if (*m_name == '\0') {
3344		strcpy(m_name, m_fullName);
3345	}
3346	strcat(m_fullName, ".o");
3347
3348	/* Get a filedesc for the module.  Check we we have a complete path */
3349	if (stat(argv[optind], &st) < 0 || !S_ISREG(st.st_mode) ||
3350			(fp = fopen(argv[optind], "r")) == NULL) {
3351		struct utsname myuname;
3352
3353		/* Hmm.  Could not open it.  First search under /lib/modules/`uname -r`,
3354		 * but do not error out yet if we fail to find it... */
3355		if (uname(&myuname) == 0) {
3356			char module_dir[FILENAME_MAX];
3357			char real_module_dir[FILENAME_MAX];
3358			snprintf (module_dir, sizeof(module_dir), "%s/%s",
3359					_PATH_MODULES, myuname.release);
3360			/* Jump through hoops in case /lib/modules/`uname -r`
3361			 * is a symlink.  We do not want recursive_action to
3362			 * follow symlinks, but we do want to follow the
3363			 * /lib/modules/`uname -r` dir, So resolve it ourselves
3364			 * if it is a link... */
3365			if (realpath (module_dir, real_module_dir) == NULL)
3366				strcpy(real_module_dir, module_dir);
3367			recursive_action(real_module_dir, TRUE, FALSE, FALSE,
3368					check_module_name_match, 0, m_fullName);
3369		}
3370
3371		/* Check if we have found anything yet */
3372		if (m_filename[0] == '\0' || ((fp = fopen(m_filename, "r")) == NULL))
3373		{
3374			char module_dir[FILENAME_MAX];
3375			if (realpath (_PATH_MODULES, module_dir) == NULL)
3376				strcpy(module_dir, _PATH_MODULES);
3377			/* No module found under /lib/modules/`uname -r`, this
3378			 * time cast the net a bit wider.  Search /lib/modules/ */
3379			if (recursive_action(module_dir, TRUE, FALSE, FALSE,
3380						check_module_name_match, 0, m_fullName) == FALSE)
3381			{
3382				if (m_filename[0] == '\0'
3383						|| ((fp = fopen(m_filename, "r")) == NULL))
3384				{
3385					error_msg("%s: no module by that name found", m_fullName);
3386					return EXIT_FAILURE;
3387				}
3388			} else
3389				error_msg_and_die("%s: no module by that name found", m_fullName);
3390		}
3391	} else
3392		safe_strncpy(m_filename, argv[optind], sizeof(m_filename));
3393
3394	printf("Using %s\n", m_filename);
3395
3396	if ((f = obj_load(fp, LOADBITS)) == NULL)
3397		perror_msg_and_die("Could not load the module");
3398
3399	if (get_modinfo_value(f, "kernel_version") == NULL)
3400		m_has_modinfo = 0;
3401	else
3402		m_has_modinfo = 1;
3403
3404#ifdef BB_FEATURE_INSMOD_VERSION_CHECKING
3405	/* Version correspondence?  */
3406
3407	k_version = get_kernel_version(k_strversion);
3408	if (m_has_modinfo) {
3409		m_version = new_get_module_version(f, m_strversion);
3410	} else {
3411		m_version = old_get_module_version(f, m_strversion);
3412		if (m_version == -1) {
3413			error_msg("couldn't find the kernel version the module was "
3414					"compiled for");
3415			goto out;
3416		}
3417	}
3418
3419	if (strncmp(k_strversion, m_strversion, STRVERSIONLEN) != 0) {
3420		if (flag_force_load) {
3421			error_msg("Warning: kernel-module version mismatch\n"
3422					"\t%s was compiled for kernel version %s\n"
3423					"\twhile this kernel is version %s",
3424					m_filename, m_strversion, k_strversion);
3425		} else {
3426			error_msg("kernel-module version mismatch\n"
3427					"\t%s was compiled for kernel version %s\n"
3428					"\twhile this kernel is version %s.",
3429					m_filename, m_strversion, k_strversion);
3430			goto out;
3431		}
3432	}
3433	k_crcs = 0;
3434#endif							/* BB_FEATURE_INSMOD_VERSION_CHECKING */
3435
3436	k_new_syscalls = !query_module(NULL, 0, NULL, 0, NULL);
3437
3438	if (k_new_syscalls) {
3439#ifdef BB_FEATURE_NEW_MODULE_INTERFACE
3440		if (!new_get_kernel_symbols())
3441			goto out;
3442		k_crcs = new_is_kernel_checksummed();
3443#else
3444		error_msg("Not configured to support new kernels");
3445		goto out;
3446#endif
3447	} else {
3448#ifdef BB_FEATURE_OLD_MODULE_INTERFACE
3449		if (!old_get_kernel_symbols(m_name))
3450			goto out;
3451		k_crcs = old_is_kernel_checksummed();
3452#else
3453		error_msg("Not configured to support old kernels");
3454		goto out;
3455#endif
3456	}
3457
3458#ifdef BB_FEATURE_INSMOD_VERSION_CHECKING
3459	if (m_has_modinfo)
3460		m_crcs = new_is_module_checksummed(f);
3461	else
3462		m_crcs = old_is_module_checksummed(f);
3463
3464	if (m_crcs != k_crcs)
3465		obj_set_symbol_compare(f, ncv_strcmp, ncv_symbol_hash);
3466#endif							/* BB_FEATURE_INSMOD_VERSION_CHECKING */
3467
3468	/* Let the module know about the kernel symbols.  */
3469	add_kernel_symbols(f);
3470
3471	/* Allocate common symbols, symbol tables, and string tables.  */
3472
3473	if (k_new_syscalls
3474		? !new_create_this_module(f, m_name)
3475		: !old_create_mod_use_count(f))
3476	{
3477		goto out;
3478	}
3479
3480	if (!obj_check_undefineds(f)) {
3481		goto out;
3482	}
3483	obj_allocate_commons(f);
3484
3485	/* done with the module name, on to the optional var=value arguments */
3486	++optind;
3487
3488	if (optind < argc) {
3489		if (m_has_modinfo
3490			? !new_process_module_arguments(f, argc - optind, argv + optind)
3491			: !old_process_module_arguments(f, argc - optind, argv + optind))
3492		{
3493			goto out;
3494		}
3495	}
3496
3497	arch_create_got(f);
3498	hide_special_symbols(f);
3499
3500	if (k_new_syscalls)
3501		new_create_module_ksymtab(f);
3502
3503	/* archdata based on relocatable addresses */
3504	if (add_archdata(f, &archdata))
3505		goto out;
3506
3507	/* Find current size of the module */
3508	m_size = obj_load_size(f);
3509
3510
3511	m_addr = create_module(m_name, m_size);
3512	if (m_addr==-1) switch (errno) {
3513	case EEXIST:
3514		error_msg("A module named %s already exists", m_name);
3515		goto out;
3516	case ENOMEM:
3517		error_msg("Can't allocate kernel memory for module; needed %lu bytes",
3518				m_size);
3519		goto out;
3520	default:
3521		perror_msg("create_module: %s", m_name);
3522		goto out;
3523	}
3524
3525#if  !LOADBITS
3526	/*
3527	 * the PROGBITS section was not loaded by the obj_load
3528	 * now we can load them directly into the kernel memory
3529	 */
3530	//	f->imagebase = (char*) m_addr;
3531	f->imagebase = (ElfW(Addr)) m_addr;
3532	if (!obj_load_progbits(fp, f)) {
3533		delete_module(m_name);
3534		goto out;
3535	}
3536#endif
3537
3538	if (!obj_relocate(f, m_addr)) {
3539		delete_module(m_name);
3540		goto out;
3541	}
3542
3543	/* Do archdata again, this time we have the final addresses */
3544	if (add_archdata(f, &archdata))
3545		goto out;
3546
3547	if (k_new_syscalls
3548		? !new_init_module(m_name, f, m_size)
3549		: !old_init_module(m_name, f, m_size))
3550	{
3551		delete_module(m_name);
3552		goto out;
3553	}
3554
3555	exit_status = EXIT_SUCCESS;
3556
3557out:
3558	fclose(fp);
3559	return(exit_status);
3560}
3561