module.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include <linux/moduleloader.h>
  2. #include <linux/elf.h>
  3. #include <linux/vmalloc.h>
  4. #include <linux/fs.h>
  5. #include <linux/string.h>
  6. #include <linux/kernel.h>
  7. int apply_relocate_add(Elf32_Shdr *sechdrs,
  8. const char *strtab,
  9. unsigned int symindex,
  10. unsigned int relsec,
  11. struct module *me)
  12. {
  13. unsigned int i;
  14. Elf32_Rela *rela = (void *)sechdrs[relsec].sh_addr;
  15. pr_debug("Applying relocate section %u to %u\n", relsec,
  16. sechdrs[relsec].sh_info);
  17. for (i = 0; i < sechdrs[relsec].sh_size / sizeof(*rela); i++) {
  18. /* This is where to make the change */
  19. uint32_t *loc =
  20. (uint32_t *)(sechdrs[sechdrs[relsec].sh_info].sh_addr
  21. + rela[i].r_offset);
  22. /* This is the symbol it is referring to. Note that all
  23. undefined symbols have been resolved. */
  24. Elf32_Sym *sym = (Elf32_Sym *)sechdrs[symindex].sh_addr
  25. + ELF32_R_SYM(rela[i].r_info);
  26. uint32_t v = sym->st_value + rela[i].r_addend;
  27. switch (ELF32_R_TYPE(rela[i].r_info)) {
  28. case R_H8_DIR24R8:
  29. loc = (uint32_t *)((uint32_t)loc - 1);
  30. *loc = (*loc & 0xff000000) | ((*loc & 0xffffff) + v);
  31. break;
  32. case R_H8_DIR24A8:
  33. if (ELF32_R_SYM(rela[i].r_info))
  34. *loc += v;
  35. break;
  36. case R_H8_DIR32:
  37. case R_H8_DIR32A16:
  38. *loc += v;
  39. break;
  40. case R_H8_PCREL16:
  41. v -= (unsigned long)loc + 2;
  42. if ((Elf32_Sword)v > 0x7fff ||
  43. (Elf32_Sword)v < -(Elf32_Sword)0x8000)
  44. goto overflow;
  45. else
  46. *(unsigned short *)loc = v;
  47. break;
  48. case R_H8_PCREL8:
  49. v -= (unsigned long)loc + 1;
  50. if ((Elf32_Sword)v > 0x7f ||
  51. (Elf32_Sword)v < -(Elf32_Sword)0x80)
  52. goto overflow;
  53. else
  54. *(unsigned char *)loc = v;
  55. break;
  56. default:
  57. pr_err("module %s: Unknown relocation: %u\n",
  58. me->name, ELF32_R_TYPE(rela[i].r_info));
  59. return -ENOEXEC;
  60. }
  61. }
  62. return 0;
  63. overflow:
  64. pr_err("module %s: relocation offset overflow: %08x\n",
  65. me->name, rela[i].r_offset);
  66. return -ENOEXEC;
  67. }