/* * Input: Mem_T structure, unsigned integer * Output: void * Purpose: Unmaps a segment from memory at the given segment index and frees * all memory associated with it. */ void unmap_segment(Mem_T memory, unsigned segIndex) { Seg_T unmapped_segment = Mem_arr_put(memory->segment_seq, NULL, segIndex); Seg_free(unmapped_segment); //fprintf(stderr, "about to push onto stack\n"); memory->reusable_indices = Stack_push(memory->reusable_indices, segIndex); //fprintf(stderr, "pushing onto stack\n"); }
/* free the mem */ void free_mem(Mem* myMem) { assert(myMem != NULL); for (int i = 0; i < Seq_length((*myMem)->segs); i++) { Seg_free(Seq_get((*myMem)->segs, i)); } Seq_free(&((*myMem)->segs)); Stack_free(&((*myMem)->unmapped)); free(*myMem); }
/* * Input: Mem_T structure, unsigned integer * Ouput: void * Purpose: Copies the segment located at segIndex and stores it in segment 0 * The segment previously at index 0 is freed. */ void load_program(Mem_T memory, unsigned segIndex) { /*Segment that will become new program*/ Seg_T program_to_load = Mem_arr_get(memory->segment_seq, segIndex); Seg_T duplicate_segment = Seg_duplicate(program_to_load); /*Copies program_to_load_temp to program_to_load*/ Seg_T old_program = Mem_arr_put(memory->segment_seq, duplicate_segment, 0); Seg_free(old_program); }
/* * create a segment with the size of nums, and return the index of the segs of * the mapped segment. There are two conditons, if the unmapped stack is not * empty, we reuse the segment index stored in unmapped stack and pop that out. * otherwise we just create a new segments and addhi into segs, the return index * is the length of segs. */ uint32_t map_segment(Mem myMem, uint32_t nums) { assert(myMem != NULL); Segment_T newSeg = Seg_new(nums); for (uint32_t i = 0; i < nums; i++) { Seq_addhi((Seq_T)newSeg, (void*) (uintptr_t) 0); } uint32_t index; if (Stack_empty(myMem->unmapped) == 1) { Seq_addhi(myMem->segs, (void*) newSeg); index = Seq_length(myMem->segs) - 1; } else { index = (int) (uintptr_t) Stack_pop(myMem->unmapped); Seg_free(Seq_put(myMem->segs, index, (void*) newSeg)); }; return index; }