一、概述
模块是作为ELF对象文件存放在文件系统中的,并通过执行insmod程序链接到内核中。对于每个模块,系统都要分配一个包含以下数据结构的内存区。
一个module对象,表示模块名的一个以null结束的字符串,实现模块功能的代码。在2.6内核以前,insmod模块过程主要是通过modutils中的insmod加载,大量工作都是在用户空间完成。但在2.6内核以后,系统使用busybox的insmod指令,把大量工作移到内核代码处理,参见模块加载过程代码分析2.
二、相关数据结构
1.module对象描述一个模块。一个双向循环链表存放所有module对象,链表头部存放在modules变量中,而指向相邻单元的指针存放在每个module对象的list字段中。
struct module
{
 /*state 表示该模块的当前状态。 
 enum module_state 
 { 
     MODULE_STATE_LIVE, 
     MODULE_STATE_COMING, 
     MODULE_STATE_GOING, 
 }; 
 在装载期间,状态为 MODULE_STATE_COMING; 
 正常运行(完成所有初始化任务之后)时,状态为 MODULE_STATE_LIVE; 
 在模块正在卸载移除时,状态为 MODULE_STATE_GOING. 
 */
 enum module_state state;//模块内部状态
 //模块链表指针,将所有加载模块保存到一个双链表中,链表的表头是定义在 的全局变量 modules。 
 struct list_head list;
 char name[MODULE_NAME_LEN];//模块名
 /* Sysfs stuff. */
 struct module_kobject mkobj;//包含一个kobject数据结构
 struct module_attribute *modinfo_attrs;
 const char *version;
 const char *srcversion;
 struct kobject *holders_dir;
 /*syms,num_syms,crcs 用于管理模块导出的符号。syms是一个数组,有 num_syms 个数组项, 
 数组项类型为 kernel_symbol,负责将标识符(name)分配到内存地址(value): 
 struct kernel_symbol 
 { 
     unsigned long value; 
     const char *name; 
 }; 
 crcs 也是一个 num_syms 个数组项的数组,存储了导出符号的校验和,用于实现版本控制 
 */
 const struct kernel_symbol *syms;//指向导出符号数组的指针
 const unsigned long *crcs;//指向导出符号CRC值数组的指针
 unsigned int num_syms;//导出符号数
 struct kernel_param *kp;//内核参数
 unsigned int num_kp;//内核参数个数 
 /*在导出符号时,内核不仅考虑了可以有所有模块(不考虑许可证类型)使用的符号,还要考虑只能由 GPL 兼容模块使用的符号。 第三类的符号当前仍然可以有任意许可证的模块使用,但在不久的将来也会转变为只适用于 GPL 模块。gpl_syms,num_gpl_syms,gpl_crcs 成员用于只提供给 GPL 模块的符号;gpl_future_syms,num_gpl_future_syms,gpl_future_crcs 用于将来只提供给 GPL 模块的符号。unused_gpl_syms 和 unused_syms 以及对应的计数器和校验和成员描述。 这两个数组用于存储(只适用于 GPL)已经导出, 但 in-tree 模块未使用的符号。在out-of-tree 模块使用此类型符号时,内核将输出一个警告消息。 
*/ 
 unsigned int num_gpl_syms;//GPL格式导出符号数
 const struct kernel_symbol *gpl_syms;//指向GPL格式导出符号数组的指针
 const unsigned long *gpl_crcs;//指向GPL格式导出符号CRC值数组的指针
 
#ifdef CONFIG_MODULE_SIG  
 bool sig_ok;/* Signature was verified. */
#endif
  /* symbols that will be GPL-only in the near future. */
 const struct kernel_symbol *gpl_future_syms;
 const unsigned long *gpl_future_crcs;
 unsigned int num_gpl_future_syms;
  
 /*如果模块定义了新的异常,异常的描述保存在 extable数组中。 num_exentries 指定了数组的长度。 */
 unsigned int num_exentries;
 struct exception_table_entry *extable;
  
  /*模块的二进制数据分为两个部分;初始化部分和核心部分。 
 前者包含的数据在转载结束后都可以丢弃(例如:初始化函数),后者包含了正常运行期间需要的所有数据。   
 初始化部分的起始地址保存在 module_init,长度为 init_size 字节; 
 核心部分有 module_core 和 core_size 描述。 
 */
 int (*init)(void);//模块初始化方法,指向一个在模块初始化时调用的函数
 void *module_init;//用于模块初始化的动态内存区指针
 void *module_core;//用于模块核心函数与数据结构的动态内存区指针
 //用于模块初始化的动态内存区大小和用于模块核心函数与数据结构的动态内存区指针
 unsigned int init_size, core_size;
 //模块初始化的可执行代码大小,模块核心可执行代码大小,只当模块链接时使用
 unsigned int init_text_size, core_text_size;
 /* Size of RO sections of the module (text+rodata) */
 unsigned int init_ro_size, core_ro_size;
 struct mod_arch_specific arch;//依赖于体系结构的字段
 /*如果模块会污染内核,则设置 taints.污染意味着内核怀疑该模块做了一个有害的事情,可能妨碍内核的正常运作。 
 如果发生内核恐慌(在发生致命的内部错误,无法恢复正常运作时,将触发内核恐慌),那么错误诊断也会包含为什么内核被污染的有关信息。 
 这有助于开发者区分来自正常运行系统的错误报告和包含某些可疑因素的系统错误。 
 add_taint_module 函数用来设置 struct module 的给定实例的 taints 成员。 
  
 模块可能因两个原因污染内核: 
 1,如果模块的许可证是专有的,或不兼容 GPL,那么在模块载入内核时,会使用 TAINT_PROPRIETARY_MODULE. 
   由于专有模块的源码可能弄不到,模块在内核中作的任何事情都无法跟踪,因此,bug 很可能是由模块引入的。 
  
   内核提供了函数 license_is_gpl_compatible 来判断给定的许可证是否与 GPL 兼容。 
 2,TAINT_FORCED_MODULE 表示该模块是强制装载的。如果模块中没有提供版本信息,也称为版本魔术(version magic), 
   或模块和内核某些符号的版本不一致,那么可以请求强制装载。  
 */
 unsigned int taints;    /* same bits as kernel:tainted */
 char *args;//模块链接时使用的命令行参数
 
#ifdef CONFIG_SMP/
 void __percpu *percpu;/*percpu 指向属于模块的各 CPU 数据。它在模块装载时初始化*/   
 unsigned int percpu_size;
#endif
 
#ifdef CONFIG_TRACEPOINTS
 unsigned int num_tracepoints;
 struct tracepoint * const *tracepoints_ptrs;
#endif
#ifdef HAVE_JUMP_LABEL
 struct jump_entry *jump_entries;
 unsigned int num_jump_entries;
#endif
#ifdef CONFIG_TRACING
  unsigned int num_trace_bprintk_fmt;
 const char **trace_bprintk_fmt_start;
#endif
#ifdef CONFIG_EVENT_TRACING
 struct ftrace_event_call **trace_events;
 unsigned int num_trace_events;
#endif
#ifdef CONFIG_FTRACE_MCOUNT_RECORD
 unsigned int num_ftrace_callsites;
 unsigned long *ftrace_callsites;
#endif
 
#ifdef CONFIG_MODULE_UNLOAD
 /* What modules depend on me? */
 struct list_head source_list;
 /* What modules do I depend on? */
 struct list_head target_list;
 struct task_struct *waiter;//正卸载模块的进程
 void (*exit)(void);//模块退出方法
 /*module_ref 用于引用计数。系统中的每个 CPU,都对应到该数组中的数组项。该项指定了系统中有多少地方使用了该模块。 
内核提供了 try_module_get 和 module_put 函数,用对引用计数器加1或减1,如果调用者确信相关模块当前没有被卸载, 
也可以使用 __module_get 对引用计数加 1.相反,try_module_get 会确认模块确实已经加载。
 struct module_ref { 
   unsigned int incs; 
   unsigned int decs; 
  } 
*/ 
 struct module_ref __percpu *refptr;//模块计数器,每个cpu一个
 #endif

#ifdef CONFIG_CONSTRUCTORS
 /* Constructor functions. */
 ctor_fn_t *ctors;
 unsigned int num_ctors;
#endif
};

三、模块链接过程
用户可以通过执行insmod外部程序把一个模块链接到正在运行的内核中。该过程执行以下操作:
1.从命令行中读取要链接的模块名
2.确定模块对象代码所在的文件在系统目录树中的位置。
3.从磁盘读入存有模块目标代码的文件。
4.调用init_module()系统调用。函数将模块二进制文件复制到内核,然后由内核完成剩余的任务。
5.init_module函数通过系统调用层,进入内核到达内核函数 sys_init_module,这是加载模块的主要函数。
6.结束。

四、insmod过程解析
1.obj_file记录模块信息
struct obj_file
{
  ElfW(Ehdr) header;//指向elf header
  ElfW(Addr) baseaddr;//模块的基址
  struct obj_section **sections;//指向节区头部表,包含每个节区头部
  struct obj_section *load_order;//节区load顺序
  struct obj_section **load_order_search_start;//
  struct obj_string_patch_struct *string_patches;//patch的字符串
  struct obj_symbol_patch_struct *symbol_patches;//patch的符号
  int (*symbol_cmp)(const char *, const char *);//指向strcmp函数
  unsigned long (*symbol_hash)(const char *);//指向obj_elf_hash函数
  unsigned long local_symtab_size;//局部符号表大小
  struct obj_symbol **local_symtab;//局部符号表
  struct obj_symbol *symtab[HASH_BUCKETS];//符号hash表
  const char *filename;//模块名
  char *persist;
};

2.obj_section记录模块节区信息
struct obj_section
{
  ElfW(Shdr) header;//指向本节区头结构
  const char *name;//节区名
  char *contents;//从节区头内容偏移处获得的节区内容
  struct obj_section *load_next;//指向下一个节区
  int idx;//该节区索引值
};

3.module_stat结构记录每一个模块的信息
struct module_stat {
 char *name;//模块名称
 unsigned long addr;//模块地址
 unsigned long modstruct; /* COMPAT_2_0! *//* depends on architecture? */
 unsigned long size;//模块大小
 unsigned long flags;//标志
 long usecount;//模块计数
 size_t nsyms;//模块中的符号个数
 struct module_symbol *syms;//指向模块符号
 size_t nrefs;//模块依赖其他模块的个数
 struct module_stat **refs;//依赖的模块数组
 unsigned long status;//模块状态
};

4.
struct load_info {
 Elf_Ehdr *hdr;//指向elf头
 unsigned long len;
 Elf_Shdr *sechdrs;//指向节区头
 char *secstrings;//指向节区名称的字符串节区
 char *strtab;//指向符号节区
 unsigned long symoffs, stroffs;
 struct _ddebug *debug;
 unsigned int num_debug;
 bool sig_ok;
 struct {
  unsigned int sym, str, mod, vers, info, pcpu;
 } index;
};

5.代码分析

  1. int main(int argc, char **argv)
  2. {
  3. /* List of possible program names and the corresponding mainline routines */
  4. static struct { char *name; int (*handler)(int, char **); } mains[] =
  5. {
  6. { "insmod", &insmod_main },
  7. #ifdef COMBINE_modprobe
  8. { "modprobe", &modprobe_main },
  9. #endif
  10. #ifdef COMBINE_rmmod
  11. { "rmmod", &rmmod_main },
  12. #endif
  13. #ifdef COMBINE_ksyms
  14. { "ksyms", &ksyms_main },
  15. #endif
  16. #ifdef COMBINE_lsmod
  17. { "lsmod", &lsmod_main },
  18. #endif
  19. #ifdef COMBINE_kallsyms
  20. { "kallsyms", &kallsyms_main },
  21. #endif
  22. };
  23. #define MAINS_NO (sizeof(mains)/sizeof(mains[0]))
  24. static int mains_match;
  25. static int mains_which;
  26. char *p = strrchr(argv[0], '/');//查找‘/’字符出现的位置
  27. char error_id1[2048] = "The ";        /* Way oversized */
  28. char error_id2[2048] = "";        /* Way oversized */
  29. int i;
  30. p = p ? p + 1 : argv[0];//得到命令符,这里是insmod命令
  31. for (i = 0; i < MAINS_NO; ++i) {
  32. if (i) {
  33. xstrcat(error_id1, "/", sizeof(error_id1));//字符串连接函数
  34. if (i == MAINS_NO-1)
  35. xstrcat(error_id2, " or ", sizeof(error_id2));
  36. else
  37. xstrcat(error_id2, ", ", sizeof(error_id2));
  38. }
  39. xstrcat(error_id1, mains[i].name, sizeof(error_id1));
  40. xstrcat(error_id2, mains[i].name, sizeof(error_id2));
  41. if (strstr(p, mains[i].name)) {//命令跟数组的数据比较
  42. ++mains_match;//insmod命令时,mains_match=1
  43. mains_which = i;//得到insmod命令所在数组的位置,insmod命令为0
  44. }
  45. }
  46. /* Finish the error identifiers */
  47. if (MAINS_NO != 1)
  48. xstrcat(error_id1, " combined", sizeof(error_id1));
  49. xstrcat(error_id1, " binary", sizeof(error_id1));
  50. if (mains_match == 0 && MAINS_NO == 1)
  51. ++mains_match;        /* Not combined, any name will do */
  52. if (mains_match == 0) {
  53. error("%s does not have a recognisable name, ""the name must contain one of %s.",error_id1, error_id2);
  54. return(1);
  55. }
  56. else if (mains_match > 1) {
  57. error("%s has an ambiguous name, it must contain %s%s.", error_id1, MAINS_NO == 1 ? "" : "exactly one of ", error_id2);
  58. return(1);
  59. }
  60. else//mains_match=1,表示在数组中找到对应的指令
  61. return((mains[mains_which].handler)(argc, argv));//调用insmod_main()函数
  62. }
  63. int insmod_main(int argc, char **argv)
  64. {
  65. if (arch64())
  66. return insmod_main_64(argc, argv);
  67. else
  68. return insmod_main_32(argc, argv);
  69. }
  70. #if defined(COMMON_3264) && defined(ONLY_32)
  71. #define INSMOD_MAIN insmod_main_32    /* 32 bit version */
  72. #elif defined(COMMON_3264) && defined(ONLY_64)
  73. #define INSMOD_MAIN insmod_main_64    /* 64 bit version */
  74. #else
  75. #define INSMOD_MAIN insmod_main        /* Not common code */
  76. #endif
  77. int INSMOD_MAIN(int argc, char **argv)
  78. {
  79. int k_version;
  80. int k_crcs;
  81. char k_strversion[STRVERSIONLEN];
  82. struct option long_opts[] = {
  83. {"force", 0, 0, 'f'},
  84. {"help", 0, 0, 'h'},
  85. {"autoclean", 0, 0, 'k'},
  86. {"lock", 0, 0, 'L'},
  87. {"map", 0, 0, 'm'},
  88. {"noload", 0, 0, 'n'},
  89. {"probe", 0, 0, 'p'},
  90. {"poll", 0, 0, 'p'},    /* poll is deprecated, remove in 2.5 */
  91. {"quiet", 0, 0, 'q'},
  92. {"root", 0, 0, 'r'},
  93. {"syslog", 0, 0, 's'},
  94. {"kallsyms", 0, 0, 'S'},
  95. {"verbose", 0, 0, 'v'},
  96. {"version", 0, 0, 'V'},
  97. {"noexport", 0, 0, 'x'},
  98. {"export", 0, 0, 'X'},
  99. {"noksymoops", 0, 0, 'y'},
  100. {"ksymoops", 0, 0, 'Y'},
  101. {"persist", 1, 0, 'e'},
  102. {"numeric-only", 1, 0, 'N'},
  103. {"name", 1, 0, 'o'},
  104. {"blob", 1, 0, 'O'},
  105. {"prefix", 1, 0, 'P'},
  106. {0, 0, 0, 0}
  107. };
  108. char *m_name = NULL;
  109. char *blob_name = NULL;        /* Save object as binary blob */
  110. int m_version;
  111. ElfW(Addr) m_addr;
  112. unsigned long m_size;
  113. int m_crcs;
  114. char m_strversion[STRVERSIONLEN];
  115. char *filename;
  116. char *persist_name = NULL;    /* filename to hold any persistent data */
  117. int fp;
  118. struct obj_file *f;
  119. struct obj_section *kallsyms = NULL, *archdata = NULL;
  120. int o;
  121. int noload = 0;
  122. int dolock = 1; /*Note: was: 0; */
  123. int quiet = 0;
  124. int exit_status = 1;
  125. int force_kallsyms = 0;
  126. int persist_parms = 0;    /* does module have persistent parms? */
  127. int i;
  128. int gpl;
  129. error_file = "insmod";
  130. /* To handle repeated calls from combined modprobe */
  131. errors = optind = 0;
  132. /* Process the command line. */
  133. while ((o = getopt_long(argc, argv, "fhkLmnpqrsSvVxXyYNe:o:O:P:R:",&long_opts[0], NULL)) != EOF)
  134. switch (o) {
  135. case 'f':    /* force loading */
  136. flag_force_load = 1;
  137. break;
  138. case 'h': /* Print the usage message. */
  139. insmod_usage();
  140. break;
  141. case 'k':    /* module loaded by kerneld, auto-cleanable */
  142. flag_autoclean = 1;
  143. break;
  144. case 'L':    /* protect against recursion. */
  145. dolock = 1;
  146. break;
  147. case 'm':    /* generate load map */
  148. flag_load_map = 1;
  149. break;
  150. case 'n':    /* don't load, just check */
  151. noload = 1;
  152. break;
  153. case 'p':    /* silent probe mode */
  154. flag_silent_probe = 1;
  155. break;
  156. case 'q':    /* Don't print unresolved symbols */
  157. quiet = 1;
  158. break;
  159. case 'r':    /* allow root to load non-root modules */
  160. root_check_off = !root_check_off;
  161. break;
  162. case 's':    /* start syslog */
  163. setsyslog("insmod");
  164. break;
  165. case 'S':    /* Force kallsyms */
  166. force_kallsyms = 1;
  167. break;
  168. case 'v':    /* verbose output */
  169. flag_verbose = 1;
  170. break;
  171. case 'V':
  172. fputs("insmod version " MODUTILS_VERSION "\n", stderr);
  173. break;
  174. case 'x':    /* do not export externs */
  175. flag_export = 0;
  176. break;
  177. case 'X':    /* do export externs */
  178. #ifdef HAS_FUNCTION_DESCRIPTORS
  179. fputs("This architecture has function descriptors, exporting everything is unsafe\n"
  180. "You must explicitly export the desired symbols with EXPORT_SYMBOL()\n", stderr);
  181. #else
  182. flag_export = 1;
  183. #endif
  184. break;
  185. case 'y':    /* do not define ksymoops symbols */
  186. flag_ksymoops = 0;
  187. break;
  188. case 'Y':    /* do define ksymoops symbols */
  189. flag_ksymoops = 1;
  190. break;
  191. case 'N':    /* only check numeric part of kernel version */
  192. flag_numeric_only = 1;
  193. break;
  194. case 'e':    /* persistent data filename */
  195. free(persist_name);
  196. persist_name = xstrdup(optarg);
  197. break;
  198. case 'o':    /* name the output module */
  199. m_name = optarg;
  200. break;
  201. case 'O':    /* save the output module object */
  202. blob_name = optarg;
  203. break;
  204. case 'P':    /* use prefix on crc */
  205. set_ncv_prefix(optarg);
  206. break;
  207. default:
  208. insmod_usage();
  209. break;
  210. }
  211. if (optind >= argc) {//参数为0,则输出insmod用法介绍
  212. insmod_usage();
  213. }
  214. filename = argv[optind++];//获得要加载的模块路径名
  215. if (config_read(0, NULL, "", NULL) < 0) {//modutil配置相关???
  216. error("Failed handle configuration");
  217. }
  218. //清空persist_name
  219. if (persist_name && !*persist_name &&(!persistdir || !*persistdir)) {
  220. free(persist_name);
  221. persist_name = NULL;
  222. if (flag_verbose) {
  223. lprintf("insmod: -e \"\" ignored, no persistdir");
  224. ++warnings;
  225. }
  226. }
  227. if (m_name == NULL) {
  228. size_t len;
  229. char *p;
  230. //根据模块的路径名获取模块的名称
  231. if ((p = strrchr(filename, '/')) != NULL)//找到最后一个'/'的位置
  232. p++;
  233. else
  234. p = filename;
  235. len = strlen(p);
  236. //去除模块名的后缀,保存在m_name中
  237. if (len > 2 && p[len - 2] == '.' && p[len - 1] == 'o')
  238. len -= 2;
  239. else if (len > 4 && p[len - 4] == '.' && p[len - 3] == 'm'&& p[len - 2] == 'o' && p[len - 1] == 'd')
  240. len -= 4;
  241. #ifdef CONFIG_USE_ZLIB
  242. else if (len > 5 && !strcmp(p + len - 5, ".o.gz"))
  243. len -= 5;
  244. #endif
  245. m_name = xmalloc(len + 1);
  246. memcpy(m_name, p, len);//模块名称拷贝到m_name[]中
  247. m_name[len] = '\0';
  248. }
  249. //根据模块路径,检查模块是否存在
  250. if (!strchr(filename, '/') && !strchr(filename, '.')) {
  251. char *tmp = search_module_path(filename);//查找模块路径???
  252. if (tmp == NULL) {
  253. error("%s: no module by that name found", filename);
  254. return 1;
  255. }
  256. filename = tmp;
  257. lprintf("Using %s", filename);
  258. } else if (flag_verbose)
  259. lprintf("Using %s", filename);
  260. //打开要加载的模块文件
  261. if ((fp = gzf_open(filename, O_RDONLY)) == -1) {
  262. error("%s: %m", filename);
  263. return 1;
  264. }
  265. /* Try to prevent multiple simultaneous loads. */
  266. if (dolock)
  267. flock(fp, LOCK_EX);
  268. /*
  269. type的三种类型,影响get_kernle_info的流程。
  270. #define K_SYMBOLS 1 //Want info about symbols
  271. #define K_INFO 2 Want extended module info
  272. #define K_REFS 4 Want info about references
  273. */
  274. //负责取得kernel中先以注册的modules,放入module_stat中,并将kernel实现的各个symbol放入ksyms中,个数为ksyms。get_kernel_info最终调用new_get_kernel_info
  275. if (!get_kernel_info(K_SYMBOLS))
  276. goto out;
  277. set_ncv_prefix(NULL);//判断symbol name中是否有前缀,象_smp之类,这里没有。
  278. for (i = 0; !noload && i < n_module_stat; ++i) {//判断是否有同名的模块存在
  279. if (strcmp(module_stat[i].name, m_name) == 0) {//遍历kernel中所有的模块,比较名称
  280. error("a module named %s already exists", m_name);
  281. goto out;
  282. }
  283. }
  284. error_file = filename;
  285. if ((f = obj_load(fp, ET_REL, filename)) == NULL)//将模块文件读入到struct obj_file结构f
  286. goto out;
  287. if (check_gcc_mismatch(f, filename))//检查编译器版本
  288. goto out;
  289. //检查内核和module的版本信息
  290. k_version = get_kernel_version(k_strversion);
  291. m_version = get_module_version(f, m_strversion);
  292. if (m_version == -1) {
  293. error("couldn't find the kernel version the module was compiled for");
  294. goto out;
  295. }
  296. //接下来还要测试内核和模块是否使用了版本的附加信息
  297. k_crcs = is_kernel_checksummed();
  298. m_crcs = is_module_checksummed(f);
  299. if ((m_crcs == 0 || k_crcs == 0) &&strncmp(k_strversion, m_strversion, STRVERSIONLEN) != 0) {
  300. if (flag_force_load) {
  301. lprintf("Warning: kernel-module version mismatch\n"
  302. "\t%s was compiled for kernel version %s\n"
  303. "\twhile this kernel is version %s",
  304. filename, m_strversion, k_strversion);
  305. ++warnings;
  306. } else {
  307. if (!quiet)
  308. error("kernel-module version mismatch\n"
  309. "\t%s was compiled for kernel version %s\n"
  310. "\twhile this kernel is version %s.",
  311. filename, m_strversion, k_strversion);
  312. goto out;
  313. }
  314. }
  315. if (m_crcs != k_crcs)//设置新的符号比较函数和hash函数,重构hash表(即symtab表)。
  316. obj_set_symbol_compare(f, ncv_strcmp, ncv_symbol_hash);
  317. //检查GPL license
  318. gpl = obj_gpl_license(f, NULL) == 0;
  319. //替换模块中的symbol值为其他已经存在的模块中相同符号的值
  320. //如果内核模块中有该符号,则将该符号的value该为内核中(ksyms[])的符号值
  321. //修改的是hash符号表中或者局部符号表中的符号值
  322. add_kernel_symbols(f, gpl);
  323. #ifdef COMPAT_2_0//linux 内核2.0版本以前
  324. if (k_new_syscalls ? !create_this_module(f, m_name): !old_create_mod_use_count(f))
  325. goto out;
  326. #else
  327. if (!create_this_module(f, m_name))//创建.this节区,添加一个"__this_module"符号
  328. goto out;
  329. #endif
  330. //这个函数的作用是创建文件的.GOT段,.GOT全称是global offset table。在这个节区里保存的是绝对地址,这些地址不受重定位的影响。如果程序需要直接引用符号的绝对地址,这些符号就必须在.GOT段中出现
  331. arch_create_got(f);
  332. if (!obj_check_undefineds(f, quiet)) {//检查是否还有未解析的symbol
  333. if (!gpl && !quiet) {
  334. if (gplonly_seen)
  335. error("\n"
  336. "Hint: You are trying to load a module without a GPL compatible license\n"
  337. " and it has unresolved symbols. The module may be trying to access\n"
  338. " GPLONLY symbols but the problem is more likely to be a coding or\n"
  339. " user error. Contact the module supplier for assistance, only they\n"
  340. " can help you.\n");
  341. else
  342. error("\n"
  343. "Hint: You are trying to load a module without a GPL compatible license\n"
  344. " and it has unresolved symbols. Contact the module supplier for\n"
  345. " assistance, only they can help you.\n");
  346. }
  347. goto out;
  348. }
  349. obj_allocate_commons(f);//处理未分配资源的符号
  350. //检查模块参数,即检查那些模块通过module_param(type, charp, S_IRUGO);声明的参数
  351. check_module_parameters(f, &persist_parms);
  352. check_tainted_module(f, noload);//???
  353. if (optind < argc) {//如果命令行里带了参数,处理命令行参数
  354. if (!process_module_arguments(f, argc - optind, argv + optind, 1))
  355. goto out;
  356. }
  357. //将符号“cleanup_module”,“init_module”,“kernel_version”的属性改为local(局部),从而使其外部不可见
  358. hide_special_symbols(f);
  359. //如果命令行参数来自文件,将文件名保存好,下面要从那里读出参数值
  360. if (persist_parms && persist_name && *persist_name) {
  361. f->persist = persist_name;
  362. persist_name = NULL;
  363. }
  364. //防止-e""这样的恶作剧
  365. if (persist_parms &&persist_name && !*persist_name) {
  366. int j, l = strlen(filename);
  367. char *relative = NULL;
  368. char *p;
  369. for (i = 0; i < nmodpath; ++i) {
  370. p = modpath[i].path;
  371. j = strlen(p);
  372. while (j && p[j] == '/')
  373. --j;
  374. if (j < l && strncmp(filename, p, j) == 0 && filename[j] == '/') {
  375. while (filename[j] == '/')
  376. ++j;
  377. relative = xstrdup(filename+j);
  378. break;
  379. }
  380. }
  381. if (relative) {
  382. i = strlen(relative);
  383. if (i > 3 && strcmp(relative+i-3, ".gz") == 0)
  384. relative[i -= 3] = '\0';
  385. if (i > 2 && strcmp(relative+i-2, ".o") == 0)
  386. relative[i -= 2] = '\0';
  387. else if (i > 4 && strcmp(relative+i-4, ".mod") == 0)
  388. relative[i -= 4] = '\0';
  389. f->persist = xmalloc(strlen(persistdir) + 1 + i + 1);
  390. strcpy(f->persist, persistdir);    /* safe, xmalloc */
  391. strcat(f->persist, "/");    /* safe, xmalloc */
  392. strcat(f->persist, relative);    /* safe, xmalloc */
  393. free(relative);
  394. }
  395. else
  396. error("Cannot calculate persistent filename");
  397. }
  398. //接下来是一些健康检查
  399. if (f->persist && *(f->persist) != '/') {
  400. error("Persistent filenames must be absolute, ignoring '%s'", f->persist);
  401. free(f->persist);
  402. f->persist = NULL;
  403. }
  404. if (f->persist && !flag_ksymoops) {
  405. error("has persistent data but ksymoops symbols are not available");
  406. free(f->persist);
  407. f->persist = NULL;
  408. }
  409. if (f->persist && !k_new_syscalls) {
  410. error("has persistent data but the kernel is too old to support it");
  411. free(f->persist);
  412. f->persist = NULL;
  413. }
  414. if (persist_parms && flag_verbose) {
  415. if (f->persist)
  416. lprintf("Persist filename '%s'", f->persist);
  417. else
  418. lprintf("No persistent filename available");
  419. }
  420. if (f->persist) {
  421. FILE *fp = fopen(f->persist, "r");
  422. if (!fp) {
  423. if (flag_verbose)
  424. lprintf("Cannot open persist file '%s' %m", f->persist);
  425. }
  426. else {
  427. int pargc = 0;
  428. char *pargv[1000];    /* hard coded but big enough */
  429. char line[3000];    /* hard coded but big enough */
  430. char *p;
  431. while (fgets(line, sizeof(line), fp)) {
  432. p = strchr(line, '\n');
  433. if (!p) {
  434. error("Persistent data line is too long\n%s", line);
  435. break;
  436. }
  437. *p = '\0';
  438. p = line;
  439. while (isspace(*p))
  440. ++p;
  441. if (!*p || *p == '#')
  442. continue;
  443. if (pargc == sizeof(pargv)/sizeof(pargv[0])) {
  444. error("More than %d persistent parameters", pargc);
  445. break;
  446. }
  447. pargv[pargc++] = xstrdup(p);
  448. }
  449. fclose(fp);
  450. if (!process_module_arguments(f, pargc, pargv, 0))
  451. goto out;
  452. while (pargc--)
  453. free(pargv[pargc]);
  454. }
  455. }
  456. //ksymoops 是一个调试辅助工具,它将试图将代码转换为指令并将堆栈值映射到内核符号。
  457. if (flag_ksymoops)
  458. add_ksymoops_symbols(f, filename, m_name);
  459. if (k_new_syscalls)//k_new_syscalls标志用于测试内核版本
  460. create_module_ksymtab(f);//创建模块要导出的符号节区ksymtab,并将要导出的符号加入该节区
  461. //创建名为“__archdata” (宏 ARCH_SEC_NAME 的定义)的段
  462. if (add_archdata(f, &archdata))
  463. goto out;
  464. //如果symbol使用的都是kernel提供的,就添加一个.kallsyms节区
  465. //这个函数主要是处理内核导出符号。
  466. if (add_kallsyms(f, &kallsyms, force_kallsyms))
  467. goto out;
  468. /**** No symbols or sections to be changed after kallsyms above ***/
  469. if (errors)
  470. goto out;
  471. //如果flag_slient_probe已经设置,说明我们不想真正安装模块,只是想测试一下,那么到这里测试已经完成了,模块一切正常.
  472. if (flag_silent_probe) {
  473. exit_status = 0;
  474. goto out;
  475. }
  476. //计算载入模块所需的大小,即各个节区的大小和
  477. m_size = obj_load_size(f);
  478. //如果noload设置了,那么我们选择不真正加载模块。随便给加载地址就完了.
  479. if (noload) {
  480. m_addr = 0x12340000;
  481. } else {
  482. errno = 0;
  483. //调用sys_create_module系统调用创建模块,分配module的空间,返回模块在内核空间的地址.这里的module结构不是内核使用的那个,它定义在./modutilst-2.4.0/include/module.h中。函数最终会调用系统调用sys_create_module,生成一个模块对象,并链入模块的内核链表
  484. //模块对象的大小就是各个节区大小的和,这里为什么分配的空间m_size不是sizeof(module)+各个节区大小的和?因为第一个节区.this的大小正好就是sizeof(module),所以第一个节区就是struct module结构。
  485. //注意:区分后边还有一次在用户空间为模块分配空间,然后先把模块section拷贝到用户空间的模块影像中,然后再由sys_init_module()函数将用户空间的模块映像拷贝到内核空间的模块地址,即这里的m_addr。
  486. m_addr = create_module(m_name, m_size);
  487. m_addr |= arch_module_base (f);//#define arch_module_base(m) ((ElfW(Addr))0)
  488. //检查是否成功创建module结构
  489. switch (errno) {
  490. case 0:
  491. break;
  492. case EEXIST:
  493. if (dolock) {
  494. exit_status = 0;
  495. goto out;
  496. }
  497. error("a module named %s already exists", m_name);
  498. goto out;
  499. case ENOMEM:
  500. error("can't allocate kernel memory for module; needed %lu bytes",m_size);
  501. goto out;
  502. default:
  503. error("create_module: %m");
  504. goto out;
  505. }
  506. }
  507. //如果模块运行时参数使用了文件,而且需要真正加载
  508. if (f->persist && !noload) {
  509. struct {
  510. struct module m;
  511. int data;
  512. } test_read;
  513. memset(&test_read, 0, sizeof(test_read));
  514. test_read.m.size_of_struct = -sizeof(test_read.m); /* -ve size => read, not write */
  515. test_read.m.read_start = m_addr + sizeof(struct module);
  516. test_read.m.read_end = test_read.m.read_start + sizeof(test_read.data);
  517. if (sys_init_module(m_name, (struct module *) &test_read)) {
  518. int old_errors = errors;
  519. error("has persistent data but the kernel is too old to support it."
  520. " Expect errors during rmmod as well");
  521. errors = old_errors;
  522. }
  523. }
  524. //模块在内核的地址.而在模块elf文件里,节区在内存的位置是假设文件从0地址加载而得出的,现在就要根据base值调整。base就是create_module时分配的地址m_addr
  525. if (!obj_relocate(f, m_addr)) {
  526. if (!noload)
  527. delete_module(m_name);
  528. goto out;
  529. }
  530. //至此相当于磁盘中的elf文件格式的.ko文件的内容,已经全部加载到内存中,需要重定位的符号已经进行了重定位,符号地址变成了真正的在内存中的地址,即绝对地址。
  531. /* Do archdata again, this time we have the final addresses */
  532. if (add_archdata(f, &archdata))
  533. goto out;
  534. //用绝对地址重新生成kallsyms段的内容
  535. if (add_kallsyms(f, &kallsyms, force_kallsyms))
  536. goto out;
  537. #ifdef COMPAT_2_0//2.0以前的版本
  538. if (k_new_syscalls)
  539. init_module(m_name, f, m_size, blob_name, noload, flag_load_map);
  540. else if (!noload)
  541. old_init_module(m_name, f, m_size);
  542. #else
  543. init_module(m_name, f, m_size, blob_name, noload, flag_load_map);
  544. #endif
  545. if (errors) {
  546. if (!noload)
  547. delete_module(m_name);
  548. goto out;
  549. }
  550. if (warnings && !noload)
  551. lprintf("Module %s loaded, with warnings", m_name);
  552. exit_status = 0;
  553. out:
  554. if (dolock)
  555. flock(fp, LOCK_UN);
  556. close(fp);
  557. if (!noload)
  558. snap_shot(NULL, 0);
  559. return exit_status;
  560. }
  561. static int new_get_kernel_info(int type)
  562. {
  563. struct module_stat *modules;
  564. struct module_stat *m;
  565. struct module_symbol *syms;
  566. struct module_symbol *s;
  567. size_t ret;
  568. size_t bufsize;
  569. size_t nmod;
  570. size_t nsyms;
  571. size_t i;
  572. size_t j;
  573. char *module_names;
  574. char *mn;
  575. drop();//首先清除module_stat内容,module_stat是个全局变量,保存模块信息
  576. //指针分配空间
  577. module_names = xmalloc(bufsize = 256);
  578. //取得系统中现有所有的module名称,ret返回个数,module_names返回各个module名称,字符0分割
  579. while (query_module(NULL, QM_MODULES, module_names, bufsize, &ret)) {
  580. if (errno != ENOSPC) {
  581. error("QM_MODULES: %m\n");
  582. return 0;
  583. }
  584. /*
  585. 会调用realloc(void *mem_address, unsigned int newsize)函数,此先判断当前的指针是否有足够的连续空间,如果有,扩大mem_address指向的地址,并且将mem_address返回,如果空间不够,先按照newsize指定的大小分配空间,将原有数据从头到尾拷贝到新分配的内存区域,而后释放原来mem_address所指内存区域(注意:原来指针是自动释放,不需要使用free),同时返回新分配的内存区域的首地址。即重新分配存储器块的地址。
  586. */
  587. module_names = xrealloc(module_names, bufsize = ret);
  588. }
  589. module_name_list = module_names;//指向系统中所有模块名称的起始地址
  590. l_module_name_list = bufsize;//所有模块名称的大小,即module_names大小
  591. n_module_stat = nmod = ret;//返回模块个数
  592. //分配空间,地址付给全局变量module_stat
  593. module_stat = modules = xmalloc(nmod * sizeof(struct module_stat));
  594. memset(modules, 0, nmod * sizeof(struct module_stat));
  595. //循环取得各个module的信息,QM_INFO的使用。
  596. for (i = 0, mn = module_names, m = modules;i < nmod;++i, ++m, mn += strlen(mn) + 1) {
  597. struct module_info info;
  598. //info包括module的地址,大小,flag和使用计数器。
  599. m->name = mn;//模块名称给module_stat结构
  600. if (query_module(mn, QM_INFO, &info, sizeof(info), &ret)) {
  601. if (errno == ENOENT) {
  602. m->flags = NEW_MOD_DELETED;
  603. continue;
  604. }
  605. error("module %s: QM_INFO: %m", mn);
  606. return 0;
  607. }
  608. m->addr = info.addr;//模块地址给module_stat结构
  609. if (type & K_INFO) {//取得module的信息
  610. m->size = info.size;
  611. m->flags = info.flags;
  612. m->usecount = info.usecount;
  613. m->modstruct = info.addr;
  614. }//将info值传给module_stat结构
  615. if (type & K_REFS) {//取得module的引用关系
  616. int mm;
  617. char *mrefs;
  618. char *mr;
  619. mrefs = xmalloc(bufsize = 64);
  620. while (query_module(mn, QM_REFS, mrefs, bufsize, &ret)) {//查找mn模块引用的模块名
  621. if (errno != ENOSPC) {
  622. error("QM_REFS: %m");
  623. return 1;
  624. }
  625. mrefs = xrealloc(mrefs, bufsize = ret);
  626. }
  627. for (j = 0, mr = mrefs;j < ret;++j, mr += strlen(mr) + 1) {
  628. for (mm = 0; mm < i; ++mm) {
  629. if (strcmp(mr, module_stat[mm].name) == 0) {
  630. m->nrefs += 1;
  631. m->refs = xrealloc(m->refs, m->nrefs * sizeof(struct module_stat **));
  632. m->refs[m->nrefs - 1] = module_stat + mm;//引用的模块名
  633. break;
  634. }
  635. }
  636. }
  637. free(mrefs);
  638. }
  639. //这里是遍历内核中其他模块的所有符号
  640. if (type & K_SYMBOLS) { /* 取得symbol信息,正是我们要得*/
  641. syms = xmalloc(bufsize = 1024);
  642. //取得mn模块的符号信息,保存在syms数组中
  643. while (query_module(mn, QM_SYMBOLS, syms, bufsize, &ret)) {
  644. if (errno == ENOSPC) {
  645. syms = xrealloc(syms, bufsize = ret);
  646. continue;
  647. }
  648. if (errno == ENOENT) {
  649. m->flags = NEW_MOD_DELETED;
  650. free(syms);
  651. goto next;
  652. } else {
  653. error("module %s: QM_SYMBOLS: %m", mn);
  654. return 0;
  655. }
  656. }
  657. nsyms = ret;
  658. //syms是module_symbol结构,ret返回symbol个数
  659. m->nsyms = nsyms;//符号个数
  660. m->syms = syms;//符号信息
  661. //name原来只是一个结构内的偏移,加上结构地址为真正的字符串地址
  662. for (j = 0, s = syms; j < nsyms; ++j, ++s)
  663. s->name += (unsigned long) syms;
  664. }
  665. next:
  666. }
  667. //这里是取得内核符号
  668. if (type & K_SYMBOLS) { /* Want info about symbols */
  669. syms = xmalloc(bufsize = 16 * 1024);
  670. //name为NULL,返回内核符号信息
  671. while (query_module(NULL, QM_SYMBOLS, syms, bufsize, &ret)) {
  672. if (errno != ENOSPC) {
  673. error("kernel: QM_SYMBOLS: %m");
  674. return 0;
  675. }
  676. syms = xrealloc(syms, bufsize = ret);//扩展空间
  677. }
  678. //将值返回给nksyms和ksyms两个全局变量存储。
  679. nksyms = nsyms = ret;//内核符号个数
  680. ksyms = syms;//内核符号
  681. /* name原来只是一个结构内的偏移,加上结构地址为真正的字符串地址 */
  682. for (j = 0, s = syms; j < nsyms; ++j, ++s)
  683. s->name += (unsigned long) syms;
  684. }
  685. return 1;
  686. }
  687. struct obj_file *obj_load (int fp, Elf32_Half e_type, const char *filename)
  688. {
  689. struct obj_file *f;
  690. ElfW(Shdr) *section_headers;
  691. int shnum, i;
  692. char *shstrtab;
  693. f = arch_new_file();//创建一个新的obj_file结构
  694. memset(f, 0, sizeof(*f));
  695. f->symbol_cmp = strcmp;//设置symbol名的比较函数就是strcmp
  696. f->symbol_hash = obj_elf_hash;//设置计算symbol hash值的函数
  697. f->load_order_search_start = &f->load_order;//??
  698. gzf_lseek(fp, 0, SEEK_SET);//文件指针设置到文件头
  699. //取得object文件的ELF头结构。
  700. if (gzf_read(fp, &f->header, sizeof(f->header)) != sizeof(f->header))
  701. {
  702. error("cannot read ELF header from %s", filename);
  703. return NULL;
  704. }
  705. //判断ELF的magic,是否是ELF文件格式
  706. if (f->header.e_ident[EI_MAG0] != ELFMAG0
  707. || f->header.e_ident[EI_MAG1] != ELFMAG1
  708. || f->header.e_ident[EI_MAG2] != ELFMAG2
  709. || f->header.e_ident[EI_MAG3] != ELFMAG3)
  710. {
  711. error("%s is not an ELF file", filename);
  712. return NULL;
  713. }
  714. //检查architecture
  715. if (f->header.e_ident[EI_CLASS] != ELFCLASSM//i386的机器上为ELFCLASS32,表示32bit
  716. || f->header.e_ident[EI_DATA] != ELFDATAM//此处值为ELFDATA2LSB,表示编码方式
  717. || f->header.e_ident[EI_VERSION] != EV_CURRENT//此值固定,表示版本
  718. || !MATCH_MACHINE(f->header.e_machine))//机器类型
  719. {
  720. error("ELF file %s not for this architecture", filename);
  721. return NULL;
  722. }
  723. //判断目标文件类型
  724. if (f->header.e_type != e_type && e_type != ET_NONE)//.ko文件类型必为ET_REL
  725. {
  726. switch (e_type) {
  727. case ET_REL:
  728. error("ELF file %s not a relocatable object", filename);
  729. break;
  730. case ET_EXEC:
  731. error("ELF file %s not an executable object", filename);
  732. break;
  733. default:
  734. error("ELF file %s has wrong type, expecting %d got %d",
  735. filename, e_type, f->header.e_type);
  736. break;
  737. }
  738. return NULL;
  739. }
  740. //检查elf文件头指定的节区头的大小是否一致
  741. if (f->header.e_shentsize != sizeof(ElfW(Shdr)))
  742. {
  743. error("section header size mismatch %s: %lu != %lu",filename,
  744. (unsigned long)f->header.e_shentsize,
  745. (unsigned long)sizeof(ElfW(Shdr)));
  746. return NULL;
  747. }
  748. shnum = f->header.e_shnum;//文件中节区个数
  749. f->sections = xmalloc(sizeof(struct obj_section *) * shnum);//为section开辟空间
  750. memset(f->sections, 0, sizeof(struct obj_section *) * shnum);
  751. //每个节区都有一个节区头部表,为shnum个节区头部表分配空间
  752. section_headers = alloca(sizeof(ElfW(Shdr)) * shnum);
  753. gzf_lseek(fp, f->header.e_shoff, SEEK_SET);//指针移到节区头部表开始位置
  754. //读取shnum个节区头部表(每个节区都有一个节区头部表)内容保存在section_headers中
  755. if (gzf_read(fp, section_headers, sizeof(ElfW(Shdr))*shnum) != sizeof(ElfW(Shdr))*shnum)
  756. {
  757. error("error reading ELF section headers %s: %m", filename);
  758. return NULL;
  759. }
  760. for (i = 0; i < shnum; ++i)//遍历所有的节区
  761. {
  762. struct obj_section *sec;
  763. f->sections[i] = sec = arch_new_section();//分配内存给每个section
  764. memset(sec, 0, sizeof(*sec));
  765. sec->header = section_headers[i];//设置obj_section结构的sec的header指向本节区的节区头部表
  766. sec->idx = i;//节区索引
  767. switch (sec->header.sh_type)//section的类型
  768. {
  769. case SHT_NULL:
  770. case SHT_NOTE:
  771. case SHT_NOBITS:/* ignore */
  772. break;
  773. case SHT_PROGBITS:
  774. case SHT_SYMTAB:
  775. case SHT_STRTAB:
  776. case SHT_RELM://将以上各种类型的section内容读到sec->contents结构中。
  777. if (sec->header.sh_size > 0)
  778. {
  779. sec->contents = xmalloc(sec->header.sh_size);
  780. //指针移到节区的第一个字节与文件头之间的偏移
  781. gzf_lseek(fp, sec->header.sh_offset, SEEK_SET);
  782. //读取节区中内容
  783. if (gzf_read(fp, sec->contents, sec->header.sh_size) != sec->header.sh_size)
  784. {
  785. error("error reading ELF section data %s: %m", filename);
  786. return NULL;
  787. }
  788. }
  789. else
  790. sec->contents = NULL;
  791. break;
  792. //描述relocation的section
  793. #if SHT_RELM == SHT_REL
  794. case SHT_RELA:
  795. if (sec->header.sh_size) {
  796. error("RELA relocations not supported on this architecture %s", filename);
  797. return NULL;
  798. }
  799. break;
  800. #else
  801. case SHT_REL:
  802. if (sec->header.sh_size) {
  803. error("REL relocations not supported on this architecture %s", filename);
  804. return NULL;
  805. }
  806. break;
  807. #endif
  808. default:
  809. if (sec->header.sh_type >= SHT_LOPROC)
  810. {
  811. if (arch_load_proc_section(sec, fp) < 0)
  812. return NULL;
  813. break;
  814. }
  815. error("can't handle sections of type %ld %s",(long)sec->header.sh_type, filename);
  816. return NULL;
  817. }
  818. }
  819. //shstrndx存的是section字符串表的索引值,就是第几个section
  820. //shstrtab就是那个section了。找到节区名字符串节区,把字符串节区内容地址付给shstrtab指针
  821. shstrtab = f->sections[f->header.e_shstrndx]->contents;
  822. for (i = 0; i < shnum; ++i)
  823. {
  824. struct obj_section *sec = f->sections[i];
  825. sec->name = shstrtab + sec->header.sh_name;//sh_name字段是节区头部字符串表节区的索引
  826. }//根据strtab,取得每个section的名字
  827. //遍历节区查找符号表
  828. for (i = 0; i < shnum; ++i)
  829. {
  830. struct obj_section *sec = f->sections[i];
  831. //也就是说即使modinfo和modstring有此标志位,也去掉。
  832. if (strcmp(sec->name, ".modinfo") == 0 ||strcmp(sec->name, ".modstring") == 0)
  833. sec->header.sh_flags &= ~SHF_ALLOC;//ALLOC表示此section是否占用内存,这两个节区不占用内存
  834. if (sec->header.sh_flags & SHF_ALLOC)//此节区在进程执行过程中占用内存
  835. obj_insert_section_load_order(f, sec);//确定section load的顺序,根据的是flag的类型加权得到优先级
  836. switch (sec->header.sh_type)
  837. {
  838. case SHT_SYMTAB://符号表节区,就是.symtab节区
  839. {
  840. unsigned long nsym, j;
  841. char *strtab;
  842. ElfW(Sym) *sym;
  843. //节区的大小若不等于符号表结构的大小,则出错
  844. if (sec->header.sh_entsize != sizeof(ElfW(Sym)))
  845. {
  846. error("symbol size mismatch %s: %lu != %lu",filename,(unsigned long)sec->header.sh_entsize,(unsigned long)sizeof(ElfW(Sym)));
  847. return NULL;
  848. }
  849. //计算符号表表项个数,nsym也就是symbol个数,我的fedcore有560个符号(结构)
  850. nsym = sec->header.sh_size / sizeof(ElfW(Sym));
  851. //sh_link是符号字符串表的索引值,f->sections[sec->header.sh_link]就是.strtab节区
  852. strtab = f->sections[sec->header.sh_link]->contents;//符号字符串表节区的内容
  853. sym = (ElfW(Sym) *) sec->contents;//符号表节区的内容Elf32_sym结构
  854. j = f->local_symtab_size = sec->header.sh_info;//本模块局部符号的size
  855. f->local_symtab = xmalloc(j *= sizeof(struct obj_symbol *));//为本模块局部符号分配空间
  856. memset(f->local_symtab, 0, j);
  857. //遍历要加载模块的符号表节区内容的符号Elf32_sym结构
  858. for (j = 1, ++sym; j < nsym; ++j, ++sym)
  859. {
  860. const char *name;
  861. if (sym->st_name)//有值就是符号字符串表strtab的索引值
  862. name = strtab+sym->st_name;
  863. else//如果为零,此symbol name是一个section的name,比如.rodata之类的
  864. name = f->sections[sym->st_shndx]->name;
  865. //obj_add_symbol将符号加入到f->symbab这个hash表中,sym->st_shndx是相关节区头部表索引。如果一个符号的取值引用了某个节区中的特定位置,那么它的节区索引成员(st_shndx)包含了其在节区头部表中的索引。(比如说符号“function_x”定义在节区.rodata中,则sym->st_shndx是节区.rodata的索引值,sym->st_value是指在该节区中的到符号位置的偏移,即符号“function_x”在模块中的地址由节区.rodata->contens+sym->st_value位置处的数值指定)
  866. //局部符号会添加到f->local_symtab表中,其余符号会添加到hash表f->symtab中(),注意:局部符号也可能添加到hash表中
  867. obj_add_symbol(f, name, j, sym->st_info, sym->st_shndx,sym->st_value, sym->st_size);
  868. }
  869. }
  870. break;
  871. }
  872. }
  873. //重定位是将符号引用与符号定义进行连接的过程。例如,当程序调用了一个函数时,相关的调用指令必须把控制传输到适当的目标执行地址。
  874. for (i = 0; i < shnum; ++i)
  875. {
  876. struct obj_section *sec = f->sections[i];
  877. switch (sec->header.sh_type)
  878. {
  879. case SHT_RELM://找到描述重定位的section
  880. {
  881. unsigned long nrel, j;
  882. ElfW(RelM) *rel;
  883. struct obj_section *symtab;
  884. char *strtab;
  885. if (sec->header.sh_entsize != sizeof(ElfW(RelM)))
  886. {
  887. error("relocation entry size mismatch %s: %lu != %lu",
  888. filename,(unsigned long)sec->header.sh_entsize,
  889. (unsigned long)sizeof(ElfW(RelM)));
  890. return NULL;
  891. }
  892. //算出rel有几项,存到nrel中
  893. nrel = sec->header.sh_size / sizeof(ElfW(RelM));
  894. rel = (ElfW(RelM) *) sec->contents;
  895. //rel的section中sh_link相关值是符号section的索引值,即.symtab符号节区
  896. symtab = f->sections[sec->header.sh_link];
  897. //而符号section中sh_link是符号字符串section的索引值,即找到.strtab节区
  898. strtab = f->sections[symtab->header.sh_link]->contents;
  899. //存储需要relocate的符号的rel的类型
  900. for (j = 0; j < nrel; ++j, ++rel)
  901. {
  902. ElfW(Sym) *extsym;
  903. struct obj_symbol *intsym;
  904. unsigned long symndx;
  905. symndx = ELFW(R_SYM)(rel->r_info);//取得要进行重定位的符号表索引
  906. if(symndx)
  907. {
  908. //取得要进行重定位的符号(Elf32_sym结构)
  909. extsym = ((ElfW(Sym) *) symtab->contents) + symndx;
  910. //符号信息是局部的,别的文件不可见
  911. if (ELFW(ST_BIND)(extsym->st_info) == STB_LOCAL)
  912. {
  913. intsym = f->local_symtab[symndx];//要从局部符号表中获取
  914. }
  915. else//其他类型,从hash表中取
  916. {
  917. const char *name;
  918. if (extsym->st_name)//有值就是符号字符串表.strtab的索引值
  919. name = strtab + extsym->st_name;
  920. else//如果为零,此symbol name是一个section的name,比如.rodata之类的
  921. name = f->sections[extsym->st_shndx]->name;
  922. //因为前边已添加到hash表中,从hash表中获取该要重定位的符号
  923. intsym = obj_find_symbol(f, name);
  924. }
  925. intsym->r_type = ELFW(R_TYPE)(rel->r_info);//设置该符号的重定位类型,为以后进行符号重定位时使用
  926. }
  927. }
  928. }
  929. break;
  930. }
  931. }
  932. f->filename = xstrdup(filename);
  933. return f;
  934. }
  935. struct obj_symbol *obj_add_symbol (struct obj_file *f, const char *name, unsigned long symidx,int info, int secidx, ElfW(Addr) value, unsigned long size)
  936. {
  937. //参数:name符号名,symidx符号索引值(在此模块中),secidx节区索引值,value符号值
  938. struct obj_symbol *sym;
  939. unsigned long hash = f->symbol_hash(name) % HASH_BUCKETS;//计算出hash值
  940. int n_type = ELFW(ST_TYPE)(info);//要添加的符号类型
  941. int n_binding = ELFW(ST_BIND)(info);//要添加的符号绑定类型,例如:STB_LOCAL或STB_GLOBAL
  942. //遍历hash表中是否已添加了此符号,根据符号类型做不同处理
  943. for (sym = f->symtab[hash]; sym; sym = sym->next)
  944. if (f->symbol_cmp(sym->name, name) == 0)
  945. {
  946. int o_secidx = sym->secidx;
  947. int o_info = sym->info;
  948. int o_type = ELFW(ST_TYPE)(o_info);
  949. int o_binding = ELFW(ST_BIND)(o_info);
  950. if (secidx == SHN_UNDEF)//如果要加入的符号的属性是SHN_UNDEF,即未定义,不用处理
  951. return sym;
  952. else if (o_secidx == SHN_UNDEF)//如果已加入的符号属性是SHN_UNDEF,则用新的符号替换。
  953. goto found;
  954. else if (n_binding == STB_GLOBAL && o_binding == STB_LOCAL)//新添加的符号是global,而old符号是局部符号,那么就将STB_GLOBAL符号替换掉STB_LOCAL 符号。
  955. {
  956. struct obj_symbol *nsym, **p;
  957. nsym = arch_new_symbol();
  958. nsym->next = sym->next;
  959. nsym->ksymidx = -1;
  960. //从链表中删除旧的符号
  961. for (p = &f->symtab[hash]; *p != sym; p = &(*p)->next)
  962. continue;
  963. *p = sym = nsym;//新的符号替换旧的符号
  964. goto found;
  965. }
  966. else if (n_binding == STB_LOCAL)//新添加的符号是局部符号,则加入到local_symtab表中,不加入 symtab
  967. {
  968. sym = arch_new_symbol();
  969. sym->next = NULL;
  970. sym->ksymidx = -1;
  971. f->local_symtab[symidx] = sym;
  972. goto found;
  973. }
  974. else if (n_binding == STB_WEAK)//新加入的符号是weak属性,则不需处理
  975. return sym;
  976. else if (o_binding == STB_WEAK)//如果已加入的符号属性是STB_WEAK,则用新的符号替换。
  977. goto found;
  978. else if (secidx == SHN_COMMON&& (o_type == STT_NOTYPE || o_type == STT_OBJECT))
  979. return sym;
  980. else if (o_secidx == SHN_COMMON&& (n_type == STT_NOTYPE || n_type == STT_OBJECT))
  981. goto found;
  982. else
  983. {
  984. if (secidx <= SHN_HIRESERVE)
  985. error("%s multiply defined", name);
  986. return sym;
  987. }
  988. }
  989. //该符号没有在hash符号表中添加过,所以有可能一个局部符号添加到了hash表中
  990. sym = arch_new_symbol();//分配一个新的符号结构体
  991. sym->next = f->symtab[hash];//链入hash数组中f->symtab[hash]
  992. f->symtab[hash] = sym;
  993. sym->ksymidx = -1;
  994. //若是局部符号(别的文件不可见),则将该符号添加到f->local_symtab[]数组中
  995. if (ELFW(ST_BIND)(info) == STB_LOCAL && symidx != -1) {
  996. if (symidx >= f->local_symtab_size)
  997. error("local symbol %s with index %ld exceeds local_symtab_size %ld",
  998. name, (long) symidx, (long) f->local_symtab_size);
  999. else
  1000. f->local_symtab[symidx] = sym;
  1001. }
  1002. found:
  1003. sym->name = name;//符号名
  1004. sym->value = value;//符号值
  1005. sym->size = size;//符号大小
  1006. sym->secidx = secidx;//节区索引值
  1007. sym->info = info;//符号类型和绑定信息
  1008. sym->r_type = 0;//重定位类型初始为0
  1009. return sym;
  1010. }
  1011. void obj_set_symbol_compare (struct obj_file *f,int (*cmp)(const char *, const char *),
  1012. unsigned long (*hash)(const char *))
  1013. {
  1014. if (cmp)
  1015. f->symbol_cmp = cmp;//符号比较函数
  1016. if (hash)
  1017. {
  1018. struct obj_symbol *tmptab[HASH_BUCKETS], *sym, *next;
  1019. int i;
  1020. f->symbol_hash = hash;//hash函数
  1021. memcpy(tmptab, f->symtab, sizeof(tmptab));//先将符号信息保存在临时数组tmptab
  1022. memset(f->symtab, 0, sizeof(f->symtab));//清空hash表
  1023. //重新使用hash函数将符号添加到符号表f->symtab中
  1024. for (i = 0; i < HASH_BUCKETS; ++i)
  1025. for (sym = tmptab[i]; sym ; sym = next)
  1026. {
  1027. unsigned long h = hash(sym->name) % HASH_BUCKETS;
  1028. next = sym->next;
  1029. sym->next = f->symtab[h];
  1030. f->symtab[h] = sym;
  1031. }
  1032. }
  1033. }
  1034. static const char *gpl_licenses[] = {
  1035. "GPL",
  1036. "GPL v2",
  1037. "GPL and additional rights",
  1038. "Dual BSD/GPL",
  1039. "Dual MPL/GPL",
  1040. };
  1041. int obj_gpl_license(struct obj_file *f, const char **license)
  1042. {
  1043. struct obj_section *sec;
  1044. //找到.modinfo节区
  1045. if ((sec = obj_find_section(f, ".modinfo"))) {
  1046. const char *value, *ptr, *endptr;
  1047. ptr = sec->contents;//指向该节区内容其实地址
  1048. endptr = ptr + sec->header.sh_size;//节区内容结束地址
  1049. while (ptr < endptr) {
  1050. //找到以”license=“起始的字符串
  1051. if ((value = strchr(ptr, '=')) && strncmp(ptr, "license", value-ptr) == 0) {
  1052. int i;
  1053. if (license)
  1054. *license = value+1;
  1055. for (i = 0; i < sizeof(gpl_licenses)/sizeof(gpl_licenses[0]); ++i) {
  1056. if (strcmp(value+1, gpl_licenses[i]) == 0)//比较是否与以上数组相同的license
  1057. return(0);
  1058. }
  1059. return(2);
  1060. }
  1061. //否则从下一个字符串开始再查找
  1062. if (strchr(ptr, '\0'))
  1063. ptr = strchr(ptr, '\0') + 1;
  1064. else
  1065. ptr = endptr;
  1066. }
  1067. }
  1068. return(1);
  1069. }
  1070. static void add_kernel_symbols(struct obj_file *f)
  1071. {
  1072. struct module_stat *m;
  1073. size_t i, nused = 0;
  1074. //注意:此处虽然将模块的全局符号用内核和其他模块的符号替换过了,而且符号结构obj_symbol的secidx字段被重新写成了SHN_HIRESERVE以上的数值。对于一些全局的未定义符号(原来的secidx为SHN_UNDEF),现在这些未定义符号的secidx字段也被重新写成了SHN_HIRESERVE以上的数值。但是这些未定义符号对于elf文件格式的符号结构Elf32_sym中的字段st_shndx的取值并未改变,仍是SHN_UNDEF。这样做的原因是:在模块的编译过程中会生成一个__versions节区,该节区中存放的都是该模块中使用到,但没被定义的符号,也就是所谓的 unresolved symbol,它们或在基本内核中定义,或在其他模块中定义,内核使用它们来做 Module versioning。注意其中的 module_layout 符号,这是一个 dummy symbol。内核使用它来跟踪不同内核版本关于模块处理的相关数据结构的变化。所以该节区的未定义的符号虽然在这里被内核符号或其他模块符号已替换,但是它本身的SHN_UNDEF性质没有改变,用来对之后模块加载时的crc校验。因为crc校验时就是检查这些SHN_UNDEF性质的符号的crc值。参见内核函数simplify_symbols()。
  1075. //而且__versions节区的未定义的符号必须是内核或内核其他模块用到的符号,这样在此系统下编译的模块安装到另一个系统上时,根据这些全局符号的crc值就能知道此模块是不是在此系统上编译的。还有这些符号虽然被设置为未定义的,但是通过符号替换,仍能得到符号的绝对地址,从而被模块引用。
  1076. /* 使用系统中已有的module中的symbol,更新symbol的值,重新写入hash表或者局部符号表。注意:要加载的模块还没有加入到module_stat数组中 */
  1077. for (i = 0, m = module_stat; i < n_module_stat; ++i, ++m)
  1078. //遍历每个模块的符号表,符号对应的节区是SHN_LORESERVE以上的节区号。节区序号大于SHN_LORESERVE的符号,是没有对应的节区的。因此,符号里的值就认为是绝对地址。内核和已加载模块导出符号就处在这个区段。
  1079. if (m->nsyms && add_symbols_from(f, SHN_HIRESERVE + 2 + i, m->syms, m->nsyms))
  1080. {
  1081. m->status = 1;//表示此模块被引用了
  1082. ++nused;
  1083. }
  1084. n_ext_modules_used = nused;//该模块依赖的内核其余模块的个数
  1085. //使用kernel导出的symbol,更新symbol的值,重新写入hash表或者局部符号表.SHN_HIRESERVE对应系统保留节区的上限,使用SHN_HIRESERVE以上的节区来保存已加载模块的符号和内核符号。
  1086. if (nksyms)
  1087. add_symbols_from(f, SHN_HIRESERVE + 1, ksyms, nksyms);
  1088. }
  1089. static int add_symbols_from(struct obj_file *f, int idx,struct module_symbol *syms, size_t nsyms)
  1090. {
  1091. struct module_symbol *s;
  1092. size_t i;
  1093. int used = 0;
  1094. //遍历该模块的所有符号
  1095. for (i = 0, s = syms; i < nsyms; ++i, ++s) {
  1096. struct obj_symbol *sym;
  1097. //从hash表中是否有需要此名字的的symbol,局部符号表中的符号不需要内核符号替换
  1098. sym = obj_find_symbol(f, (char *) s->name);
  1099. //从要加载模块的hash表中找到该符号(必须为非局部符号),表示要加载模块需要改符号
  1100. if (sym && !ELFW(ST_BIND) (sym->info) == STB_LOCAL) {
  1101. /*将hash表中的待解析的symbol的value添成正确的值s->value*/
  1102. sym = obj_add_symbol(f, (char *) s->name, -1,ELFW(ST_INFO) (STB_GLOBAL, STT_NOTYPE),idx, s->value, 0);
  1103. if (sym->secidx == idx)
  1104. used = 1;//表示发生了符号替换
  1105. }
  1106. }
  1107. return used;
  1108. }
  1109. static int create_this_module(struct obj_file *f, const char *m_name)
  1110. {
  1111. struct obj_section *sec;
  1112. //创建一个.this节区,显然准备在这个节区里存放module结构。注意:这个节区是load时的首个节区,即起始节区
  1113. sec = obj_create_alloced_section_first(f, ".this", tgt_sizeof_long,sizeof(struct module));
  1114. memset(sec->contents, 0, sizeof(struct module));
  1115. //添加一个"__this_module"符号,所在节区是.this,属性是 STB_LOCAL,类型是 STT_OBJECT,symidx 为-1,所以这个符号不加入 local_symtab 中(因为这个符号不是文件原有的)
  1116. obj_add_symbol(f, "__this_module", -1, ELFW(ST_INFO) (STB_LOCAL, STT_OBJECT),sec->idx, 0, sizeof(struct module));
  1117. /*为了能在obj_file里引用模块名(回忆一下,每个字符串要么与节区名对应,要么对应于一个符号,而在这里,模块名没有对应的符号或节区),因此obj_file通过obj_string_patch_struct结构收留这些孤独的字符串*/
  1118. //创建.kstrtab节区,若存在该节区则扩展该节区,给该节区内容赋值为m_name,这里即”fedcore.ko“
  1119. obj_string_patch(f, sec->idx, offsetof(struct module, name), m_name);
  1120. return 1;
  1121. }
  1122. struct obj_section *obj_create_alloced_section_first (struct obj_file *f, const char *name,
  1123. unsigned long align, unsigned long size)
  1124. {
  1125. int newidx = f->header.e_shnum++;//elf文件头中的节区头数量加1
  1126. struct obj_section *sec;
  1127. //为节区头分配空间
  1128. f->sections = xrealloc(f->sections, (newidx+1) * sizeof(sec));
  1129. f->sections[newidx] = sec = arch_new_section();
  1130. memset(sec, 0, sizeof(*sec));//.this节区的偏移地址是0,sec->header.sh_addr=0
  1131. sec->header.sh_type = SHT_PROGBITS;
  1132. sec->header.sh_flags = SHF_WRITE|SHF_ALLOC;
  1133. sec->header.sh_size = size;
  1134. sec->header.sh_addralign = align;
  1135. sec->name = name;
  1136. sec->idx = newidx;
  1137. if (size)
  1138. sec->contents = xmalloc(size);//节区内容分配空间
  1139. sec->load_next = f->load_order;
  1140. f->load_order = sec;
  1141. if (f->load_order_search_start == &f->load_order)
  1142. f->load_order_search_start = &sec->load_next;
  1143. return sec;
  1144. }
  1145. int obj_string_patch(struct obj_file *f, int secidx, ElfW(Addr) offset,const char *string)
  1146. {
  1147. struct obj_string_patch_struct *p;
  1148. struct obj_section *strsec;
  1149. size_t len = strlen(string)+1;
  1150. char *loc;
  1151. p = xmalloc(sizeof(*p));
  1152. p->next = f->string_patches;
  1153. p->reloc_secidx = secidx;
  1154. p->reloc_offset = offset;
  1155. f->string_patches = p;//patch 字符串
  1156. //查找.kstrtab节区
  1157. strsec = obj_find_section(f, ".kstrtab");
  1158. if (strsec == NULL)
  1159. {
  1160. //该节区不存在则创建该节区
  1161. strsec = obj_create_alloced_section(f, ".kstrtab", 1, len, 0);
  1162. p->string_offset = 0;
  1163. loc = strsec->contents;
  1164. }
  1165. else
  1166. {
  1167. p->string_offset = strsec->header.sh_size;//字符串偏移地址
  1168. loc = obj_extend_section(strsec, len);//扩展该节区内容的地址大小
  1169. }
  1170. memcpy(loc, string, len);//赋值给节区内容
  1171. return 1;
  1172. }
  1173. int obj_check_undefineds(struct obj_file *f, int quiet)
  1174. {
  1175. unsigned long i;
  1176. int ret = 1;
  1177. //遍历模块的hash表的所有符号,检查是否还有未定义的符号
  1178. for (i = 0; i < HASH_BUCKETS; ++i)
  1179. {
  1180. struct obj_symbol *sym;
  1181. //一般来说此处不会有未定义的符号,因为前边经过了一次内核符号和其他模块符号的替换操作add_kernel_symbols,但是在模块的编译
  1182. for (sym = f->symtab[i]; sym ; sym = sym->next)
  1183. if (sym->secidx == SHN_UNDEF)//如果有未定义的符号
  1184. {
  1185. //对于属性为weak的符号,如果未能解析,链接器只是将它置0完事
  1186. if (ELFW(ST_BIND)(sym->info) == STB_WEAK)
  1187. {
  1188. sym->secidx = SHN_ABS;//符号具有绝对取值,不会因为重定位而发生变化。
  1189. sym->value = 0;
  1190. }
  1191. else if (sym->r_type) /* assumes R_arch_NONE is 0 on all arch */
  1192. {//如果不是weak属性,而且受重定位影响那就出错了
  1193. if (!quiet)
  1194. error("%s: unresolved symbol %s",f->filename, sym->name);
  1195. ret = 0;
  1196. }
  1197. }
  1198. }
  1199. return ret;
  1200. }
  1201. void obj_allocate_commons(struct obj_file *f)
  1202. {
  1203. struct common_entry
  1204. {
  1205. struct common_entry *next;
  1206. struct obj_symbol *sym;
  1207. } *common_head = NULL;
  1208. unsigned long i;
  1209. for (i = 0; i < HASH_BUCKETS; ++i)
  1210. {
  1211. struct obj_symbol *sym;
  1212. //遍历该模块的hash符号表
  1213. for (sym = f->symtab[i]; sym ; sym = sym->next)
  1214. //若设置了该标志SHN_COMMON,则表示符号标注了一个尚未分配的公共块,例如未分配的C外部变量。就是说,链接编辑器将为符号分配存储空间,地址位于 st_value 的倍数处。符号的大小给出了所需要的字节数。
  1215. //找出所有SHN_COMMON的符号,并按符号大小排序,链入到common_head链表中
  1216. if (sym->secidx == SHN_COMMON)
  1217. {
  1218. {
  1219. struct common_entry **p, *n;
  1220. for (p = &common_head; *p ; p = &(*p)->next)
  1221. if (sym->size <= (*p)->sym->size)
  1222. break;
  1223. n = alloca(sizeof(*n));
  1224. n->next = *p;
  1225. n->sym = sym;
  1226. *p = n;
  1227. }
  1228. }
  1229. }
  1230. //遍历该模块的局部符号表local_symtab,找出所有SHN_COMMON的符号,并按符号大小排序,链入到common_head链表中
  1231. for (i = 1; i < f->local_symtab_size; ++i)
  1232. {
  1233. struct obj_symbol *sym = f->local_symtab[i];
  1234. if (sym && sym->secidx == SHN_COMMON)
  1235. {
  1236. struct common_entry **p, *n;
  1237. for (p = &common_head; *p ; p = &(*p)->next)
  1238. if (sym == (*p)->sym)
  1239. break;
  1240. else if (sym->size < (*p)->sym->size)
  1241. {
  1242. n = alloca(sizeof(*n));
  1243. n->next = *p;
  1244. n->sym = sym;
  1245. *p = n;
  1246. break;
  1247. }
  1248. }
  1249. }
  1250. if (common_head)
  1251. {
  1252. for (i = 0; i < f->header.e_shnum; ++i)
  1253. //SHT_NOBITS表明这个节区不占据文件空间,这正是.bss节区的类型,这里就是为了查找.bss节区
  1254. if (f->sections[i]->header.sh_type == SHT_NOBITS)
  1255. break;
  1256. //如果没有找到.bss节区,则就创建一个.bss节区
  1257. //.bss 含义:包含将出现在程序的内存映像中的为初始化数据。根据定义,当程序开始执行,系统将把这些数据初始化为 0。此节区不占用文件空间。
  1258. if (i == f->header.e_shnum)
  1259. {
  1260. struct obj_section *sec;
  1261. f->sections = xrealloc(f->sections, (i+1) * sizeof(sec));
  1262. f->sections[i] = sec = arch_new_section();//分配节区结构obj_section
  1263. f->header.e_shnum = i+1;//节区数量加1
  1264. memset(sec, 0, sizeof(*sec));
  1265. sec->header.sh_type = SHT_PROGBITS;//节区类型
  1266. sec->header.sh_flags = SHF_WRITE|SHF_ALLOC;
  1267. sec->name = ".bss";//节区名称
  1268. sec->idx = i;//节区索引值
  1269. }
  1270. {
  1271. ElfW(Addr) bss_size = f->sections[i]->header.sh_size;//节区大小
  1272. ElfW(Addr) max_align = f->sections[i]->header.sh_addralign;//对齐边界
  1273. struct common_entry *c;
  1274. //根据SHN_COMMON的符号重新计算该.bss节区大小和对齐边界
  1275. for (c = common_head; c ; c = c->next)
  1276. {
  1277. ElfW(Addr) align = c->sym->value;
  1278. if (align > max_align)
  1279. max_align = align;
  1280. if (bss_size & (align - 1))
  1281. bss_size = (bss_size | (align - 1)) + 1;
  1282. c->sym->secidx = i;//该符号的节区索引值也改变了,即是.bss节区
  1283. c->sym->value = bss_size;//符号值也变了,变成.bss节区符号偏移量
  1284. bss_size += c->sym->size;
  1285. }
  1286. f->sections[i]->header.sh_size = bss_size;
  1287. f->sections[i]->header.sh_addralign = max_align;
  1288. }
  1289. }
  1290. //为SHT_NOBITS节区分配资源,并将它设为SHT_PROGBITS。从这里可以看到,文件定义的静态、全局变量,还有引用的外部变量,最终放在了.bss节区中
  1291. for (i = 0; i < f->header.e_shnum; ++i)
  1292. {
  1293. struct obj_section *s = f->sections[i];
  1294. if (s->header.sh_type == SHT_NOBITS)//找到.bss节区
  1295. {
  1296. if (s->header.sh_size)
  1297. //节区内容都初始化为0,即.bss节区中符号对应的文件定义的静态、全局变量,还有引用的外部变量都初始化为0
  1298. s->contents = memset(xmalloc(s->header.sh_size),0, s->header.sh_size);
  1299. else
  1300. s->contents = NULL;
  1301. s->header.sh_type = SHT_PROGBITS;
  1302. }
  1303. }
  1304. }
  1305. static void check_module_parameters(struct obj_file *f, int *persist_flag)
  1306. {
  1307. struct obj_section *sec;
  1308. char *ptr, *value, *n, *endptr;
  1309. int namelen, err = 0;
  1310. //查找 ".modinfo"节区
  1311. sec = obj_find_section(f, ".modinfo");
  1312. if (sec == NULL) {
  1313. return;
  1314. }
  1315. ptr = sec->contents;//节区内容起始地址
  1316. endptr = ptr + sec->header.sh_size;//节区内容结束地址
  1317. while (ptr < endptr && !err) {
  1318. value = strchr(ptr, '=');//定位到该字符串的”=“位置出
  1319. n = strchr(ptr, '\0');
  1320. if (value) {
  1321. namelen = value - ptr;//找到该字符串的名称
  1322. //查找相对应的"parm_"或"parm_desc_"开头的字符串
  1323. if (namelen >= 5 && strncmp(ptr, "parm_", 5) == 0
  1324. && !(namelen > 10 && strncmp(ptr, "parm_desc_", 10) == 0)) {
  1325. char *pname = xmalloc(namelen + 1);
  1326. strncpy(pname, ptr + 5, namelen - 5);//取得该字符串名
  1327. pname[namelen - 5] = '\0';
  1328. //检查该参数字符串的内容
  1329. err = check_module_parameter(f, pname, value+1, persist_flag);
  1330. free(pname);
  1331. }
  1332. } else {
  1333. if (n - ptr >= 5 && strncmp(ptr, "parm_", 5) == 0) {
  1334. error("parameter %s found with no value", ptr);
  1335. err = 1;
  1336. }
  1337. }
  1338. ptr = n + 1;//下一个字符串
  1339. }
  1340. if (err)
  1341. *persist_flag = 0;
  1342. return;
  1343. }
  1344. static int check_module_parameter(struct obj_file *f, char *key, char *value, int *persist_flag)
  1345. {
  1346. struct obj_symbol *sym;
  1347. int min, max;
  1348. char *p = value;
  1349. //确定该符号是否存在
  1350. sym = obj_find_symbol(f, key);
  1351. if (sym == NULL) {
  1352. lprintf("Warning: %s symbol for parameter %s not found", error_file, key);
  1353. ++warnings;
  1354. return(1);
  1355. }
  1356. //解析参数值个数的声明,如果没有参数值个数的取值声明就默认为1
  1357. if (isdigit(*p)) {
  1358. min = strtoul(p, &p, 10);
  1359. if (*p == '-')
  1360. max = strtoul(p + 1, &p, 10);
  1361. else
  1362. max = min;
  1363. } else
  1364. min = max = 1;
  1365. if (max < min) {
  1366. lprintf("Warning: %s parameter %s has max < min!", error_file, key);
  1367. ++warnings;
  1368. return(1);
  1369. }
  1370. //处理变量类型
  1371. switch (*p) {
  1372. case 'c':
  1373. if (!isdigit(p[1])) {
  1374. lprintf("%s parameter %s has no size after 'c'!", error_file, key);
  1375. ++warnings;
  1376. return(1);
  1377. }
  1378. while (isdigit(p[1]))
  1379. ++p;    /* swallow c array size */
  1380. break;
  1381. case 'b':    /* drop through */
  1382. case 'h':    /* drop through */
  1383. case 'i':    /* drop through */
  1384. case 'l':    /* drop through */
  1385. case 's':
  1386. break;
  1387. case '\0':
  1388. lprintf("%s parameter %s has no format character!", error_file, key);
  1389. ++warnings;
  1390. return(1);
  1391. default:
  1392. lprintf("%s parameter %s has unknown format character '%c'", error_file, key, *p);
  1393. ++warnings;
  1394. return(1);
  1395. }
  1396. switch (*++p) {
  1397. case 'p':
  1398. if (*(p-1) == 's') {
  1399. error("parameter %s is invalid persistent string", key);
  1400. return(1);
  1401. }
  1402. *persist_flag = 1;
  1403. break;
  1404. case '\0':
  1405. break;
  1406. default:
  1407. lprintf("%s parameter %s has unknown format modifier '%c'", error_file, key, *p);
  1408. ++warnings;
  1409. return(1);
  1410. }
  1411. return(0);
  1412. }
  1413. static int process_module_arguments(struct obj_file *f, int argc, char **argv, int required)
  1414. {
  1415. //遍历命令行参数
  1416. for (; argc > 0; ++argv, --argc) {
  1417. struct obj_symbol *sym;
  1418. int c;
  1419. int min, max;
  1420. int n;
  1421. char *contents;
  1422. char *input;
  1423. char *fmt;
  1424. char *key;
  1425. char *loc;
  1426. //因为使用命令行参数时,一定是param=value这样的形式
  1427. if ((input = strchr(*argv, '=')) == NULL)
  1428. continue;
  1429. n = input - *argv;//参数长度
  1430. input += 1; /* skip '=' */
  1431. key = alloca(n + 6);
  1432. if (m_has_modinfo) {
  1433. //将该参数组合成参数符号格式”parm_xxx“
  1434. memcpy(key, "parm_", 5);
  1435. memcpy(key + 5, *argv, n);
  1436. key[n + 5] = '\0';
  1437. //从节区.modinfo中查找该模块参数
  1438. if ((fmt = get_modinfo_value(f, key)) == NULL) {
  1439. if (required || flag_verbose) {
  1440. lprintf("Warning: ignoring %s, no such parameter in this module", *argv);
  1441. ++warnings;
  1442. continue;
  1443. }
  1444. }
  1445. key += 5;
  1446. //解析参数值个数的声明,如果没有参数值个数的取值声明就默认为1
  1447. if (isdigit(*fmt)) {
  1448. min = strtoul(fmt, &fmt, 10);
  1449. if (*fmt == '-')
  1450. max = strtoul(fmt + 1, &fmt, 10);
  1451. else
  1452. max = min;
  1453. } else
  1454. min = max = 1;
  1455. } else { /* not m_has_modinfo */
  1456. memcpy(key, *argv, n);
  1457. key[n] = '\0';
  1458. if (isdigit(*input))
  1459. fmt = "i";
  1460. else
  1461. fmt = "s";
  1462. min = max = 0;
  1463. }
  1464. //到hash符号表中查找该参数符号
  1465. sym = obj_find_symbol(f, key);
  1466. if (sym == NULL || sym->secidx > SHN_HIRESERVE) {
  1467. error("symbol for parameter %s not found", key);
  1468. return 0;
  1469. }
  1470. //找到符号,读取该符号所在节区的内容
  1471. contents = f->sections[sym->secidx]->contents;
  1472. loc = contents + sym->value;//存储该参数符号的值地址付给loc指针,下边就会给参数符号重新赋值
  1473. n = 1;
  1474. while (*input) {
  1475. char *str;
  1476. switch (*fmt) {
  1477. case 's':
  1478. case 'c':
  1479. if (*input == '"') {
  1480. char *r;
  1481. str = alloca(strlen(input));
  1482. for (r = str, input++; *input != '"'; ++input, ++r) {
  1483. if (*input == '\0') {
  1484. error("improperly terminated string argument for %s", key);
  1485. return 0;
  1486. }
  1487. /* else */
  1488. if (*input != '\\') {
  1489. *r = *input;
  1490. continue;
  1491. }
  1492. /* else handle \ */
  1493. switch (*++input) {
  1494. case 'a': *r = '\a'; break;
  1495. case 'b': *r = '\b'; break;
  1496. case 'e': *r = '\033'; break;
  1497. case 'f': *r = '\f'; break;
  1498. case 'n': *r = '\n'; break;
  1499. case 'r': *r = '\r'; break;
  1500. case 't': *r = '\t'; break;
  1501. case '0':
  1502. case '1':
  1503. case '2':
  1504. case '3':
  1505. case '4':
  1506. case '5':
  1507. case '6':
  1508. case '7':
  1509. c = *input - '0';
  1510. if ('0' <= input[1] && input[1] <= '7') {
  1511. c = (c * 8) + *++input - '0';
  1512. if ('0' <= input[1] && input[1] <= '7')
  1513. c = (c * 8) + *++input - '0';
  1514. }
  1515. *r = c;
  1516. break;
  1517. default: *r = *input; break;
  1518. }
  1519. }
  1520. *r = '\0';
  1521. ++input;
  1522. } else {
  1523. /*
  1524. * The string is not quoted.
  1525. * We will break it using the comma
  1526. * (like for ints).
  1527. * If the user wants to include commas
  1528. * in a string, he just has to quote it
  1529. */
  1530. char *r;
  1531. /* Search the next comma */
  1532. if ((r = strchr(input, ',')) != NULL) {
  1533. /*
  1534. * Found a comma
  1535. * Recopy the current field
  1536. */
  1537. str = alloca(r - input + 1);
  1538. memcpy(str, input, r - input);
  1539. str[r - input] = '\0';
  1540. /* Keep next fields */
  1541. input = r;
  1542. } else {
  1543. /* last string */
  1544. str = input;
  1545. input = "";
  1546. }
  1547. }
  1548. if (*fmt == 's') {
  1549. /* Normal string */
  1550. obj_string_patch(f, sym->secidx, loc - contents, str);
  1551. loc += tgt_sizeof_char_p;
  1552. } else {
  1553. /* Array of chars (in fact, matrix !) */
  1554. long charssize;    /* size of each member */
  1555. /* Get the size of each member */
  1556. /* Probably we should do that outside the loop ? */
  1557. if (!isdigit(*(fmt + 1))) {
  1558. error("parameter type 'c' for %s must be followed by the maximum size", key);
  1559. return 0;
  1560. }
  1561. charssize = strtoul(fmt + 1, (char **) NULL, 10);
  1562. /* Check length */
  1563. if (strlen(str) >= charssize-1) {
  1564. error("string too long for %s (max %ld)",key, charssize - 1);
  1565. return 0;
  1566. }
  1567. /* Copy to location */
  1568. strcpy((char *) loc, str);    /* safe, see check above */
  1569. loc += charssize;
  1570. }
  1571. /*
  1572. * End of 's' and 'c'
  1573. */
  1574. break;
  1575. case 'b':
  1576. *loc++ = strtoul(input, &input, 0);
  1577. break;
  1578. case 'h':
  1579. *(short *) loc = strtoul(input, &input, 0);
  1580. loc += tgt_sizeof_short;
  1581. break;
  1582. case 'i':
  1583. *(int *) loc = strtoul(input, &input, 0);
  1584. loc += tgt_sizeof_int;
  1585. break;
  1586. case 'l':
  1587. *(tgt_long *) loc = tgt_strtoul(input, &input, 0);
  1588. loc += tgt_sizeof_long;
  1589. break;
  1590. default:
  1591. error("unknown parameter type '%c' for %s",*fmt, key);
  1592. return 0;
  1593. }
  1594. /*
  1595. * end of switch (*fmt)
  1596. */
  1597. while (*input && isspace(*input))
  1598. ++input;
  1599. if (*input == '\0')
  1600. break; /* while (*input) */
  1601. /* else */
  1602. if (*input == ',') {
  1603. if (max && (++n > max)) {
  1604. error("too many values for %s (max %d)", key, max);
  1605. return 0;
  1606. }
  1607. ++input;
  1608. /* continue with while (*input) */
  1609. } else {
  1610. error("invalid argument syntax for %s: '%c'",key, *input);
  1611. return 0;
  1612. }
  1613. } /* end of while (*input) */
  1614. if (min && (n < min)) {
  1615. error("too few values for %s (min %d)", key, min);
  1616. return 0;
  1617. }
  1618. } /* end of for (;argc > 0;) */
  1619. return 1;
  1620. }
  1621. static void hide_special_symbols(struct obj_file *f)
  1622. {
  1623. struct obj_symbol *sym;
  1624. const char *const *p;
  1625. static const char *const specials[] =
  1626. {
  1627. "cleanup_module",
  1628. "init_module",
  1629. "kernel_version",
  1630. NULL
  1631. };
  1632. //查找数组中的几个符号,找到后类型改为STB_LOCAL(局部)
  1633. for (p = specials; *p; ++p)
  1634. if ((sym = obj_find_symbol(f, *p)) != NULL)
  1635. sym->info = ELFW(ST_INFO) (STB_LOCAL, ELFW(ST_TYPE) (sym->info));
  1636. }
  1637. static void add_ksymoops_symbols(struct obj_file *f, const char *filename,const char *m_name)
  1638. {
  1639. struct obj_section *sec;
  1640. struct obj_symbol *sym;
  1641. char *name, *absolute_filename;
  1642. char str[STRVERSIONLEN], real[PATH_MAX];
  1643. int i, l, lm_name, lfilename, use_ksymtab, version;
  1644. struct stat statbuf;
  1645. static const char *section_names[] = {
  1646. ".text",
  1647. ".rodata",
  1648. ".data",
  1649. ".bss"
  1650. ".sbss"
  1651. };
  1652. //找到模块所在的完整路径名
  1653. if (realpath(filename, real)) {
  1654. absolute_filename = xstrdup(real);
  1655. }
  1656. else {
  1657. int save_errno = errno;
  1658. error("cannot get realpath for %s", filename);
  1659. errno = save_errno;
  1660. perror("");
  1661. absolute_filename = xstrdup(filename);
  1662. }
  1663. lm_name = strlen(m_name);
  1664. lfilename = strlen(absolute_filename);
  1665. //查找"__ksymtab"节区是否存在或者模块符号是否需要导出
  1666. use_ksymtab = obj_find_section(f, "__ksymtab") || !flag_export;
  1667. //找到.this节区,记录经过修饰的模块名和经过修饰的长度不为0的节区。在这里修饰的目的,应该是为了唯一确定所使用的模块。
  1668. if ((sec = obj_find_section(f, ".this"))) {
  1669. l = sizeof(symprefix)+            /* "__insmod_" */
  1670. lm_name+                /* module name */
  1671. 2+                    /* "_O" */
  1672. lfilename+                /* object filename */
  1673. 2+                    /* "_M" */
  1674. 2*sizeof(statbuf.st_mtime)+        /* mtime in hex */
  1675. 2+                    /* "_V" */
  1676. 8+                    /* version in dec */
  1677. 1;                    /* nul */
  1678. name = xmalloc(l);
  1679. if (stat(absolute_filename, &statbuf) != 0)
  1680. statbuf.st_mtime = 0;
  1681. version = get_module_version(f, str);    /* -1 if not found */
  1682. snprintf(name, l, "%s%s_O%s_M%0*lX_V%d",symprefix, m_name, absolute_filename,
  1683. (int)(2*sizeof(statbuf.st_mtime)), statbuf.st_mtime,version);
  1684. //添加一个符号,该符号所在节区是.this节区,符号value给出该符号的地址在节区sec->header.sh_addr(值为0)的偏移地址处
  1685. sym = obj_add_symbol(f, name, -1,ELFW(ST_INFO) (STB_GLOBAL, STT_NOTYPE),sec->idx, sec->header.sh_addr, 0);
  1686. if (use_ksymtab)
  1687. add_ksymtab(f, sym);//该符号添加到__ksymtab节区中
  1688. }
  1689. free(absolute_filename);
  1690. //参数若是通过文件传入的,也要修饰记录这个文件名
  1691. if (f->persist) {
  1692. l = sizeof(symprefix)+        /* "__insmod_" */
  1693. lm_name+        /* module name */
  1694. 2+            /* "_P" */
  1695. strlen(f->persist)+    /* data store */
  1696. 1;            /* nul */
  1697. name = xmalloc(l);
  1698. snprintf(name, l, "%s%s_P%s",symprefix, m_name, f->persist);
  1699. sym = obj_add_symbol(f, name, -1, ELFW(ST_INFO) (STB_GLOBAL, STT_NOTYPE),sec->idx, sec->header.sh_addr, 0);
  1700. if (use_ksymtab)
  1701. add_ksymtab(f, sym);//该符号添加到__ksymtab节区中,要导出的符号加入该节区"__ksymtab"
  1702. }
  1703. /* tag the desired sections if size is non-zero */
  1704. for (i = 0; i < sizeof(section_names)/sizeof(section_names[0]); ++i) {
  1705. if ((sec = obj_find_section(f, section_names[i])) &&sec->header.sh_size) {
  1706. l = sizeof(symprefix)+        /* "__insmod_" */
  1707. lm_name+        /* module name */
  1708. 2+            /* "_S" */
  1709. strlen(sec->name)+    /* section name */
  1710. 2+            /* "_L" */
  1711. 8+            /* length in dec */
  1712. 1;            /* nul */
  1713. name = xmalloc(l);
  1714. snprintf(name, l, "%s%s_S%s_L%ld",symprefix, m_name, sec->name,(long)sec->header.sh_size);
  1715. sym = obj_add_symbol(f, name, -1, ELFW(ST_INFO) (STB_GLOBAL, STT_NOTYPE),sec->idx, sec->header.sh_addr, 0);
  1716. if (use_ksymtab)
  1717. add_ksymtab(f, sym);//该符号添加到__ksymtab节区中,要导出的符号加入该节区"__ksymtab"
  1718. }
  1719. }
  1720. }
  1721. static int create_module_ksymtab(struct obj_file *f)
  1722. {
  1723. struct obj_section *sec;
  1724. int i;
  1725. //n_ext_modules_used是该模块引用的模块的数量
  1726. if (n_ext_modules_used) {
  1727. struct module_ref *dep;
  1728. struct obj_symbol *tm;
  1729. //创建一个.kmodtab节区保存该模块所引用的模块信息
  1730. sec = obj_create_alloced_section(f, ".kmodtab",tgt_sizeof_void_p,sizeof(struct module_ref) * n_ext_modules_used, 0);
  1731. if (!sec)
  1732. return 0;
  1733. tm = obj_find_symbol(f, "__this_module");
  1734. dep = (struct module_ref *) sec->contents;
  1735. //
  1736. for (i = 0; i < n_module_stat; ++i)
  1737. if (module_stat[i].status) {//模块若被引用,则status为1
  1738. dep->dep = module_stat[i].addr;
  1739. dep->dep |= arch_module_base (f);
  1740. obj_symbol_patch(f, sec->idx, (char *) &dep->ref - sec->contents, tm);
  1741. dep->next_ref = 0;
  1742. ++dep;
  1743. }
  1744. }
  1745. // 在存在__ksymtab节区或者不存在这个节区,而且其他符号都不导出的情况下,还要将这些符号添加入__symtab节区
  1746. //如果需要导出外部(extern)符号,而__ksymtab段不存在(这种情况下,add_ksymoops_symbols里是不会创建__ksymtab段的。而实际上,模块一般是不会不包含__ksymtab段的,因为模块的导出符号都位于这个段里。),那么通过add_ksymtab创建__ksymtab段,并加入模块要导出的符号。在这里可以发现,如果模块需要导出符号,那么经过修饰的模块名、模块文件名,甚至参数文件名会在这里加入__ksymtab段(因为在前面的add_ksymoops_symbols函数里,这些符号被设为STB_GLOBOL了,段序号指向.this段)。
  1747. //注意,在不存在__ksymtab段的情况下(这时模块没有定义任何需要导出的参数),直接导出序号在SHN_LORESERVE~SHN_HIRESERVE的符号,以及其他已分配资源段的非local符号。(根据elf规范里,位于SHN_LORESERVE~SHN_HIRESERVE区的已定义序号有SHN_LOPROC、SHN_HIPROC、SHN_ABS、SHN_COMMON。经过前面的处理,到这里SHN_COMMON对应的符号已经不存在了。这些序号的节区实际上是不存在的,存在的是持有这些序号的符号。其中SHN_ABS是不受重定位影响的符号,其他2个则是与处理器有关的。至于为什么模块不需要导出符号时,要导出这些区的符号,我也不太清楚,可以肯定的是,这和GCC有关,谁知道它放了什么进来?!)。
  1748. if (flag_export && !obj_find_section(f, "__ksymtab")) {
  1749. int *loaded;
  1750. loaded = alloca(sizeof(int) * (i = f->header.e_shnum));
  1751. while (--i >= 0)
  1752. loaded[i] = (f->sections[i]->header.sh_flags & SHF_ALLOC) != 0;//节区是否占用内存
  1753. for (i = 0; i < HASH_BUCKETS; ++i) {
  1754. struct obj_symbol *sym;
  1755. for (sym = f->symtab[i]; sym; sym = sym->next)
  1756. {
  1757. if (ELFW(ST_BIND) (sym->info) != STB_LOCAL && sym->secidx <= SHN_HIRESERVE&& (sym->secidx >= SHN_LORESERVE || loaded[sym->secidx])) {
  1758. add_ksymtab(f, sym);//要导出的符号加入该节区"__ksymtab"
  1759. }
  1760. }
  1761. }
  1762. }
  1763. return 1;
  1764. }
  1765. static void add_ksymtab(struct obj_file *f, struct obj_symbol *sym)
  1766. {
  1767. struct obj_section *sec;
  1768. ElfW(Addr) ofs;
  1769. //查找是否已经存在"__ksymtab"节区
  1770. sec = obj_find_section(f, "__ksymtab");
  1771. //如果存在这个节区,但是没有标示SHF_ALLOC,则直接将该节区的名字修改掉,标示删除
  1772. if (sec && !(sec->header.sh_flags & SHF_ALLOC)) {
  1773. *((char *)(sec->name)) = 'x';    /* override const */
  1774. sec = NULL;
  1775. }
  1776. if (!sec)
  1777. sec = obj_create_alloced_section(f, "__ksymtab",tgt_sizeof_void_p, 0, 0);
  1778. if (!sec)
  1779. return;
  1780. sec->header.sh_flags |= SHF_ALLOC;
  1781. sec->header.sh_addralign = tgt_sizeof_void_p;    /* Empty section mightbe byte-aligned */
  1782. ofs = sec->header.sh_size;
  1783. obj_symbol_patch(f, sec->idx, ofs, sym);//使用f->sybol_ptches保存这些符号
  1784. obj_string_patch(f, sec->idx, ofs + tgt_sizeof_void_p, sym->name);//使用f->string_patches保存符号名
  1785. obj_extend_section(sec, 2 * tgt_sizeof_char_p);//扩展"__ksymtab"节区
  1786. }
  1787. static int add_archdata(struct obj_file *f,struct obj_section **sec)
  1788. {
  1789. size_t i;
  1790. *sec = NULL;
  1791. //查找是否有ARCHDATA_SEC_NAME=“__archdata”节区,没有则创建该节区
  1792. for (i = 0; i < f->header.e_shnum; ++i) {
  1793. if (strcmp(f->sections[i]->name, ARCHDATA_SEC_NAME) == 0) {
  1794. *sec = f->sections[i];
  1795. break;
  1796. }
  1797. }
  1798. if (!*sec)
  1799. *sec = obj_create_alloced_section(f, ARCHDATA_SEC_NAME, 16, 0, 0);
  1800. //x86体系下是空函数
  1801. if (arch_archdata(f, *sec))
  1802. return(1);
  1803. return 0;
  1804. }
  1805. static int add_kallsyms(struct obj_file *f,struct obj_section **module_kallsyms, int force_kallsyms)
  1806. {
  1807. struct module_symbol *s;
  1808. struct obj_file *f_kallsyms;
  1809. struct obj_section *sec_kallsyms;
  1810. size_t i;
  1811. int l;
  1812. const char *p, *pt_R;
  1813. unsigned long start = 0, stop = 0;
  1814. //遍历所有内核符号,内核符号都保存在全局变量ksyms中
  1815. for (i = 0, s = ksyms; i < nksyms; ++i, ++s) {
  1816. p = (char *)s->name;
  1817. pt_R = strstr(p, "_R");//查找符号中是否有 "_R",计算符号长度是,去掉这两个字符
  1818. if (pt_R)
  1819. l = pt_R - p;
  1820. else
  1821. l = strlen(p);
  1822. //内核导出符号位于“__start_kallsyms”和“__stop_kallsyms”符号所指向的地址之间
  1823. if (strncmp(p, "__start_" KALLSYMS_SEC_NAME, l) == 0)
  1824. start = s->value;
  1825. else if (strncmp(p, "__stop_" KALLSYMS_SEC_NAME, l) == 0)
  1826. stop = s->value;
  1827. }
  1828. if (start >= stop && !force_kallsyms)
  1829. return(0);
  1830. /* The kernel contains all symbols, do the same for this module. */
  1831. //找到该模块的“kallsyms”节区
  1832. for (i = 0; i < f->header.e_shnum; ++i) {
  1833. if (strcmp(f->sections[i]->name, KALLSYMS_SEC_NAME) == 0) {
  1834. *module_kallsyms = f->sections[i];
  1835. break;
  1836. }
  1837. }
  1838. //如果没有找到,则创建一个kallsyms节区
  1839. if (!*module_kallsyms)
  1840. *module_kallsyms = obj_create_alloced_section(f, KALLSYMS_SEC_NAME, 0, 0, 0);
  1841. //这个函数的作用是将输入obj_file里的符号提取出来,忽略不用于调试的符号.构建出obj_file只包含kallsyms节区。这个段可以任意定位,因为不包含重定位信息。
  1842. //实际上,f_kallsyms这个文件就是将输入文件里的信息整理整理,更方便使用(记住__kallsyms节区是用作辅助内核调试),整个输出文件只是临时的调试仓库。
  1843. if (obj_kallsyms(f, &f_kallsyms))//???
  1844. return(1);
  1845. sec_kallsyms = f_kallsyms->sections[KALLSYMS_IDX];//临时创建obj_file里的kallsyms节区
  1846. (*module_kallsyms)->header.sh_addralign = sec_kallsyms->header.sh_addralign;//节区对齐大小
  1847. (*module_kallsyms)->header.sh_size = sec_kallsyms->header.sh_size;//节区大小
  1848. free((*module_kallsyms)->contents);
  1849. (*module_kallsyms)->contents = sec_kallsyms->contents;//内容赋值给kallsyms节区
  1850. sec_kallsyms->contents = NULL;
  1851. obj_free(f_kallsyms);
  1852. return 0;
  1853. }
  1854. unsigned long obj_load_size (struct obj_file *f)
  1855. {
  1856. unsigned long dot = 0;
  1857. struct obj_section *sec;
  1858. //前面提到段按对其边界大小排序,可以减少空间占用,就是体现在这里。
  1859. for (sec = f->load_order; sec ; sec = sec->load_next)
  1860. {
  1861. ElfW(Addr) align;
  1862. align = sec->header.sh_addralign;
  1863. if (align && (dot & (align - 1)))
  1864. dot = (dot | (align - 1)) + 1;
  1865. sec->header.sh_addr = dot;
  1866. dot += sec->header.sh_size;//各个节区大小累加
  1867. }
  1868. return dot;
  1869. }
  1870. asmlinkage unsigned long sys_create_module(const char *name_user, size_t size)
  1871. {
  1872. char *name;
  1873. long namelen, error;
  1874. struct module *mod;
  1875. if (!capable(CAP_SYS_MODULE))//是否具有创建模块的特权
  1876. return EPERM;
  1877. lock_kernel();
  1878. if ((namelen = get_mod_name(name_user, &name)) < 0) {//模块名拷贝到内核空间
  1879. error = namelen;
  1880. goto err0;
  1881. }
  1882. if (size < sizeof(struct module)+namelen) {//检查模块名的大小
  1883. error = EINVAL;
  1884. goto err1;
  1885. }
  1886. if (find_module(name) != NULL) {//在内存中查找是否模块已经安装
  1887. error = EEXIST;
  1888. goto err1;
  1889. }
  1890. //分配module空间 #define module_map(x) vmalloc(x)
  1891. if ((mod = (struct module *)module_map(size)) == NULL) {
  1892. error = ENOMEM;
  1893. goto err1;
  1894. }
  1895. memset(mod, 0, sizeof(*mod));
  1896. mod->size_of_struct = sizeof(*mod);
  1897. mod->next = module_list;//挂入链表
  1898. mod->name = (char *)(mod + 1);//module结构下边用来存储模块名
  1899. mod->size = size;
  1900. memcpy((char*)(mod+1), name, namelen+1);//拷贝模块名
  1901. put_mod_name(name);//释放name的空间
  1902. module_list = mod;//挂入链表
  1903. error = (long) mod;
  1904. goto err0;
  1905. err1:
  1906. put_mod_name(name);
  1907. err0:
  1908. unlock_kernel();
  1909. return error;
  1910. }
  1911. //base是模块在内核空间的起始地址,也是.this节区的偏移地址
  1912. int obj_relocate (struct obj_file *f, ElfW(Addr) base)
  1913. {
  1914. int i, n = f->header.e_shnum;
  1915. int ret = 1;
  1916. //节区在内存的位置是假设文件从0地址加载而得出的,现在就要根据base值调整
  1917. arch_finalize_section_address(f, base);
  1918. //处理重定位符号,遍历每一个节区
  1919. for (i = 0; i < n; ++i)
  1920. {
  1921. struct obj_section *relsec, *symsec, *targsec, *strsec;
  1922. ElfW(RelM) *rel, *relend;
  1923. ElfW(Sym) *symtab;
  1924. const char *strtab;
  1925. unsigned long nsyms;
  1926. relsec = f->sections[i];
  1927. if (relsec->header.sh_type != SHT_RELM)//如果该节区不是重定位类型,则继续查找
  1928. continue;
  1929. //重定位节区会引用两个其它节区:符号表、要修改的节区。符号表是symsec,要修改的节区是targsec节区.例如重定位节区(relsec).rel.text是对节区是.text(targsec)的进行重定位.原来重定位的目标节区(.text)的内容contents只是读入到内存中,这块内存是系统在堆上malloc的,内容中对应的地址不是真正的符号所在的地址。现在符号的真正的地址已经计算出,就要修改contents区的符号对应的地址,从而将符号链接到正确的地址。
  1930. //重定位节区的sh_link表示相关符号表的节区头部索引,即.symtab符号节区
  1931. symsec = f->sections[relsec->header.sh_link];
  1932. //重定位节区的sh_info表示重定位所适用的节区的节区头部索引,像.text等节区
  1933. targsec = f->sections[relsec->header.sh_info];
  1934. //找到重定位节区相关符号表字符串的节区,即.strtab
  1935. strsec = f->sections[symsec->header.sh_link];
  1936. if (!(targsec->header.sh_flags & SHF_ALLOC))
  1937. continue;
  1938. //读出该节区重定位信息开始地址
  1939. rel = (ElfW(RelM) *)relsec->contents;
  1940. //重定位信息结束地址
  1941. relend = rel + (relsec->header.sh_size / sizeof(ElfW(RelM)));
  1942. //找到重定位节区相关符号表的内容
  1943. symtab = (ElfW(Sym) *)symsec->contents;
  1944. nsyms = symsec->header.sh_size / symsec->header.sh_entsize;
  1945. strtab = (const char *)strsec->contents;//找到重定位节区相关符号表字符串的节区的内容
  1946. for (; rel < relend; ++rel)
  1947. {
  1948. ElfW(Addr) value = 0;
  1949. struct obj_symbol *intsym = NULL;
  1950. unsigned long symndx;
  1951. const char *errmsg;
  1952. //给出要重定位的符号表索引
  1953. symndx = ELFW(R_SYM)(rel->r_info);
  1954. if (symndx)
  1955. {
  1956. /* Note we've already checked for undefined symbols. */
  1957. if (symndx >= nsyms)
  1958. {
  1959. error("%s: Bad symbol index: %08lx >= %08lx",f->filename, symndx, nsyms);
  1960. continue;
  1961. }
  1962. //这些要重定位的符号就是重定位目标节区(例如.text节区)里的符号,然后把该符号的绝对地址在覆盖这个节区的(例如.text节区)对应符号的地址
  1963. obj_find_relsym(intsym, f, f, rel, symtab, strtab);//返回要找的重定位符号intsym
  1964. value = obj_symbol_final_value(f, intsym);//计算符号的绝对地址(是内核空间的绝对地址,因为base就是内核空间的一个地址)
  1965. }
  1966. #if SHT_RELM == SHT_RELA
  1967. value += rel->r_addend;
  1968. #endif
  1969. //获得了绝对地址,可以进行操作了
  1970. //注意:这里虽然重新定义了符号的绝对地址,但是节区的内容还没有拷贝到分配模块返回的内核空间地址处。后边会进行这项操作。先将节区内容拷贝的用户空间中,再从用户空间拷贝到内核空间地址处,即base处。
  1971. //f:objfile结构,targsec:.text节,symsec:.symtab节,rel:.rel结构,value:绝对地址
  1972. switch (arch_apply_relocation(f,targsec,symsec,intsym,rel,value))
  1973. {
  1974. case obj_reloc_ok:
  1975. break;
  1976. case obj_reloc_overflow:
  1977. errmsg = "Relocation overflow";
  1978. goto bad_reloc;
  1979. case obj_reloc_dangerous:
  1980. errmsg = "Dangerous relocation";
  1981. goto bad_reloc;
  1982. case obj_reloc_unhandled:
  1983. errmsg = "Unhandled relocation";
  1984. goto bad_reloc;
  1985. case obj_reloc_constant_gp:
  1986. errmsg = "Modules compiled with -mconstant-gp cannot be loaded";
  1987. goto bad_reloc;
  1988. bad_reloc:
  1989. error("%s: %s of type %ld for %s", f->filename, errmsg,
  1990. (long)ELFW(R_TYPE)(rel->r_info), intsym->name);
  1991. ret = 0;
  1992. break;
  1993. }
  1994. }
  1995. }
  1996. /* Finally, take care of the patches. */
  1997. if (f->string_patches)
  1998. {
  1999. struct obj_string_patch_struct *p;
  2000. struct obj_section *strsec;
  2001. ElfW(Addr) strsec_base;
  2002. strsec = obj_find_section(f, ".kstrtab");
  2003. strsec_base = strsec->header.sh_addr;
  2004. for (p = f->string_patches; p ; p = p->next)
  2005. {
  2006. struct obj_section *targsec = f->sections[p->reloc_secidx];
  2007. *(ElfW(Addr) *)(targsec->contents + p->reloc_offset)= strsec_base + p->string_offset;
  2008. }
  2009. }
  2010. if (f->symbol_patches)
  2011. {
  2012. struct obj_symbol_patch_struct *p;
  2013. for (p = f->symbol_patches; p; p = p->next)
  2014. {
  2015. struct obj_section *targsec = f->sections[p->reloc_secidx];
  2016. *(ElfW(Addr) *)(targsec->contents + p->reloc_offset)= obj_symbol_final_value(f, p->sym);
  2017. }
  2018. }
  2019. return ret;
  2020. }
  2021. int arch_finalize_section_address(struct obj_file *f, Elf32_Addr base)
  2022. {
  2023. int i, n = f->header.e_shnum;
  2024. //每个节区的起始地址都要加上模块在内核的起始地址
  2025. f->baseaddr = base;//模块在内核的起始地址
  2026. for (i = 0; i < n; ++i)
  2027. f->sections[i]->header.sh_addr += base;
  2028. return 1;
  2029. }
  2030. #define obj_find_relsym(isym, f, find, rel, symtab, strtab) \
  2031. { \
  2032. unsigned long symndx = ELFW(R_SYM)((rel)->r_info); \
  2033. ElfW(Sym) *extsym = (symtab)+symndx; \//在符号表节区的内容中根据索引值找到相关符号
  2034. if (ELFW(ST_BIND)(extsym->st_info) == STB_LOCAL) { \//若是局部符号
  2035. isym = (typeof(isym)) (f)->local_symtab[symndx]; \//直接在局部符号表中返回要找的重定位符号
  2036. } \
  2037. else { \
  2038. const char *name; \
  2039. if (extsym->st_name) \//有值的话,就是strtab字符串节区内容的索引值
  2040. name = (strtab) + extsym->st_name; \//找到符号名
  2041. else \//否则就是节区名
  2042. name = (f)->sections[extsym->st_shndx]->name; \
  2043. isym = (typeof(isym)) obj_find_symbol((find), name); \//在符号hash表中找到该重定位符号
  2044. } \
  2045. }
  2046. ElfW(Addr) obj_symbol_final_value (struct obj_file *f, struct obj_symbol *sym)
  2047. {
  2048. if (sym)
  2049. {
  2050. //在保留区内直接返回符号值,即符号绝对地址(一般是内核符号,因为前边将模块内的符号用内核中或已存在的模块中相同符号的value更写过了,并且节区索引值设置高于SHN_HIRESERVE,所以这些符号的value保存的就是符号的实际地址)
  2051. if (sym->secidx >= SHN_LORESERVE)
  2052. return sym->value;
  2053. //其余节区内的符号value要加上现在节区的偏移地址,才是符号指向的实际地址(因为节区的偏移地址已经更改了)
  2054. return sym->value + f->sections[sym->secidx]->header.sh_addr;//符号值加上节区头偏移地址
  2055. }
  2056. else
  2057. {
  2058. /* As a special case, a NULL sym has value zero. */
  2059. return 0;
  2060. }
  2061. }
  2062. //x86架构
  2063. /*
  2064. 。“重定位表”记录的是每个需要重定位的地方(即有了重定位表,就可知道哪个段、偏移多少的地方的地址或值是需要修改的)、重定位的类型、符号的名字(即重定位的地方属于哪个符号)。(静态)链接器在链接目标文件的时候,会扫描每个目标文件,为每个目标文件中的段分配运行时的地址(这个地址就是进程地址空间的地址,因为每个操作系统都会位应用程序指定装载地址、如eos和windows的0x00400000,linux的0x0804800,通过用操作系统指定的地址配置链接器,链接器根据每个段的属性、大小和对齐属性等,就可得到每个段运行时的地址了),这样每个段的地址就确定下来了,从而,每个符号的地址都确定了,然后把符号表中符号的值修改为正确的地址。然后连接器就会把所有目标文件的符号表合并为一个全局的符号表(主要是为了定位的方便)。接下来,连接器就读取每个目标文件,通过重定位表找到需要重定位的地方和这个符号的名字,然后用这个符号去检索全局符号表,得到符号的地址,再用个这个地址填入需要修正的地方(对于相对跳转指令是用这个地址和修正处的地址和修正处存放的值参运算计算出正确的跳转偏移,然后填入),最后把所有经过了重定位的目标文件中相同段名和属性的段合并,输出到最终的可执行文件中并建立相应的数据结构,可执行文件也是有格式的,linux 常见的elf,windows和eos的pe格式。
  2065. */
  2066. //重定位结构(Elf32_Rel)中的字段r_info指定重定位地址属于哪个符号,r_offset字段指定重定位的地方。然后把这个符号的绝对地址写到重定位的地方
  2067. enum obj_reloc arch_apply_relocation (struct obj_file *f,
  2068. struct obj_section *targsec,
  2069. struct obj_section *symsec,
  2070. struct obj_symbol *sym,
  2071. Elf32_Rel *rel,
  2072. Elf32_Addr v)
  2073. {
  2074. struct i386_file *ifile = (struct i386_file *)f;
  2075. struct i386_symbol *isym = (struct i386_symbol *)sym;
  2076. 找到重定位的地方,下边在这个地方写入符号的绝对地址
  2077. Elf32_Addr *loc = (Elf32_Addr *)(targsec->contents + rel->r_offset);
  2078. Elf32_Addr dot = targsec->header.sh_addr + rel->r_offset;
  2079. Elf32_Addr got = ifile->got ? ifile->got->header.sh_addr : 0;
  2080. enum obj_reloc ret = obj_reloc_ok;
  2081. switch (ELF32_R_TYPE(rel->r_info))//重定位类型
  2082. {
  2083. case R_386_NONE:
  2084. break;
  2085. case R_386_32:
  2086. *loc += v;
  2087. break;
  2088. case R_386_PLT32:
  2089. case R_386_PC32:
  2090. *loc += v - dot;
  2091. break;
  2092. case R_386_GLOB_DAT:
  2093. case R_386_JMP_SLOT:
  2094. *loc = v;
  2095. break;
  2096. case R_386_RELATIVE:
  2097. *loc += f->baseaddr;
  2098. break;
  2099. case R_386_GOTPC:
  2100. assert(got != 0);
  2101. *loc += got - dot;
  2102. break;
  2103. case R_386_GOT32:
  2104. assert(isym != NULL);
  2105. if (!isym->gotent.reloc_done)
  2106. {
  2107. isym->gotent.reloc_done = 1;
  2108. *(Elf32_Addr *)(ifile->got->contents + isym->gotent.offset) = v;
  2109. }
  2110. *loc += isym->gotent.offset;
  2111. break;
  2112. case R_386_GOTOFF:
  2113. assert(got != 0);
  2114. *loc += v - got;
  2115. break;
  2116. default:
  2117. ret = obj_reloc_unhandled;
  2118. break;
  2119. }
  2120. return ret;
  2121. }
  2122. //insmod包含在modutils包里。我们感兴趣的东西是insmod.c文件里的init_module()函数。
  2123. static int init_module(const char *m_name, struct obj_file *f,unsigned long m_size, const char *blob_name,unsigned int noload, unsigned int flag_load_map)
  2124. {
  2125. //传入的参数m_name是模块名称,obj_file *f已经将模块的节区信息添加到该结构中,m_size是模块大小
  2126. struct module *module;
  2127. struct obj_section *sec;
  2128. void *image;
  2129. int ret = 0;
  2130. tgt_long m_addr;
  2131. //从节区数组中查找.this节区
  2132. sec = obj_find_section(f, ".this");
  2133. module = (struct module *) sec->contents;//取得本节区的内容,是一个module结构
  2134. //下边的操作就是初始化module结构,都保存在.this节区的contents中。
  2135. //.this节区的偏移地址地址就是module结构的在内核空间的起始地址,因为.this节区是首节区,前边该节区的偏移地址根据内核空间的模块起始地址做了一个偏移即sec->header.sh_addr+m_addr,又因为.this节区的sh_addr初始值是0,所以加了这个偏移,就正好指向模块在内核空间的起始地址。
  2136. m_addr = sec->header.sh_addr;
  2137. module->size_of_struct = sizeof(*module);//模块结构大小
  2138. module->size = m_size;//模块大小
  2139. module->flags = flag_autoclean ? NEW_MOD_AUTOCLEAN : 0;
  2140. //查找__ksymtab节表,保存的是该模块导出的符号
  2141. sec = obj_find_section(f, "__ksymtab");
  2142. if (sec && sec->header.sh_size) {
  2143. module->syms = sec->header.sh_addr;
  2144. module->nsyms = sec->header.sh_size / (2 * tgt_sizeof_char_p);
  2145. }
  2146. //查找.kmodtab节表,module的依赖对象对应于.kmodtab节区
  2147. if (n_ext_modules_used) {
  2148. sec = obj_find_section(f, ".kmodtab");
  2149. module->deps = sec->header.sh_addr;
  2150. module->ndeps = n_ext_modules_used;
  2151. }
  2152. //obj_find_symbol()函数遍历符号列表查找名字为init_module的符号,然后提取这个结构体符号(struct symbol)并把它传递给 obj_symbol_final_value()。后者从这个结构体符号提取出init_module函数的地址。
  2153. module->init = obj_symbol_final_value(f, obj_find_symbol(f, "init_module"));
  2154. module->cleanup = obj_symbol_final_value(f,obj_find_symbol(f, "cleanup_module"));
  2155. //查找__ex_table节表
  2156. sec = obj_find_section(f, "__ex_table");
  2157. if (sec) {
  2158. module->ex_table_start = sec->header.sh_addr;
  2159. module->ex_table_end = sec->header.sh_addr + sec->header.sh_size;
  2160. }
  2161. //查找.text.init节表
  2162. sec = obj_find_section(f, ".text.init");
  2163. if (sec) {
  2164. module->runsize = sec->header.sh_addr - m_addr;
  2165. }
  2166. //查找.data.init节表
  2167. sec = obj_find_section(f, ".data.init");
  2168. if (sec) {
  2169. if (!module->runsize || module->runsize > sec->header.sh_addr - m_addr)
  2170. module->runsize = sec->header.sh_addr - m_addr;
  2171. }
  2172. sec = obj_find_section(f, ARCHDATA_SEC_NAME);
  2173. if (sec && sec->header.sh_size) {
  2174. module->archdata_start = sec->header.sh_addr;
  2175. module->archdata_end = module->archdata_start + sec->header.sh_size;
  2176. }
  2177. //查找kallsyms节区
  2178. sec = obj_find_section(f, KALLSYMS_SEC_NAME);
  2179. if (sec && sec->header.sh_size) {
  2180. module->kallsyms_start = sec->header.sh_addr;//符号开始地址
  2181. module->kallsyms_end = module->kallsyms_start + sec->header.sh_size;//符号结束地址
  2182. }
  2183. if (!arch_init_module(f, module))//x86下什么也不干
  2184. return 0;
  2185. //在用户空间分配module的image的内存,返回模块起始地址
  2186. image = xmalloc(m_size);
  2187. //各个section的内容拷入image中,包括原文件中的section和后来构造的section
  2188. obj_create_image(f, image);//模块内容从f结构指定的地址中拷贝到image中,构建模块映像
  2189. if (flag_load_map)
  2190. print_load_map(f);
  2191. if (blob_name) {//是否指定了要输出模块到指定的文件blob_name
  2192. int fd, l;
  2193. fd = open(blob_name, O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
  2194. if (fd < 0) {
  2195. error("open %s failed %m", blob_name);
  2196. ret = -1;
  2197. }
  2198. else {
  2199. if ((l = write(fd, image, m_size)) != m_size) {
  2200. error("write %s failed %m", blob_name);
  2201. ret = -1;
  2202. }
  2203. close(fd);
  2204. }
  2205. }
  2206. if (ret == 0 && !noload) {
  2207. fflush(stdout);        /* Flush any debugging output */
  2208. //sys_init_module() 这个系统调用通知内核加载相应模块,这个函数的代码可以在 /usr/src/linux/kernel/module.c
  2209. //在此函数中把在用户空间的module映像复制到前边由create_module创建地内核空间中。
  2210. ret = sys_init_module(m_name, (struct module *) image);
  2211. if (ret) {
  2212. error("init_module: %m");
  2213. lprintf("Hint: insmod errors can be caused by incorrect module parameters, "
  2214. "including invalid IO or IRQ parameters.You may find more information in syslog or the output from dmesg
  1. }
  2. }
  3. free(image);
  4. return ret == 0;
  5. }
  6. int obj_create_image (struct obj_file *f, char *image)
  7. {
  8. struct obj_section *sec;
  9. ElfW(Addr) base = f->baseaddr;
  10. //注意:首个load的节区是.this节区
  11. for (sec = f->load_order; sec ; sec = sec->load_next)
  12. {
  13. char *secimg;
  14. if (sec->contents == 0)
  15. continue;
  16. secimg = image + (sec->header.sh_addr - base);
  17. //所有的节区内容拷贝到以image地址开始的地方,当然第一个节区的内容恰好是struct module结构
  18. memcpy(secimg, sec->contents, sec->header.sh_size);
  19. }
  20. return 1;
    1. int sys_init_module(const char *name, const struct module *info)
    2. {
    3. //调用系统调用init_module(),系统调用init_module()在内核中的实现是sys_init_module(),这是由内核提供的,全内核只有这一个函数。注意,这是linux V2.6以前的调用。
    4. return init_module(name, info);
    5. }
    6. asmlinkage long sys_init_module(const char *name_user, struct module *mod_user)
    7. {
    8. struct module mod_tmp, *mod;
    9. char *name, *n_name, *name_tmp = NULL;
    10. long namelen, n_namelen, i, error;
    11. unsigned long mod_user_size;
    12. struct module_ref *dep;
    13. //检查模块加载的权限
    14. if (!capable(CAP_SYS_MODULE))
    15. return EPERM;
    16. lock_kernel();
    17. //复制模块名到内核空间name中
    18. if ((namelen = get_mod_name(name_user, &name)) < 0) {
    19. error = namelen;
    20. goto err0;
    21. }
    22. //从module_list中找到之前通过creat_module()在内核空间创建的module结构,创建模块时已经将模块结构链入module_list
    23. if ((mod = find_module(name)) == NULL) {
    24. error = ENOENT;
    25. goto err1;
    26. }
    27. //把用户空间的module结构的size_of_struct复制到内核中加以检查,将模块结构的大小size_of_struct赋值给mod_user_size,即sizeof(struct module)
    28. if ((error = get_user(mod_user_size, &mod_user->size_of_struct)) != 0)
    29. goto err1;
    30. //对用户空间和内核空间的module结构的大小进行检查
    31. //如果申请的模块头部长度小于旧版的模块头长度或者大于将来可能的模块头长度
    32. if (mod_user_size < (unsigned long)&((struct module *)0L)->persist_start
    33. || mod_user_size > sizeof(struct module) + 16*sizeof(void*)) {
    34. printk(KERN_ERR "init_module: Invalid module header size.\n"
    35. KERN_ERR "A new version of the modutils is likely ""needed.\n");
    36. error = EINVAL;
    37. goto err1;
    38. }
    39. mod_tmp = *mod;//内核中的module结构先保存到堆栈中
    40. //分配保存内核空间模块名的空间
    41. name_tmp = kmalloc(strlen(mod->name) + 1, GFP_KERNEL); /* Where's kstrdup()? */
    42. if (name_tmp == NULL) {
    43. error = ENOMEM;
    44. goto err1;
    45. }
    46. strcpy(name_tmp, mod->name);//将内核中module的name复制给name_tmp,在堆栈中先保存起来
    47. //将用户空间的模块结构到内核空间原来的module地址处(即将用户空间的模块映像覆盖掉在内核空间模块映像的所在地址,这样前边设置的符号地址就不需要改变了,正好就是我们在前边按照内核空间的模块起始地址设置的),mod_user_size是模块结构的大小,即sizeof(struct module)
    48. error = copy_from_user(mod, mod_user, mod_user_size);
    49. if (error) {
    50. error = EFAULT;
    51. goto err2;
    52. }
    53. error = EINVAL;
    54. //比较内核空间和用户空间模块大小,若在insmod用户空间创建的module结构大小大于内核空间的module大小,就出错退出
    55. if (mod->size > mod_tmp.size) {
    56. printk(KERN_ERR "init_module: Size of initialized module ""exceeds size of created module.\n");
    57. goto err2;
    58. }
    59. if (!mod_bound(mod->name, namelen, mod)) {//用来检查用户指针所指的对象是否落在模块的边界内
    60. printk(KERN_ERR "init_module: mod->name out of bounds.\n");
    61. goto err2;
    62. }
    63. if (mod->nsyms && !mod_bound(mod->syms, mod->nsyms, mod)) {// 符号表的区域是否在模块体中
    64. printk(KERN_ERR "init_module: mod->syms out of bounds.\n");
    65. goto err2;
    66. }
    67. if (mod->ndeps && !mod_bound(mod->deps, mod->ndeps, mod)) {//依赖关系表是否在模块体中
    68. printk(KERN_ERR "init_module: mod->deps out of bounds.\n");
    69. goto err2;
    70. }
    71. if (mod->init && !mod_bound(mod->init, 0, mod)) {//init函数是否是模块体中
    72. printk(KERN_ERR "init_module: mod->init out of bounds.\n");
    73. goto err2;
    74. }
    75. if (mod->cleanup && !mod_bound(mod->cleanup, 0, mod)) {//cleanup函数是否是模块体中
    76. printk(KERN_ERR "init_module: mod->cleanup out of bounds.\n");
    77. goto err2;
    78. }
    79. //检查模块的异常描述表是否在模块影像内
    80. if (mod->ex_table_start > mod->ex_table_end|| (mod->ex_table_start
    81. &&!((unsigned long)mod->ex_table_start >= ((unsigned long)mod + mod->size_of_struct)
    82. && ((unsigned long)mod->ex_table_end< (unsigned long)mod + mod->size)))||
    83. (((unsigned long)mod->ex_table_start-(unsigned long)mod->ex_table_end)% sizeof(struct exception_table_entry))) {
    84. printk(KERN_ERR "init_module: mod->ex_table_* invalid.\n");
    85. goto err2;
    86. }
    87. if (mod->flags & ~MOD_AUTOCLEAN) {
    88. printk(KERN_ERR "init_module: mod->flags invalid.\n");
    89. goto err2;
    90. }
    91. if (mod_member_present(mod, can_unload)//检查结构的大小,看用户模块是否包含can_unload字段
    92. && mod->can_unload && !mod_bound(mod->can_unload, 0, mod)) {//若包含can_unload字段,就检查其边界
    93. printk(KERN_ERR "init_module: mod->can_unload out of bounds.\n");
    94. goto err2;
    95. }
    96. if (mod_member_present(mod, kallsyms_end)) {
    97. if (mod->kallsyms_end &&(!mod_bound(mod->kallsyms_start, 0, mod) ||!mod_bound(mod->kallsyms_end, 0, mod))) {
    98. printk(KERN_ERR "init_module: mod->kallsyms out of bounds.\n");
    99. goto err2;
    100. }
    101. if (mod->kallsyms_start > mod->kallsyms_end) {
    102. printk(KERN_ERR "init_module: mod->kallsyms invalid.\n");
    103. goto err2;
    104. }
    105. }
    106. if (mod_member_present(mod, archdata_end)) {
    107. if (mod->archdata_end &&(!mod_bound(mod->archdata_start, 0, mod) ||
    108. !mod_bound(mod->archdata_end, 0, mod))) {
    109. printk(KERN_ERR "init_module: mod->archdata out of bounds.\n");
    110. goto err2;
    111. }
    112. if (mod->archdata_start > mod->archdata_end) {
    113. printk(KERN_ERR "init_module: mod->archdata invalid.\n");
    114. goto err2;
    115. }
    116. }
    117. if (mod_member_present(mod, kernel_data) && mod->kernel_data) {
    118. printk(KERN_ERR "init_module: mod->kernel_data must be zero.\n");
    119. goto err2;
    120. }
    121. //在把用户空间的模块名从用户空间拷贝进来
    122. if ((n_namelen = get_mod_name(mod->name-(unsigned long)mod+ (unsigned long)mod_user,&n_name)) < 0) {
    123. printk(KERN_ERR "init_module: get_mod_name failure.\n");
    124. error = n_namelen;
    125. goto err2;
    126. }
    127. //比较内核空间中和用户空间中模块名是否相同
    128. if (namelen != n_namelen || strcmp(n_name, mod_tmp.name) != 0) {
    129. printk(KERN_ERR "init_module: changed module name to ""`%s' from `%s'\n",n_name, mod_tmp.name);
    130. goto err3;
    131. }
    132. //拷贝除module结构本身以外的其它section到内核空间中,就是拷贝模块映像
    133. if (copy_from_user((char *)mod+mod_user_size,(char *)mod_user+mod_user_size,mod->size-mod_user_size)) {
    134. error = EFAULT;
    135. goto err3;
    136. }
    137. if (module_arch_init(mod))//空操作
    138. goto err3;
    139. flush_icache_range((unsigned long)mod, (unsigned long)mod + mod->size);
    140. mod->next = mod_tmp.next;//mod->next在拷贝模块头时被覆盖了
    141. mod->refs = NULL;//由于是新加载的,还没有别的模块引用我
    142. //检查模块的依赖关系,依赖的模块仍在内核中
    143. for (i = 0, dep = mod->deps; i < mod->ndeps; ++i, ++dep) {
    144. struct module *o, *d = dep->dep;
    145. if (d == mod) {//依赖的模块不能使自身
    146. printk(KERN_ERR "init_module: selfreferential""dependency in mod->deps.\n");
    147. goto err3;
    148. }
    149. //若依赖的模块已经不在module_list中,则系统调用失败
    150. for (o = module_list; o != &kernel_module && o != d; o = o->next);
    151. if (o != d) {
    152. printk(KERN_ERR "init_module: found dependency that is ""(no longer?) a module.\n");
    153. goto err3;
    154. }
    155. }
    156. //再扫描,将每个module_ref结构链入到所依赖模块的refs队列中,并将结构中的ref指针指向正在安装的nodule结构。这样每个module_ref结构既存在于所属模块的deps[]数组中,又出现于该模块所依赖的某个模块的refs队列中。
    157. for (i = 0, dep = mod->deps; i < mod->ndeps; ++i, ++dep) {
    158. struct module *d = dep->dep;
    159. dep->ref = mod;
    160. dep->next_ref = d->refs;
    161. d->refs = dep;
    162. d->flags |= MOD_USED_ONCE;
    163. }
    164. put_mod_name(n_name);//释放空间
    165. put_mod_name(name);//释放空间
    166. mod->flags |= MOD_INITIALIZING;//设置模块初始化标志
    167. atomic_set(&mod->uc.usecount,1);//用户计数设为1
    168. //检查模块的init_module()函数,然后执行模块的init_module()函数,注意此函数与内核中的
    169. //init_module()函数是不一样的,内核中的调用sys_init_module()
    170. if (mod->init && (error = mod->init()) != 0) {
    171. atomic_set(&mod->uc.usecount,0);//模块的计数加1
    172. mod->flags &= ~MOD_INITIALIZING;//初始化标志清零
    173. if (error > 0) /* Buggy module */
    174. error = EBUSY;
    175. goto err0;
    176. }
    177. atomic_dec(&mod->uc.usecount);//递减计数
    178. //初始化标志清零,标志设置为MOD_RUNNING
    179. mod->flags = (mod->flags | MOD_RUNNING) & ~MOD_INITIALIZING;
    180. error = 0;
    181. goto err0;
    182. err3:
    183. put_mod_name(n_name);
    184. err2:
    185. *mod = mod_tmp;
    186. strcpy((char *)mod->name, name_tmp); /* We know there is room for this */
    187. err1:
    188. put_mod_name(name);
    189. err0:
    190. unlock_kernel();
    191. kfree(name_tmp);
    192. return error;
    193. }

模块加载过程代码分析1相关推荐

  1. FreeSwitch 的初始化及其模块加载过程

    FS 主函数main() Freeswitch的主函数是在文件switch.c中定义的,该文件的260行是整个程序的入口,主函数主要完成的功能是包括,命令行解析,初始化apr库,构建全局内存池,模块加 ...

  2. 【Node】模块加载过程

    1.JS/JSON/Node模块 Module.runMain或Module.require (1)路径解析 (1)内置JS模块:直接返回 (2)构造查找路径 (1)模块名/绝对路径:parentPa ...

  3. FreeSwitch Sofia模块加载过程

         模块加载入口函数mod_sofia_load(),首先一系列switch_event_reserve_subclass()调用,注册事件类型.然后调用switch_queue_create( ...

  4. linux ipv6模块,有关Linux ipv6模块加载失败的问题

    有关Linux ipv6模块加载失败的问题 同事一个SUSE11sp3环境配置ipv6地址失败,提示不支持IPv6,请求帮助,第一反应是应该ipv6相关内核模块没有加载. 主要检查内容: ipv6地址 ...

  5. 高通平台dtb文件的加载过程

    高通平台dtb文件的加载过程 高通平台对dts的两种打包方式 zImage-dtb dt.img zImage-dtb方式 zImage-dtb的编译 二进制文件查看 lk的加载过程代码分析 dt.i ...

  6. 浏览器页面资源加载过程与优化

    评价页面性能好坏的核心之一就是页面的加载速度,而页面加载速度的关键就是页面资源的加载.本文将从浏览器浏览器页面资源加载过程展开分析,来引出页面关键请求路径的概念,并给出如何优化该关键请求路径的一些方法 ...

  7. nodejs学习巩固笔记-nodejs基础,Node.js 高级编程(核心模块、模块加载机制)

    目录 Nodejs 基础 大前端开发过程中的必备技能 nodejs 的架构 为什么是 Nodejs Nodejs 异步 IO Nodejs 事件驱动架构 全局对象 全局变量之 process 核心模块 ...

  8. 重温.NET下Assembly的加载过程 ASP.NET Core Web API下事件驱动型架构的实现(三):基于RabbitMQ的事件总线...

    重温.NET下Assembly的加载过程 最近在工作中牵涉到了.NET下的一个古老的问题:Assembly的加载过程.虽然网上有很多文章介绍这部分内容,很多文章也是很久以前就已经出现了,但阅读之后发现 ...

  9. 重温.NET下Assembly的加载过程

    最近在工作中牵涉到了.NET下的一个古老的问题:Assembly的加载过程.虽然网上有很多文章介绍这部分内容,很多文章也是很久以前就已经出现了,但阅读之后发现,并没能解决我的问题,有些点写的不是特别详 ...

最新文章

  1. UVA-10714 Ants---蚂蚁模拟
  2. 4月22日(牛马不对嘴)
  3. 转载:opencv错误rect错误
  4. 2 创建联合索引_想进大厂,这些Mysql索引底层知识你是必须知道的
  5. POS开发问题 - 多个弹出框的实现
  6. ECSHOP批量添加商品到购物车
  7. Flask基础(03)--创建第一个Flask程序
  8. Ubuntu 默认 root 密码修改
  9. JQuery input file 上传图片
  10. python 获取路径
  11. 【办公自动化】基于Arcpy建立GIS三调转换工具箱,23万图斑shp文件分分钟转换完成
  12. dede mysql x_mysql 插入数据时中文变x87xE7xA7x91xE7x82这种?
  13. Rockstar Games遭黑客攻击,《侠盗猎车手6》90个开发视频外泄
  14. php 文章页面阅读全文,给WordPress文章内容页增加阅读全文展开功能
  15. 抖音获取douyin分享口令url API 返回值说明
  16. 3dmax:3dmax的软件右边栏常用修改器(Cloth修改器、车削、倒角/剖面、对称、FFD长方体/圆柱体、Gizmo、规格化样条线、挤出 、路径、扭曲、晶格、壳、拉伸)之详细攻略
  17. Multimedia Standards Introduction——专业术语
  18. 知识点滴 - 喝啤酒吗
  19. python淘宝爬虫登陆功能和下单功能_Python 爬虫实战5 模拟登录淘宝并获取所有订单...
  20. 【bzoj3698】XWW的难题 有上下界最大流

热门文章

  1. Electron 调用系统工具记事本、计算器等
  2. 关于一些朋友想做在线教育的回复和分享
  3. PermGen space错误解决方法
  4. KVM 介绍(4):I/O 设备直接分配和 SR-IOV [KVM PCI/PCIe Pass-Through SR-IOV]
  5. Android draw9patch点九图常识
  6. Enterprise Library 5.0发布
  7. springboot2处理跨域
  8. 洛谷 P2359 三素数数
  9. Bmob图片上传遇到的坑
  10. Des和Base64的Util