6 #include <syslinux/loadfile.h>
11 #define COM32_IDT ((void*)0x100000)
12 #define COM32_LOAD_ADDR ((void*)0x101000)
13 #define STACK_SIZE 0x1000
15 extern char _start
[], _end
[];
24 static inline void error(const char *msg
)
29 static inline uint32_t reloc_ptr(struct reloc_info
*ri
, void *ptr
)
31 return ri
->reloc_base
+ (uint32_t) ((char *)ptr
- _start
);
34 static void hijack_interrupt(int intn
, uint32_t handler
)
41 idt
[intn
].lo
= (idt
[intn
].lo
& 0xffff0000) | (handler
& 0x0000ffff);
42 idt
[intn
].hi
= (idt
[intn
].hi
& 0x0000ffff) | (handler
& 0xffff0000);
45 static void shift_cmdline(struct com32_sys_args
*com32
)
49 /* Skip leading whitespace */
50 for (p
= com32
->cs_cmdline
; *p
!= '\0' && *p
== ' '; p
++) ;
53 for (; *p
!= '\0' && *p
!= ' '; p
++) ;
55 /* Skip whitespace after first word */
56 for (; *p
!= '\0' && *p
== ' '; p
++) ;
58 com32
->cs_cmdline
= p
;
61 static __noreturn
reloc_entry(struct reloc_info
*ri
)
63 extern char int_handler
[];
64 size_t stack_frame_size
= sizeof(struct com32_sys_args
) + 4;
65 struct com32_sys_args
*com32
;
68 hijack_interrupt(X86_INT_DB
, reloc_ptr(ri
, int_handler
));
69 hijack_interrupt(X86_INT_BP
, reloc_ptr(ri
, int_handler
));
71 /* Copy module to load address */
72 memcpy(COM32_LOAD_ADDR
, ri
->data
, ri
->len
);
74 /* Copy stack frame onto module stack */
75 module_esp
= (ri
->reloc_base
- stack_frame_size
) & ~15;
76 memcpy((void *)module_esp
, (void *)ri
->old_esp
, stack_frame_size
);
78 /* Fix up command line */
79 com32
= (struct com32_sys_args
*)(module_esp
+ 4);
82 /* Set up CPU state to run module and enter GDB */
83 asm volatile ("movl %0, %%esp\n\t"
87 "jmp *%2\n\t"::"r" (module_esp
),
88 "c"(COM32_LOAD_ADDR
), "r"(reloc_ptr(ri
, int_handler
))
90 for (;;) ; /* shut the compiler up */
93 static inline __noreturn
reloc(void *ptr
, size_t len
)
95 extern uint32_t __entry_esp
;
96 size_t total_size
= _end
- _start
;
97 __noreturn(*entry_fn
) (struct reloc_info
*);
102 /* Calculate relocation address, preserve current stack */
103 asm volatile ("movl %%esp, %0\n\t":"=m" (esp
));
104 dest
= (char *)((esp
- STACK_SIZE
- total_size
) & ~3);
106 /* Calculate entry point in relocated code */
107 entry_fn
= (void *)(dest
+ ((char *)reloc_entry
- _start
));
109 /* Copy all sections to relocation address */
110 printf("Relocating %d bytes from %p to %p\n", total_size
, _start
, dest
);
111 memcpy(dest
, _start
, total_size
);
113 /* Call into relocated code */
116 ri
.old_esp
= __entry_esp
;
117 ri
.reloc_base
= (uint32_t) dest
;
121 int main(int argc
, char *argv
[])
126 openconsole(&dev_null_r
, &dev_stdcon_w
);
129 error("Usage: gdbstub.c32 com32_file arguments...\n");
133 if (loadfile(argv
[1], &data
, &data_len
)) {
134 error("Unable to load file\n");
140 /* No more lib calls after this point */
141 reloc(data
, data_len
);