refactor: elf parsing utility and exec related
[lunaix-os.git] / lunaix-os / kernel / mm / dmm.c
1 #include <lunaix/mm/mmap.h>
2 #include <lunaix/mm/vmm.h>
3 #include <lunaix/process.h>
4 #include <lunaix/status.h>
5
6 #include <lunaix/spike.h>
7 #include <lunaix/syscall.h>
8 #include <lunaix/syscall_utils.h>
9
10 void
11 __heap_copied(struct mm_region* region)
12 {
13     mm_index((void**)&region->proc_vms->heap, region);
14 }
15
16 int
17 create_heap(struct proc_mm* pvms, ptr_t addr)
18 {
19     struct mmap_param map_param = { .pvms = pvms,
20                                     .vms_mnt = VMS_SELF,
21                                     .flags = MAP_ANON | MAP_PRIVATE,
22                                     .type = REGION_TYPE_HEAP,
23                                     .proct = PROT_READ | PROT_WRITE,
24                                     .mlen = PG_SIZE };
25     int status = 0;
26     struct mm_region* heap;
27     if ((status = mem_map(NULL, &heap, addr, NULL, &map_param))) {
28         return status;
29     }
30
31     heap->region_copied = __heap_copied;
32     mm_index((void**)&pvms->heap, heap);
33 }
34
35 __DEFINE_LXSYSCALL1(void*, sbrk, ssize_t, incr)
36 {
37     struct proc_mm* pvms = &__current->mm;
38     struct mm_region* heap = pvms->heap;
39
40     assert(heap);
41     int err = mem_adjust_inplace(&pvms->regions, heap, heap->end + incr);
42     if (err) {
43         return (void*)DO_STATUS(err);
44     }
45     return (void*)heap->end;
46 }
47
48 __DEFINE_LXSYSCALL1(int, brk, void*, addr)
49 {
50     struct proc_mm* pvms = &__current->mm;
51     struct mm_region* heap = pvms->heap;
52
53     if (!heap) {
54         return DO_STATUS(create_heap(pvms, addr));
55     }
56
57     assert(heap);
58     int err = mem_adjust_inplace(&pvms->regions, heap, (ptr_t)addr);
59     return DO_STATUS(err);
60 }