Pārlūkot izejas kodu

memalign(): fix padding

Ioannis Koutras 11 gadi atpakaļ
vecāks
revīzija
1155435b59
1 mainītis faili ar 10 papildinājumiem un 18 dzēšanām
  1. 10 18
      src/memalign.c

+ 10 - 18
src/memalign.c

@@ -1,5 +1,5 @@
 /*
- *   Copyright Institute of Communication and Computer Systems (ICCS) 
+ *   Copyright Institute of Communication and Computer Systems (ICCS)
  *
  *   Licensed under the Apache License, Version 2.0 (the "License");
  *   you may not use this file except in compliance with the License.
@@ -87,23 +87,13 @@ void *memalign(size_t alignment, size_t size) {
 
             /* A big block has to be created */
 
-            /* If the alignment size is smaller than the raw block header size,
-             * the padding may cause an overlap between the old and the new
-             * (aligned) raw block header. In order to ensure this is not
-             * happening and memcpy() is safe to be used, the alignment size is
-             * increased until it is bigger than the header size.
-             */
-            unsigned int counter = 0;
-            if(alignment < sizeof(raw_block_header_t)) {
-                size_t new_alignment = alignment;
-                for(counter = 0; new_alignment < sizeof(raw_block_header_t);
-                        counter++) {
-                    new_alignment += alignment;
-                }
-            }
+            /* extra_size denotes the worst-case scenario. Because memcpy() is
+             * used, at least HEADER_SIZE is needed for no memory overlap. */
+            size_t extra_size = sizeof(raw_block_header_t) + alignment - 1;
+
+            memptr = (void *)create_raw_block(size + extra_size +
+                    sizeof(raw_block_header_t), BIGBLOCK);
 
-            memptr = (void *)create_raw_block(size + (counter + 1) * alignment
-                    - 1 + sizeof(raw_block_header_t), BIGBLOCK);
             if(memptr != NULL) {
 
                 memptr = (void *)((uintptr_t) memptr +
@@ -112,7 +102,9 @@ void *memalign(size_t alignment, size_t size) {
                 /* Check if alignment is needed */
                 if(((uintptr_t) memptr) % alignment != 0) {
                     size_t padding = (- (size_t) memptr) & (alignment - 1);
-                    padding += counter * alignment;
+                    while(padding < sizeof(raw_block_header_t)) {
+                        padding += alignment;
+                    }
 
                     /* Sometimes a deadlock is observed unless the old mutex is
                      * destroyed.