module: add exitcall function

Signed-off-by: Michael Shaw <m@michaelsshaw.com>
This commit is contained in:
Michael Shaw 2026-08-12 12:15:59 -04:00
commit 3abfd32fbb
Signed by: michaelsshaw
GPG key ID: 5A5E0FB20708A9E7
6 changed files with 110 additions and 11 deletions

View file

@ -22,6 +22,52 @@ static const char elf_sig[4] = {0x7f, 'E', 'L', 'F'};
extern char __kernel_end[];
static vaddr_t mod_next_vaddr;
struct loaded_mod {
struct loaded_mod *next;
char name[32];
void *base;
size_t size;
void (*exit)(void);
};
static struct loaded_mod *mod_list;
static struct loaded_mod *mod_add(const char *name, void *base, size_t size, void (*exit)(void))
{
struct loaded_mod *m = kalloc(sizeof(struct loaded_mod), ALLOC_KERN);
if (!m)
return NULL;
strncpy(m->name, name, sizeof(m->name) - 1);
m->name[sizeof(m->name) - 1] = 0;
m->base = base;
m->size = size;
m->exit = exit;
m->next = mod_list;
mod_list = m;
return m;
}
static struct loaded_mod *mod_find(const char *name)
{
for (struct loaded_mod *m = mod_list; m; m = m->next)
if (strcmp(m->name, name) == 0)
return m;
return NULL;
}
static void mod_remove(struct loaded_mod *m)
{
struct loaded_mod **pp = &mod_list;
while (*pp) {
if (*pp == m) {
*pp = m->next;
kfree(m);
return;
}
pp = &(*pp)->next;
}
}
static void *alloc_module(size_t size)
{
if (!mod_next_vaddr)
@ -52,10 +98,7 @@ static void *sym_lookup(const char *name)
static int str_prefix(const char *str, const char *pre)
{
while (*pre)
if (*str++ != *pre++)
return 0;
return 1;
return strncmp(str, pre, strlen(pre)) == 0;
}
static int elf_validate(const struct ehdr *ehdr, size_t fsize)
@ -199,7 +242,7 @@ static void call_initcalls(const struct shdr *shdr, struct sec_info *secs, size_
}
}
static int elf_load(const char *file, size_t fsize)
static int elf_load(const char *name, const char *file, size_t fsize)
{
const struct ehdr *ehdr = (const struct ehdr *)file;
@ -243,8 +286,22 @@ static int elf_load(const char *file, size_t fsize)
if (apply_reloc(shdr, secs, n_sec, file, base, sym_val))
goto err_sym;
void (*exit)(void) = NULL;
for (size_t i = 0; i < n_sec; i++) {
if (!secs[i].loadable)
continue;
if (!str_prefix(shstrtab + shdr[i].sh_name, ".exitcall"))
continue;
void (**fn)(void) = (void (**)(void))(base + secs[i].load_off);
if (fn[0])
exit = fn[0];
break;
}
call_initcalls(shdr, secs, n_sec, shstrtab, base);
mod_add(name, base, total, exit);
kfree(sym_val);
kfree(secs);
return 0;
@ -271,8 +328,27 @@ int driver_load(const char *name)
vfs_read(dent->inode, buf, dent->inode->file_size, 0);
int ret = elf_load(buf, dent->inode->file_size);
int ret = elf_load(name, buf, dent->inode->file_size);
kfree(buf);
return ret;
}
int driver_unload(const char *name)
{
if (!name)
return -EINVAL;
struct loaded_mod *m = mod_find(name);
if (!m)
return -ENOENT;
if (m->exit)
m->exit();
page_unmap(kpgd, (vaddr_t)m->base, m->size, NULL);
tlb_flush();
mod_remove(m);
return 0;
}