comparison src/c/urweb.c @ 2013:77cc9169d6e0

Change context-local memory allocation to return word-aligned addresses (based on patch by Evan Danaher)
author Adam Chlipala <adam@chlipala.net>
date Sun, 18 May 2014 18:58:50 -0400
parents 93ff76058825
children 4a93f379c452
comparison
equal deleted inserted replaced
2012:2b2d07946e65 2013:77cc9169d6e0
1254 1254
1255 void uw_end_initializing(uw_context ctx) { 1255 void uw_end_initializing(uw_context ctx) {
1256 ctx->amInitializing = 0; 1256 ctx->amInitializing = 0;
1257 } 1257 }
1258 1258
1259 static void align_heap(uw_context ctx) {
1260 size_t posn = ctx->heap.front - ctx->heap.start;
1261
1262 if (posn % 4 != 0) {
1263 size_t bump = 4 - posn % 4;
1264 uw_check_heap(ctx, bump);
1265 ctx->heap.front += bump;
1266 }
1267 }
1268
1259 void *uw_malloc(uw_context ctx, size_t len) { 1269 void *uw_malloc(uw_context ctx, size_t len) {
1270 // On some architectures, it's important that all word-sized memory accesses
1271 // be to word-aligned addresses, so we'll do a little bit of extra work here
1272 // in anticipation of a possible word-aligned access to the address we'll
1273 // return.
1274
1260 void *result; 1275 void *result;
1261 1276
1262 if (ctx->amInitializing) { 1277 if (ctx->amInitializing) {
1263 result = malloc(len); 1278 int error = posix_memalign(&result, 4, len);
1264 1279
1265 if (result) 1280 if (!error)
1266 return result; 1281 return result;
1267 else 1282 else
1268 uw_error(ctx, FATAL, "uw_malloc: malloc() returns 0"); 1283 uw_error(ctx, FATAL, "uw_malloc: posix_memalign() returns %d", error);
1269 } else { 1284 } else {
1285 align_heap(ctx);
1286
1270 uw_check_heap(ctx, len); 1287 uw_check_heap(ctx, len);
1271 1288
1272 result = ctx->heap.front; 1289 result = ctx->heap.front;
1273 ctx->heap.front += len; 1290 ctx->heap.front += len;
1274 return result; 1291 return result;
1275 } 1292 }
1276 } 1293 }
1277 1294
1278 void uw_begin_region(uw_context ctx) { 1295 void uw_begin_region(uw_context ctx) {
1296 align_heap(ctx);
1297
1279 regions *r = (regions *) ctx->heap.front; 1298 regions *r = (regions *) ctx->heap.front;
1280 1299
1281 uw_check_heap(ctx, sizeof(regions)); 1300 uw_check_heap(ctx, sizeof(regions));
1282 1301
1283 ctx->heap.front += sizeof(regions); 1302 ctx->heap.front += sizeof(regions);