insmod模塊加載過程代碼分析1【轉】


轉自:http://blog.chinaunix.net/uid-27717694-id-3966290.html

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

---恢復內容結束---

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM