memry.cpp 17.3 KB
Newer Older
T
tmbdev 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
/**********************************************************************
 * File:        memry.c  (Formerly memory.c)
 * Description: Memory allocation with builtin safety checks.
 * Author:					Ray Smith
 * Created:					Wed Jan 22 09:43:33 GMT 1992
 *
 * (C) Copyright 1992, Hewlett-Packard Ltd.
 ** Licensed under the Apache License, Version 2.0 (the "License");
 ** you may not use this file except in compliance with the License.
 ** You may obtain a copy of the License at
 ** http://www.apache.org/licenses/LICENSE-2.0
 ** Unless required by applicable law or agreed to in writing, software
 ** distributed under the License is distributed on an "AS IS" BASIS,
 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ** See the License for the specific language governing permissions and
 ** limitations under the License.
 *
 **********************************************************************/

#include          "mfcpch.h"
#include          <stdlib.h>
#ifdef __UNIX__
#include          <assert.h>
#endif
#include          "stderr.h"
#include          "tprintf.h"
#include          "memblk.h"
#include          "memry.h"

//#define COUNTING_CLASS_STRUCTURES

/**********************************************************************
 * new
 *
 * Replace global new to get at memory leaks etc.
 **********************************************************************/
/*
void*						operator new(				//allocate memory
size_t						size						//amount to allocate
)
{
  if (size==0)
  {
    err.log(RESULT_LOGICAL_ERROR,E_LOC,ERR_PRIMITIVES,
      ERR_SCROLLING,ERR_CONTINUE,ERR_ERROR,
      "Zero requested of new");
    size=1;
  }
  return alloc_big_mem(size);
}

void						operator delete(			//free memory
void*						addr						//mem to free
)
{
  free_big_mem(addr);
}*/

/**********************************************************************
 * check_mem
 *
 * Check consistency of all memory controlled by alloc_mem.
 **********************************************************************/

DLLSYM void check_mem(                     //check consistency
                      const char *string,  //context message
67
                      inT8 level           //level of check
T
tmbdev 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
                     ) {
  big_mem.check (string, level);
  main_mem.check (string, level);
  check_structs(level);
}


/**********************************************************************
 * alloc_string
 *
 * Allocate space for a string.  The space can only be used for chars as
 * it is not aligned.  Allocation is guaranteed to be fast and not cause
 * fragmentation for small strings (upto 10*worst alignment).  Calls for
 * larger strings will be satisfied with alloc_mem.
 * Use free_string to free the space from alloc_string.
 **********************************************************************/

DLLSYM char *alloc_string(             //allocate string
86
                          inT32 count  //no of chars required
T
tmbdev 已提交
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
                         ) {
#ifdef RAYS_MALLOC
  char *string;                  //allocated string

  if (count < 1 || count > MAX_CHUNK) {
    tprintf ("Invalid size %d requested of alloc_string", count);
    return NULL;
  }

  count++;                       //add size byte
  if (count <= MAX_STRUCTS * sizeof (MEMUNION)) {
    string = (char *) alloc_struct (count, "alloc_string");
    //get a fast structure
    if (string == NULL) {
      tprintf ("No memory for alloc_string");
      return NULL;
    }
104
    string[0] = (inT8) count;    //save its length
T
tmbdev 已提交
105 106 107 108 109 110 111 112 113 114 115 116
  }
  else {
                                 //get a big block
    string = (char *) alloc_mem (count);
    if (string == NULL) {
      tprintf ("No memory for alloc_string");
      return NULL;
    }
    string[0] = 0;               //mark its id
  }
  return &string[1];             //string for user
#else
117 118
  // Round up the amount allocated to a multiple of 4
  return static_cast<char*>(malloc((count + 3) & ~3));
T
tmbdev 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
#endif
}


/**********************************************************************
 * free_string
 *
 * Free a string allocated by alloc_string.
 **********************************************************************/

DLLSYM void free_string(              //free a string
                        char *string  //string to free
                       ) {
#ifdef RAYS_MALLOC
  if (((ptrdiff_t) string & 3) == 1) { //one over word
    string--;                    //get id marker
    if (*string == 0) {
      free_mem(string);  //generally free it
      return;
    }
    else if (*string <= MAX_STRUCTS * sizeof (MEMUNION)) {
                                 //free structure
      free_struct (string, *string, "alloc_string");
      return;
    }
  }
  tprintf ("Non-string given to free_string");
#else
  free(string);
#endif
}


/**********************************************************************
 * alloc_struct
 *
 * Allocate space for a structure.  This function is designed to be
 * fast and fragmentation free for arbitrary combinations of small
 * objects. (Upto 40 bytes in length.)
 * It can be used for any size of object up to 512K, but you must use
 * free_struct to release the memory it gives.  alloc_mem is better
 * for arbitrary data blocks of large size (>40 bytes.)
 * alloc_struct always aborts if the allocation fails.
 **********************************************************************/

DLLSYM void *
alloc_struct (                   //allocate memory
166
inT32 count,                     //no of chars required
T
tmbdev 已提交
167 168 169 170 171 172 173 174 175
#if defined COUNTING_CLASS_STRUCTURES
const char *name                 //name of type
#else
const char *                     //name of type
#endif
) {
#ifdef RAYS_MALLOC
  MEMUNION *element;             //current element
  MEMUNION *returnelement;       //return value
176 177 178
  inT32 struct_count;            //no of required structs
  inT32 blocksize;               //no of structs in block
  inT32 index;                   //index to structure
T
tmbdev 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250

  if (count < 1 || count > MAX_CHUNK) {
    tprintf ("Invalid size %d requested of alloc_struct", count);
    return NULL;
  }

  //      tprintf("Allocating structure of size %d\n",count);
                                 //no of MEMUNIONS-1
  struct_count = (count - 1) / sizeof (MEMUNION);
  if (struct_count < MAX_STRUCTS) {
                                 //can do fixed sizes
    #ifdef COUNTING_CLASS_STRUCTURES
    if (name != NULL) {
      index = identify_struct_owner (struct_count, name);
      if (index < MAX_CLASSES)
        owner_counts[struct_count][index]++;
    }
    #endif
                                 //head of freelist
    returnelement = free_structs[struct_count];
    if (returnelement == NULL) {
                                 //need a new block
                                 //get one
      element = (MEMUNION *) new_struct_block ();
      if (element == NULL) {
        tprintf ("No memory to satisfy request for %d", (int) count);
        return NULL;
      }
                                 //add to block list
      element->ptr = struct_blocks[struct_count];
      struct_blocks[struct_count] = element;
      blocks_in_use[struct_count]++;
      element++;                 //free cell
      returnelement = element;   //going to return 1st
      blocksize = STRUCT_BLOCK_SIZE / (struct_count + 1) - 1;

      for (index = 1; index < blocksize; index++) {
                                 //make links
        element->ptr = element + struct_count + 1;
        element += struct_count + 1;
      }
      element->ptr = NULL;       //end of freelist
    }
                                 //new free one
    free_structs[struct_count] = returnelement->ptr;
                                 //count number issued
    structs_in_use[struct_count]++;
  }
  else {
                                 //just get some
    returnelement = (MEMUNION *) alloc_mem (count);
    if (returnelement == NULL) {
      tprintf ("No memory to satisfy request for %d", (int) count);
      return NULL;
    }
  }
  return returnelement;          //free cell
#else
  return malloc(count);
#endif
}


/**********************************************************************
 * free_struct
 *
 * Free memory allocated by alloc_struct.  The size must be supplied.
 **********************************************************************/

DLLSYM void
free_struct (                    //free a structure
void *deadstruct,                //structure to free
251
inT32 count,                     //no of bytes
T
tmbdev 已提交
252 253 254 255 256 257 258 259 260 261 262 263 264
#if defined COUNTING_CLASS_STRUCTURES
const char *name                 //name of type
#else
const char *                     //name of type
#endif
) {
#ifdef RAYS_MALLOC
  MEMUNION *end_element;         //current element
  MEMUNION *element;             //current element
  MEMUNION *prev_element;        //previous element
  MEMUNION *prev_block;          //previous element
  MEMUNION *nextblock;           //next block in list
  MEMUNION *block;               //next block in list
265 266
  inT32 struct_count;            //no of required structs
  inT32 index;                   //to structure counts
T
tmbdev 已提交
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389

  if (count < 1 || count > MAX_CHUNK) {
    tprintf ("Invalid size %d requested of free_struct", count);
    return;
  }

  //      tprintf("Freeing structure of size %d\n",count);
                                 //no of MEMUNIONS-1
  struct_count = (count - 1) / sizeof (MEMUNION);

  if (deadstruct == NULL) {
                                 //not really legal
    check_struct(MEMCHECKS, count);
  }
  else {
    if (struct_count < MAX_STRUCTS) {
                                 //can do fixed sizes
      #ifdef COUNTING_CLASS_STRUCTURES
      if (name != NULL) {
        index = identify_struct_owner (struct_count, name);
        if (index < MAX_CLASSES) {
          owner_counts[struct_count][index]--;
          ASSERT_HOST (owner_counts[struct_count][index] >= 0);
        }
      }
      #endif
      element = (MEMUNION *) deadstruct;
                                 //add to freelist
      element->ptr = free_structs[struct_count];
      free_structs[struct_count] = element;
                                 //one less in use
      structs_in_use[struct_count]--;
      if (structs_in_use[struct_count] == 0) {
        index = 0;
        for (element = struct_blocks[struct_count];
        element != NULL; element = nextblock) {
                                 //traverse and destroy
          nextblock = element->ptr;
                                 //free all the blocks
          old_struct_block(element);
          index++;
        }
                                 //none left any more
        struct_blocks[struct_count] = NULL;
                                 //no free structs
        free_structs[struct_count] = NULL;
        blocks_in_use[struct_count] = 0;
      }
      else if (structs_in_use[struct_count] < 0) {
        tprintf ("Negative number of structs of size %d in use",
          (int) count);
      }
      else if (structs_in_use[struct_count] < blocks_in_use[struct_count]) {
        prev_block = NULL;
        for (block = struct_blocks[struct_count];
        block != NULL; block = nextblock) {
          nextblock = block;
          index = STRUCT_BLOCK_SIZE / (struct_count + 1) - 1;
          end_element = block + STRUCT_BLOCK_SIZE;
          for (element = free_structs[struct_count];
          element != NULL; element = element->ptr) {
            if (element > nextblock && element < end_element) {
              index--;
              if (index == 0)
                break;
            }
          }
          if (index == 0) {
            index = STRUCT_BLOCK_SIZE / (struct_count + 1) - 1;
            for (element =
              free_structs[struct_count], prev_element = NULL;
            element != NULL; element = element->ptr) {
              if (element > nextblock && element < end_element) {
                index--;
                if (prev_element != NULL)
                  prev_element->ptr = element->ptr;
                else
                  free_structs[struct_count] = element->ptr;
                if (index == 0)
                  break;
              }
              else
                prev_element = element;
            }
            if (prev_block != NULL)
              prev_block->ptr = block->ptr;
            else
              struct_blocks[struct_count] = block->ptr;
            nextblock = block->ptr;
            blocks_in_use[struct_count]--;
                                 //free all the blocks
            old_struct_block(block);
          }
          else {
            prev_block = block;
                                 //traverse and destroy
            nextblock = block->ptr;
          }
        }
      }
    }
    else
      free_mem(deadstruct);  //free directly
  }
#else
  free(deadstruct);
#endif
}


/**********************************************************************
 * alloc_mem_p
 *
 * Allocate permanent space which will never be returned.
 * This space is allocated from the top end of a memory block to
 * avoid the fragmentation which would result from alternate use
 * of alloc_mem for permanent and temporary blocks.
 **********************************************************************/

//#ifdef __UNIX__
//#pragma OPT_LEVEL 0
//#endif
DLLSYM void *alloc_mem_p(             //allocate permanent space
390
                         inT32 count  //block size to allocate
T
tmbdev 已提交
391 392 393 394 395 396 397 398
                        ) {
  #ifdef RAYS_MALLOC
  #ifdef TESTING_BIGSTUFF
  if (main_mem.biggestblock == 0)
    main_mem.init (alloc_big_mem, free_big_mem,
      FIRSTSIZE, LASTSIZE, MAX_CHUNK);
  #else
  if (main_mem.biggestblock == 0)
399
    main_mem.init ((void *(*)(inT32)) malloc, free,
T
tmbdev 已提交
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
      FIRSTSIZE, LASTSIZE, MAX_CHUNK);
  #endif
  if (mem_mallocdepth > 0)
    return main_mem.alloc_p (count, trace_caller (mem_mallocdepth));
  else
    return main_mem.alloc_p (count, NULL);
  #else
  return malloc ((size_t) count);
  #endif
}


/**********************************************************************
 * alloc_mem
 *
 * Return a pointer to a buffer of count bytes aligned for any type.
 **********************************************************************/

DLLSYM void *alloc_mem(             //get some memory
419
                       inT32 count  //no of bytes to get
T
tmbdev 已提交
420 421 422 423 424 425 426 427
                      ) {
  #ifdef RAYS_MALLOC
  #ifdef TESTING_BIGSTUFF
  if (main_mem.biggestblock == 0)
    main_mem.init (alloc_big_mem, free_big_mem,
      FIRSTSIZE, LASTSIZE, MAX_CHUNK);
  #else
  if (main_mem.biggestblock == 0)
428
    main_mem.init ((void *(*)(inT32)) malloc, free,
T
tmbdev 已提交
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
      FIRSTSIZE, LASTSIZE, MAX_CHUNK);
  #endif
  if (mem_mallocdepth > 0)
    return main_mem.alloc (count, trace_caller (mem_mallocdepth));
  else
    return main_mem.alloc (count, NULL);
  #else
  return malloc ((size_t) count);
  #endif
}


/**********************************************************************
 * alloc_big_mem
 *
 * Return a pointer to a buffer of count bytes aligned for any type.
 **********************************************************************/

DLLSYM void *alloc_big_mem(             //get some memory
448
                           inT32 count  //no of bytes to get
T
tmbdev 已提交
449 450 451
                          ) {
  #ifdef TESTING_BIGSTUFF
  if (big_mem.biggestblock == 0)
452
    big_mem.init ((void *(*)(inT32)) malloc, free,
T
tmbdev 已提交
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
      BIGSIZE, BIGSIZE, MAX_BIGCHUNK);
  if (mem_mallocdepth > 0)
    return big_mem.alloc (count, trace_caller (mem_mallocdepth));
  else
    return big_mem.alloc (count, NULL);
  #else
  return malloc ((size_t) count);
  #endif
}


/**********************************************************************
 * alloc_big_zeros
 *
 * Return a pointer to a buffer of count bytes aligned for any type.
 **********************************************************************/

DLLSYM void *alloc_big_zeros(             //get some memory
471
                             inT32 count  //no of bytes to get
T
tmbdev 已提交
472 473 474
                            ) {
  #ifdef TESTING_BIGSTUFF
  if (big_mem.biggestblock == 0)
475
    big_mem.init ((void *(*)(inT32)) malloc, free,
T
tmbdev 已提交
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
      BIGSIZE, BIGSIZE, MAX_BIGCHUNK);
  void *buf;                     //return value

  if (mem_mallocdepth > 0)
    buf = big_mem.alloc (count, trace_caller (mem_mallocdepth));
  else
    buf = big_mem.alloc (count, NULL);
  memset (buf, 0, count);
  return buf;
  #else
  return calloc ((size_t) count, 1);
  #endif
}


/**********************************************************************
 * free_mem
 *
 * Free a block allocated by alloc_mem (or alloc_mem_p).
 * It checks that the pointer is legal and maintains counts of the
 * amount of free memory above and below the current free pointer.
 **********************************************************************/

DLLSYM void free_mem(                //free mem from alloc_mem
                     void *oldchunk  //chunk to free
                    ) {
  #ifdef RAYS_MALLOC
  if (mem_freedepth > 0 && main_mem.callers != NULL)
    main_mem.dealloc (oldchunk, trace_caller (mem_freedepth));
  else
    main_mem.dealloc (oldchunk, NULL);
  #else
  free(oldchunk);
  #endif
}


/**********************************************************************
 * free_big_mem
 *
 * Free a block allocated by alloc_big_mem.
 * It checks that the pointer is legal and maintains counts of the
 * amount of free memory above and below the current free pointer.
 **********************************************************************/

DLLSYM void free_big_mem(                //free mem from alloc_mem
                         void *oldchunk  //chunk to free
                        ) {
  #ifdef TESTING_BIGSTUFF
  if (mem_freedepth > 0 && main_mem.callers != NULL)
    big_mem.dealloc (oldchunk, trace_caller (mem_freedepth));
  else
    big_mem.dealloc (oldchunk, NULL);
  #else
  free(oldchunk);
  #endif
}