-
+ 9DEA2170DE57AC92123D3DAC0FD5930BC5C1A5AC88CA1C2FDA88C8555091A38E5862FD7AC5BCED9393349F66AB970707B27D759FE0041F358A0D205E066ECDE0
mpi/memory.c
(0 . 0)(1 . 681)
5301 /* memory.c - memory allocation
5302 * Copyright (C) 1998, 1999, 2001, 2005 Free Software Foundation, Inc.
5303 *
5304 * This file is part of GnuPG.
5305 *
5306 * GnuPG is free software; you can redistribute it and/or modify
5307 * it under the terms of the GNU General Public License as published by
5308 * the Free Software Foundation; either version 3 of the License, or
5309 * (at your option) any later version.
5310 *
5311 * GnuPG is distributed in the hope that it will be useful,
5312 * but WITHOUT ANY WARRANTY; without even the implied warranty of
5313 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
5314 * GNU General Public License for more details.
5315 *
5316 * You should have received a copy of the GNU General Public License
5317 * along with this program; if not, see <http://www.gnu.org/licenses/>.
5318 *
5319 *
5320 * We use our own memory allocation functions instead of plain malloc(),
5321 * so that we can provide some special enhancements:
5322 * a) functions to provide memory from a secure memory.
5323 * b) by looking at the requested allocation size we
5324 * can reuse memory very quickly (e.g. MPI storage)
5325 * (really needed?)
5326 * c) memory usage reporting if compiled with M_DEBUG
5327 * d) memory checking if compiled with M_GUARD
5328 */
5329
5330 #include <config.h>
5331 #include <stdio.h>
5332 #include <stdlib.h>
5333 #include <string.h>
5334 #include <stdarg.h>
5335
5336 #include "types.h"
5337 #include "memory.h"
5338 #include "util.h"
5339
5340
5341 #define MAGIC_NOR_BYTE 0x55
5342 #define MAGIC_SEC_BYTE 0xcc
5343 #define MAGIC_END_BYTE 0xaa
5344
5345 /* This is a very crude alignment check which does not work on all CPUs
5346 * IIRC, I once introduced it for testing on an Alpha. We should better
5347 * replace this guard stuff with one provided by a modern malloc library
5348 */
5349 #if SIZEOF_UNSIGNED_LONG == 8
5350 #define EXTRA_ALIGN 4
5351 #else
5352 #define EXTRA_ALIGN 0
5353 #endif
5354
5355 #if defined(M_DEBUG) || defined(M_GUARD)
5356 static void membug( const char *fmt, ... );
5357 #endif
5358
5359 #ifdef M_DEBUG
5360
5361 #ifndef M_GUARD
5362 #define M_GUARD 1
5363 #endif
5364 #undef xmalloc
5365 #undef xtrymalloc
5366 #undef xmalloc_clear
5367 #undef xmalloc_secure
5368 #undef xmalloc_secure_clear
5369 #undef xrealloc
5370 #undef xfree
5371 #undef m_check
5372 #undef xstrdup
5373 #undef xtrystrdup
5374 #define FNAME(a) m_debug_ ##a
5375 #define FNAMEX(a) m_debug_ ##a
5376 #define FNAMEXM(a) m_debug_ ##a
5377 #define FNAMEPRT , const char *info
5378 #define FNAMEARG , info
5379 #ifndef __riscos__
5380 #define store_len(p,n,m) do { add_entry(p,n,m, \
5381 info, __FUNCTION__); } while(0)
5382 #else
5383 #define store_len(p,n,m) do { add_entry(p,n,m, \
5384 info, __func__ ); } while(0)
5385 #endif
5386 #else
5387 #define FNAME(a) m_ ##a
5388 #define FNAMEX(a) x ##a
5389 #define FNAMEXM(a) xm ##a
5390 #define FNAMEPRT
5391 #define FNAMEARG
5392 #define store_len(p,n,m) do { ((byte*)p)[EXTRA_ALIGN+0] = n; \
5393 ((byte*)p)[EXTRA_ALIGN+1] = n >> 8 ; \
5394 ((byte*)p)[EXTRA_ALIGN+2] = n >> 16 ; \
5395 ((byte*)p)[EXTRA_ALIGN+3] = m? MAGIC_SEC_BYTE \
5396 : MAGIC_NOR_BYTE; \
5397 } while(0)
5398 #endif
5399
5400
5401 #ifdef M_GUARD
5402 static long used_memory;
5403 #endif
5404
5405 #ifdef M_DEBUG /* stuff used for memory debuging */
5406
5407 struct info_entry {
5408 struct info_entry *next;
5409 unsigned count; /* call count */
5410 const char *info; /* the reference to the info string */
5411 };
5412
5413 struct memtbl_entry {
5414 const void *user_p; /* for reference: the pointer given to the user */
5415 size_t user_n; /* length requested by the user */
5416 struct memtbl_entry *next; /* to build a list of unused entries */
5417 const struct info_entry *info; /* points into the table with */
5418 /* the info strings */
5419 unsigned inuse:1; /* this entry is in use */
5420 unsigned count:31;
5421 };
5422
5423
5424 #define INFO_BUCKETS 53
5425 #define info_hash(p) ( *(u32*)((p)) % INFO_BUCKETS )
5426 static struct info_entry *info_strings[INFO_BUCKETS]; /* hash table */
5427
5428 static struct memtbl_entry *memtbl; /* the table with the memory info */
5429 static unsigned memtbl_size; /* number of allocated entries */
5430 static unsigned memtbl_len; /* number of used entries */
5431 static struct memtbl_entry *memtbl_unused;/* to keep track of unused entries */
5432
5433 static void dump_table_at_exit(void);
5434 static void dump_table(void);
5435 static void check_allmem( const char *info );
5436
5437 /****************
5438 * Put the new P into the debug table and return a pointer to the table entry.
5439 * mode is true for security. BY is the name of the function which called us.
5440 */
5441 static void
5442 add_entry( byte *p, unsigned n, int mode, const char *info, const char *by )
5443 {
5444 unsigned index;
5445 struct memtbl_entry *e;
5446 struct info_entry *ie;
5447
5448 if( memtbl_len < memtbl_size )
5449 index = memtbl_len++;
5450 else {
5451 struct memtbl_entry *e;
5452 /* look for a used entry in the table. We take the first one,
5453 * so that freed entries remain as long as possible in the table
5454 * (free appends a new one)
5455 */
5456 if( (e = memtbl_unused) ) {
5457 index = e - memtbl;
5458 memtbl_unused = e->next;
5459 e->next = NULL;
5460 }
5461 else { /* no free entries in the table: extend the table */
5462 if( !memtbl_size ) { /* first time */
5463 memtbl_size = 100;
5464 if( !(memtbl = calloc( memtbl_size, sizeof *memtbl )) )
5465 membug("memory debug table malloc failed\n");
5466 index = 0;
5467 memtbl_len = 1;
5468 atexit( dump_table_at_exit );
5469 }
5470 else { /* realloc */
5471 unsigned n = memtbl_size / 4; /* enlarge by 25% */
5472 if(!(memtbl = realloc(memtbl, (memtbl_size+n)*sizeof *memtbl)))
5473 membug("memory debug table realloc failed\n");
5474 memset(memtbl+memtbl_size, 0, n*sizeof *memtbl );
5475 memtbl_size += n;
5476 index = memtbl_len++;
5477 }
5478 }
5479 }
5480 e = memtbl+index;
5481 if( e->inuse )
5482 membug("Ooops: entry %u is flagged as in use\n", index);
5483 e->user_p = p + EXTRA_ALIGN + 4;
5484 e->user_n = n;
5485 e->count++;
5486 if( e->next )
5487 membug("Ooops: entry is in free entry list\n");
5488 /* do we already have this info string */
5489 for( ie = info_strings[info_hash(info)]; ie; ie = ie->next )
5490 if( ie->info == info )
5491 break;
5492 if( !ie ) { /* no: make a new entry */
5493 if( !(ie = malloc( sizeof *ie )) )
5494 membug("can't allocate info entry\n");
5495 ie->next = info_strings[info_hash(info)];
5496 info_strings[info_hash(info)] = ie;
5497 ie->info = info;
5498 ie->count = 0;
5499 }
5500 ie->count++;
5501 e->info = ie;
5502 e->inuse = 1;
5503
5504 /* put the index at the start of the memory */
5505 p[EXTRA_ALIGN+0] = index;
5506 p[EXTRA_ALIGN+1] = index >> 8 ;
5507 p[EXTRA_ALIGN+2] = index >> 16 ;
5508 p[EXTRA_ALIGN+3] = mode? MAGIC_SEC_BYTE : MAGIC_NOR_BYTE ;
5509 if( DBG_MEMORY )
5510 log_debug( "%s allocates %u bytes using %s\n", info, e->user_n, by );
5511 }
5512
5513
5514
5515 /****************
5516 * Check that the memory block is correct. The magic byte has already been
5517 * checked. Checks which are done here:
5518 * - see whether the index points into our memory table
5519 * - see whether P is the same as the one stored in the table
5520 * - see whether we have already freed this block.
5521 */
5522 struct memtbl_entry *
5523 check_mem( const byte *p, const char *info )
5524 {
5525 unsigned n;
5526 struct memtbl_entry *e;
5527
5528 n = p[EXTRA_ALIGN+0];
5529 n |= p[EXTRA_ALIGN+1] << 8;
5530 n |= p[EXTRA_ALIGN+2] << 16;
5531
5532 if( n >= memtbl_len )
5533 membug("memory at %p corrupted: index=%u table_len=%u (%s)\n",
5534 p+EXTRA_ALIGN+4, n, memtbl_len, info );
5535 e = memtbl+n;
5536
5537 if( e->user_p != p+EXTRA_ALIGN+4 )
5538 membug("memory at %p corrupted: reference mismatch (%s)\n",
5539 p+EXTRA_ALIGN+4, info );
5540 if( !e->inuse )
5541 membug("memory at %p corrupted: marked as free (%s)\n",
5542 p+EXTRA_ALIGN+4, info );
5543
5544 if( !(p[EXTRA_ALIGN+3] == MAGIC_NOR_BYTE
5545 || p[EXTRA_ALIGN+3] == MAGIC_SEC_BYTE) )
5546 membug("memory at %p corrupted: underflow=%02x (%s)\n",
5547 p+EXTRA_ALIGN+4, p[EXTRA_ALIGN+3], info );
5548 if( p[EXTRA_ALIGN+4+e->user_n] != MAGIC_END_BYTE )
5549 membug("memory at %p corrupted: overflow=%02x (%s)\n",
5550 p+EXTRA_ALIGN+4, p[EXTRA_ALIGN+4+e->user_n], info );
5551 return e;
5552 }
5553
5554
5555 /****************
5556 * free the entry and the memory (replaces free)
5557 */
5558 static void
5559 free_entry( byte *p, const char *info )
5560 {
5561 struct memtbl_entry *e, *e2;
5562
5563 check_allmem("add_entry");
5564
5565 e = check_mem(p, info);
5566 if( DBG_MEMORY )
5567 log_debug( "%s frees %u bytes alloced by %s\n",
5568 info, e->user_n, e->info->info );
5569 if( !e->inuse ) {
5570 if( e->user_p == p + EXTRA_ALIGN+ 4 )
5571 membug("freeing an already freed pointer at %p\n", p+EXTRA_ALIGN+4 );
5572 else
5573 membug("freeing pointer %p which is flagged as freed\n", p+EXTRA_ALIGN+4 );
5574 }
5575
5576 e->inuse = 0;
5577 e->next = NULL;
5578 if( !memtbl_unused )
5579 memtbl_unused = e;
5580 else {
5581 for(e2=memtbl_unused; e2->next; e2 = e2->next )
5582 ;
5583 e2->next = e;
5584 }
5585 if( m_is_secure(p+EXTRA_ALIGN+4) )
5586 secmem_free(p);
5587 else {
5588 memset(p,'f', e->user_n+5);
5589 free(p);
5590 }
5591 }
5592
5593 static void
5594 dump_entry(struct memtbl_entry *e )
5595 {
5596 unsigned n = e - memtbl;
5597
5598 fprintf(stderr, "mem %4u%c %5u %p %5u %s (%u)\n",
5599 n, e->inuse?'a':'u', e->count, e->user_p, e->user_n,
5600 e->info->info, e->info->count );
5601
5602
5603 }
5604
5605
5606 static void
5607 dump_table_at_exit( void)
5608 {
5609 if( DBG_MEMSTAT )
5610 dump_table();
5611 }
5612
5613 static void
5614 dump_table( void)
5615 {
5616 unsigned n;
5617 struct memtbl_entry *e;
5618 ulong sum = 0, chunks =0;
5619
5620 for( e = memtbl, n = 0; n < memtbl_len; n++, e++ ) {
5621 if(e->inuse) {
5622 dump_entry(e);
5623 sum += e->user_n;
5624 chunks++;
5625 }
5626 }
5627 fprintf(stderr, " memory used: %8lu bytes in %ld chunks\n",
5628 sum, chunks );
5629 }
5630
5631
5632 static void
5633 check_allmem( const char *info )
5634 {
5635 unsigned n;
5636 struct memtbl_entry *e;
5637
5638 for( e = memtbl, n = 0; n < memtbl_len; n++, e++ ) {
5639 if( e->inuse ) {
5640 #ifndef __riscos__
5641 check_mem(e->user_p-4-EXTRA_ALIGN, info);
5642 #else
5643 check_mem((const byte *) e->user_p-4-EXTRA_ALIGN, info);
5644 #endif
5645 }
5646 }
5647 }
5648
5649 #endif /* M_DEBUG */
5650
5651 #if defined(M_DEBUG) || defined(M_GUARD)
5652 static void
5653 membug( const char *fmt, ... )
5654 {
5655 va_list arg_ptr ;
5656
5657 fprintf(stderr, "\nMemory Error: " ) ;
5658 va_start( arg_ptr, fmt ) ;
5659 vfprintf(stderr,fmt,arg_ptr) ;
5660 va_end(arg_ptr);
5661 fflush(stderr);
5662 #ifdef M_DEBUG
5663 if( DBG_MEMSTAT )
5664 dump_table();
5665 #endif
5666 abort();
5667 }
5668 #endif
5669
5670 void
5671 m_print_stats( const char *prefix )
5672 {
5673 #ifdef M_DEBUG
5674 unsigned n;
5675 struct memtbl_entry *e;
5676 ulong sum = 0, chunks =0;
5677
5678 for( e = memtbl, n = 0; n < memtbl_len; n++, e++ ) {
5679 if(e->inuse) {
5680 sum += e->user_n;
5681 chunks++;
5682 }
5683 }
5684
5685 log_debug( "%s%smemstat: %8lu bytes in %ld chunks used\n",
5686 prefix? prefix:"", prefix? ": ":"", sum, chunks );
5687 #elif defined(M_GUARD)
5688 log_debug( "%s%smemstat: %8ld bytes\n",
5689 prefix? prefix:"", prefix? ": ":"", used_memory );
5690 #endif
5691 }
5692
5693 void
5694 m_dump_table( const char *prefix )
5695 {
5696 #ifdef M_DEBUG
5697 fprintf(stderr,"Memory-Table-Dump: %s\n", prefix);
5698 dump_table();
5699 #endif
5700 m_print_stats( prefix );
5701 }
5702
5703
5704 static void
5705 out_of_core(size_t n, int secure)
5706 {
5707 log_error ("out of %s memory while allocating %u bytes\n",
5708 secure? "secure":"" ,(unsigned)n );
5709 if (secure) {
5710 /*secmem_dump_stats ();*/
5711 log_info ("(this may be caused by too many secret keys used "
5712 "simultaneously or due to excessive large key sizes)\n");
5713 }
5714 #if defined(M_GUARD) && defined(__riscos__)
5715 abort();
5716 #endif
5717 exit (2);
5718 }
5719
5720 /****************
5721 * Allocate memory of size n.
5722 * This function gives up if we do not have enough memory
5723 */
5724 void *
5725 FNAMEXM(alloc)( size_t n FNAMEPRT )
5726 {
5727 char *p;
5728
5729 #ifdef M_GUARD
5730 if(!n)
5731 out_of_core(n,0); /* should never happen */
5732 if( !(p = malloc( n + EXTRA_ALIGN+5 )) )
5733 out_of_core(n,0);
5734 store_len(p,n,0);
5735 used_memory += n;
5736 p[4+EXTRA_ALIGN+n] = MAGIC_END_BYTE;
5737 return p+EXTRA_ALIGN+4;
5738 #else
5739 /* mallocing zero bytes is undefined by ISO-C, so we better make
5740 sure that it won't happen */
5741 if (!n)
5742 n = 1;
5743 if( !(p = malloc( n )) )
5744 out_of_core(n,0);
5745 return p;
5746 #endif
5747 }
5748
5749 /* Allocate memory of size n. This function returns NULL if we do not
5750 have enough memory. */
5751 void *
5752 FNAMEX(trymalloc)(size_t n FNAMEPRT)
5753 {
5754 #ifdef M_GUARD
5755 char *p;
5756
5757 if (!n)
5758 n = 1;
5759 p = malloc (n + EXTRA_ALIGN+5);
5760 if (!p)
5761 return NULL;
5762 store_len(p,n,0);
5763 used_memory += n;
5764 p[4+EXTRA_ALIGN+n] = MAGIC_END_BYTE;
5765 return p+EXTRA_ALIGN+4;
5766 #else
5767 /* Mallocing zero bytes is undefined by ISO-C, so we better make
5768 sure that it won't happen. */
5769 return malloc (n? n: 1);
5770 #endif
5771 }
5772
5773 /****************
5774 * Allocate memory of size n from the secure memory pool.
5775 * This function gives up if we do not have enough memory
5776 */
5777 void *
5778 FNAMEXM(alloc_secure)( size_t n FNAMEPRT )
5779 {
5780 char *p;
5781
5782 #ifdef M_GUARD
5783 if(!n)
5784 out_of_core(n,1); /* should never happen */
5785 if( !(p = secmem_malloc( n +EXTRA_ALIGN+ 5 )) )
5786 out_of_core(n,1);
5787 store_len(p,n,1);
5788 p[4+EXTRA_ALIGN+n] = MAGIC_END_BYTE;
5789 return p+EXTRA_ALIGN+4;
5790 #else
5791 /* mallocing zero bytes is undefined by ISO-C, so we better make
5792 sure that it won't happen */
5793 if (!n)
5794 n = 1;
5795 if( !(p = secmem_malloc( n )) )
5796 out_of_core(n,1);
5797 return p;
5798 #endif
5799 }
5800
5801 void *
5802 FNAMEXM(alloc_clear)( size_t n FNAMEPRT )
5803 {
5804 void *p;
5805 p = FNAMEXM(alloc)( n FNAMEARG );
5806 memset(p, 0, n );
5807 return p;
5808 }
5809
5810 void *
5811 FNAMEXM(alloc_secure_clear)( size_t n FNAMEPRT)
5812 {
5813 void *p;
5814 p = FNAMEXM(alloc_secure)( n FNAMEARG );
5815 memset(p, 0, n );
5816 return p;
5817 }
5818
5819
5820 /****************
5821 * realloc and clear the old space
5822 */
5823 void *
5824 FNAMEX(realloc)( void *a, size_t n FNAMEPRT )
5825 {
5826 void *b;
5827
5828 #ifdef M_GUARD
5829 if( a ) {
5830 #error "--enable-m-guard does not currently work"
5831 unsigned char *p = a;
5832 size_t len = m_size(a);
5833
5834 if( len >= n ) /* we don't shrink for now */
5835 return a;
5836 if( p[-1] == MAGIC_SEC_BYTE )
5837 b = FNAME(alloc_secure_clear)(n FNAMEARG);
5838 else
5839 b = FNAME(alloc_clear)(n FNAMEARG);
5840 FNAME(check)(NULL FNAMEARG);
5841 memcpy(b, a, len );
5842 FNAME(free)(p FNAMEARG);
5843 }
5844 else
5845 b = FNAME(alloc)(n FNAMEARG);
5846 #else
5847 if( m_is_secure(a) ) {
5848 if( !(b = secmexrealloc( a, n )) )
5849 out_of_core(n,1);
5850 }
5851 else {
5852 if( !(b = realloc( a, n )) )
5853 out_of_core(n,0);
5854 }
5855 #endif
5856
5857 return b;
5858 }
5859
5860
5861
5862 /****************
5863 * Free a pointer
5864 */
5865 void
5866 FNAMEX(free)( void *a FNAMEPRT )
5867 {
5868 byte *p = a;
5869
5870 if( !p )
5871 return;
5872 #ifdef M_DEBUG
5873 free_entry(p-EXTRA_ALIGN-4, info);
5874 #elif defined M_GUARD
5875 m_check(p);
5876 if( m_is_secure(a) )
5877 secmem_free(p-EXTRA_ALIGN-4);
5878 else {
5879 used_memory -= m_size(a);
5880 free(p-EXTRA_ALIGN-4);
5881 }
5882 #else
5883 if( m_is_secure(a) )
5884 secmem_free(p);
5885 else
5886 free(p);
5887 #endif
5888 }
5889
5890
5891 void
5892 FNAME(check)( const void *a FNAMEPRT )
5893 {
5894 #ifdef M_GUARD
5895 const byte *p = a;
5896
5897 #ifdef M_DEBUG
5898 if( p )
5899 check_mem(p-EXTRA_ALIGN-4, info);
5900 else
5901 check_allmem(info);
5902 #else
5903 if( !p )
5904 return;
5905 if( !(p[-1] == MAGIC_NOR_BYTE || p[-1] == MAGIC_SEC_BYTE) )
5906 membug("memory at %p corrupted (underflow=%02x)\n", p, p[-1] );
5907 else if( p[m_size(p)] != MAGIC_END_BYTE )
5908 membug("memory at %p corrupted (overflow=%02x)\n", p, p[-1] );
5909 #endif
5910 #endif
5911 }
5912
5913
5914 size_t
5915 m_size( const void *a )
5916 {
5917 #ifndef M_GUARD
5918 log_debug("dummy m_size called\n");
5919 return 0;
5920 #else
5921 const byte *p = a;
5922 size_t n;
5923
5924 #ifdef M_DEBUG
5925 n = check_mem(p-EXTRA_ALIGN-4, "m_size")->user_n;
5926 #else
5927 n = ((byte*)p)[-4];
5928 n |= ((byte*)p)[-3] << 8;
5929 n |= ((byte*)p)[-2] << 16;
5930 #endif
5931 return n;
5932 #endif
5933 }
5934
5935
5936 char *
5937 FNAMEX(strdup)( const char *a FNAMEPRT )
5938 {
5939 size_t n = strlen(a);
5940 char *p = FNAMEXM(alloc)(n+1 FNAMEARG);
5941 strcpy(p, a);
5942 return p;
5943 }
5944
5945 char *
5946 FNAMEX(trystrdup)(const char *a FNAMEPRT)
5947 {
5948 size_t n = strlen (a);
5949 char *p = FNAMEX(trymalloc)(n+1 FNAMEARG);
5950 if (p)
5951 strcpy (p, a);
5952 return p;
5953 }
5954
5955
5956 /* Wrapper around xmalloc_clear to take the usual 2 arguments of a
5957 calloc style function. */
5958 void *
5959 xcalloc (size_t n, size_t m)
5960 {
5961 size_t nbytes;
5962
5963 nbytes = n * m;
5964 if (m && nbytes / m != n)
5965 out_of_core (nbytes, 0);
5966 return xmalloc_clear (nbytes);
5967 }
5968
5969 /* Wrapper around xmalloc_csecure_lear to take the usual 2 arguments
5970 of a calloc style function. */
5971 void *
5972 xcalloc_secure (size_t n, size_t m)
5973 {
5974 size_t nbytes;
5975
5976 nbytes = n * m;
5977 if (m && nbytes / m != n)
5978 out_of_core (nbytes, 1);
5979 return xmalloc_secure_clear (nbytes);
5980 }
5981