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