X-Git-Url: https://pintos-os.org/cgi-bin/gitweb.cgi?a=blobdiff_plain;f=src%2Fthreads%2Fmalloc.c;h=9782a5a5ec161d70266d202e79c729c3b7b7d7da;hb=ac7b54c81e81f4b7a4cc404b5aa21f46a5dbdddd;hp=28f2324c79ef190d3357393546d80f5caff03546;hpb=f6580e9ad405b519dbe85027691bf3c66074b0a4;p=pintos-anon diff --git a/src/threads/malloc.c b/src/threads/malloc.c index 28f2324..9782a5a 100644 --- a/src/threads/malloc.c +++ b/src/threads/malloc.c @@ -1,11 +1,12 @@ -#include "malloc.h" +#include "threads/malloc.h" +#include +#include #include -#include "mmu.h" -#include "palloc.h" -#include "synch.h" -#include "lib/debug.h" -#include "lib/lib.h" -#include "lib/list.h" +#include +#include +#include "threads/mmu.h" +#include "threads/palloc.h" +#include "threads/synch.h" /* A simple implementation of malloc(). @@ -40,9 +41,13 @@ struct desc struct lock lock; /* Lock. */ }; +/* Magic number for detecting arena corruption. */ +#define ARENA_MAGIC 0x9a548eed + /* Arena. */ struct arena { + unsigned magic; /* Always set to ARENA_MAGIC. */ struct desc *desc; /* Owning descriptor. */ size_t free_cnt; /* Number of free blocks. */ }; @@ -54,7 +59,7 @@ struct block }; /* Our set of descriptors. */ -static struct desc descs[16]; /* Descriptors. */ +static struct desc descs[10]; /* Descriptors. */ static size_t desc_cnt; /* Number of descriptors. */ static struct arena *block_to_arena (struct block *); @@ -93,11 +98,11 @@ malloc (size_t size) /* Find the smallest descriptor that satisfies a SIZE-byte request. */ for (d = descs; d < descs + desc_cnt; d++) - if (size < d->block_size) + if (d->block_size >= size) break; if (d == descs + desc_cnt) { - printk ("malloc: %zu byte allocation too big\n", size); + printf ("malloc: %zu byte allocation too big\n", size); return NULL; } @@ -117,11 +122,12 @@ malloc (size_t size) } /* Initialize arena and add its blocks to the free list. */ + a->magic = ARENA_MAGIC; a->desc = d; a->free_cnt = d->blocks_per_arena; for (i = 0; i < d->blocks_per_arena; i++) { - b = arena_to_block (a, i); + struct block *b = arena_to_block (a, i); list_push_back (&d->free_list, &b->free_elem); } } @@ -160,13 +166,17 @@ calloc (size_t a, size_t b) void free (void *p) { - struct block *b = p; - struct arena *a = block_to_arena (b); - struct desc *d = a->desc; + struct block *b; + struct arena *a; + struct desc *d; if (p == NULL) return; + b = p; + a = block_to_arena (b); + d = a->desc; + lock_acquire (&d->lock); /* Add block to free list. */ @@ -193,13 +203,18 @@ free (void *p) static struct arena * block_to_arena (struct block *b) { - return pg_round_down (b); + struct arena *a = pg_round_down (b); + ASSERT (a != NULL); + ASSERT (a->magic == ARENA_MAGIC); + return a; } /* Returns the (IDX - 1)'th block within arena A. */ static struct block * arena_to_block (struct arena *a, size_t idx) { + ASSERT (a != NULL); + ASSERT (a->magic == ARENA_MAGIC); ASSERT (idx < a->desc->blocks_per_arena); return (struct block *) ((uint8_t *) a + sizeof *a