1212#include <heap.h>
1313#include <stddef.h>
1414#include <graphics.h>
15+ #include <memory2.h>
1516
1617uint32_t last_alloc = 0 ;
1718uint32_t heap_end = 0 ;
@@ -47,6 +48,19 @@ void mm_extend(uint32_t additional_size)
4748 done ("Heap extended." , __FILE__ );
4849}
4950
51+ void mm_constrict (uint32_t removal_size )
52+ {
53+ if (removal_size <= 0 ){
54+ warn ("mm_extend: Invalid size." , __FILE__ );
55+ return ;
56+ }
57+
58+ info ("Constricting heap." , __FILE__ );
59+ heap_end -= removal_size ;
60+ printf ("Heap constricting by %d bytes. New heap end: 0x%x" , removal_size , heap_end );
61+ done ("Heap Constricted." , __FILE__ );
62+ }
63+
5064void mm_print_out ()
5165{
5266 printf ("%sMemory used :%s %d bytes" , yellow_color , reset_color , memory_used );
@@ -56,6 +70,11 @@ void mm_print_out()
5670
5771void free (void * mem )
5872{
73+ if (mem == 0 ){
74+ warn ("free: Cannot free null pointer." , __FILE__ );
75+ return ;
76+ }
77+
5978 alloc_t * alloc = (mem - sizeof (alloc_t ));
6079 memory_used -= alloc -> size + sizeof (alloc_t );
6180 alloc -> status = 0 ;
@@ -75,7 +94,11 @@ void pfree(void *mem)
7594
7695char * pmalloc (size_t size )
7796{
78- /* Loop through the avail_list */
97+ if (size <= 0 ){
98+ warn ("pmalloc: Cannot allocate 0 bytes." , __FILE__ );
99+ return 0 ;
100+ }
101+
79102 for (int i = 0 ; i < MAX_PAGE_ALIGNED_ALLOCS ; i ++ )
80103 {
81104 if (pheap_desc [i ]) continue ;
@@ -89,7 +112,10 @@ char* pmalloc(size_t size)
89112
90113char * malloc (size_t size )
91114{
92- if (!size ) return 0 ;
115+ if (size <= 0 ){
116+ warn ("malloc: Cannot allocate 0 bytes." , __FILE__ );
117+ return 0 ;
118+ }
93119
94120 /* Loop through blocks and find a block sized the same or bigger */
95121 uint8_t * mem = (uint8_t * )heap_begin ;
@@ -134,7 +160,7 @@ char* malloc(size_t size)
134160 nalloc :;
135161 if (last_alloc + size + sizeof (alloc_t ) >= heap_end )
136162 {
137- meltdown_screen ("Heap out of memory!" , __FILE__ , __LINE__ , 0 , 0 , 0 );
163+ meltdown_screen ("Heap out of memory!" , __FILE__ , __LINE__ , 0 , getCR2 () , 0 );
138164 hcf ();
139165 }
140166 alloc_t * alloc = (alloc_t * )last_alloc ;
@@ -144,6 +170,7 @@ char* malloc(size_t size)
144170 last_alloc += size ;
145171 last_alloc += sizeof (alloc_t );
146172 last_alloc += 4 ;
173+
147174 // printf("Allocated %d bytes from to 0x%x", size, (uint32_t)alloc + sizeof(alloc_t), last_alloc);
148175 memory_used += size + 4 + sizeof (alloc_t );
149176 memset ((char * )((uint32_t )alloc + sizeof (alloc_t )), 0 , size );
0 commit comments