Skip to content

Commit

Permalink
Free unused compartments, so they don't leak
Browse files Browse the repository at this point in the history
Following review feedback from Andrei, Laurie. Thanks both!
  • Loading branch information
probablytom committed Nov 13, 2023
1 parent 3c39dc7 commit bd783eb
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
29 changes: 29 additions & 0 deletions example_allocators/compartment_alloc/compartment_alloc.c
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,32 @@ void *__capability malloc_compartment(size_t len, void *__capability compartment

return allocated;
}

/*
* Unmaps the compartment identified by the `compartment_id` argument,
* effectively freeing it.
*
* Note that this is a naive implementation for demo purposes. The capabilities
* previously returned by `malloc_compartment` now point to de-allocated memory.
*/
void free_compartment(void *__capability compartment_id) {
int munmap_rc;
int i;

// Search for a compartment with the given identifier
for (i = 0; i < maxCompartments && compartments[i].identifier != compartment_id; i++)
{
}
if (i == maxCompartments)
{
perror("Given an ID for a non-existent compartment");
exit(1);
}

munmap_rc = munmap(compartments[i].buffer, compartments[i].max_allocated);
if (munmap_rc != 0) {
perror("Attempted to deallocate a compartment, but munmap errored");
exit(1);
}

}
1 change: 1 addition & 0 deletions example_allocators/compartment_alloc/compartment_alloc.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ typedef struct _heap_compartment

void *__capability init_compartment(size_t size_in_bytes, void *__capability dc);
void *__capability malloc_compartment(size_t len, void *__capability component_id);
void free_compartment(void *__capability compartment_id);
8 changes: 7 additions & 1 deletion example_allocators/compartment_alloc/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,13 @@ int main()
"read-only.\n\tWe allocated 256 bytes.\n");
pp_cap(c2_allocated_memory);

printf("\nCompleted successfully.\n");

// Clean up compartments
free_compartment(compartment1);
free_compartment(compartment2);

printf("\nFreed compartments.\n");

printf("\nCompleted successfully.\n");
return 0;
}

0 comments on commit bd783eb

Please sign in to comment.