| 1 |
#include "memory.h" |
|---|
| 2 |
#include <stdlib.h> |
|---|
| 3 |
#include <string.h> |
|---|
| 4 |
#include <assert.h> |
|---|
| 5 |
|
|---|
| 6 |
#ifdef DMALLOC |
|---|
| 7 |
# include <dmalloc.h> |
|---|
| 8 |
#endif |
|---|
| 9 |
|
|---|
| 10 |
void ops_memory_init(ops_memory_t *mem,size_t initial_size) |
|---|
| 11 |
{ |
|---|
| 12 |
mem->length=0; |
|---|
| 13 |
if(mem->buf) |
|---|
| 14 |
{ |
|---|
| 15 |
if(mem->allocated < initial_size) |
|---|
| 16 |
{ |
|---|
| 17 |
mem->buf=realloc(mem->buf,initial_size); |
|---|
| 18 |
mem->allocated=initial_size; |
|---|
| 19 |
} |
|---|
| 20 |
return; |
|---|
| 21 |
} |
|---|
| 22 |
mem->buf=malloc(initial_size); |
|---|
| 23 |
mem->allocated=initial_size; |
|---|
| 24 |
} |
|---|
| 25 |
|
|---|
| 26 |
void ops_memory_pad(ops_memory_t *mem,size_t length) |
|---|
| 27 |
{ |
|---|
| 28 |
assert(mem->allocated >= mem->length); |
|---|
| 29 |
if(mem->allocated < mem->length+length) |
|---|
| 30 |
{ |
|---|
| 31 |
mem->allocated=mem->allocated*2+length; |
|---|
| 32 |
mem->buf=realloc(mem->buf,mem->allocated); |
|---|
| 33 |
} |
|---|
| 34 |
assert(mem->allocated >= mem->length+length); |
|---|
| 35 |
} |
|---|
| 36 |
|
|---|
| 37 |
void ops_memory_add(ops_memory_t *mem,const unsigned char *src,size_t length) |
|---|
| 38 |
{ |
|---|
| 39 |
ops_memory_pad(mem,length); |
|---|
| 40 |
memcpy(mem->buf+mem->length,src,length); |
|---|
| 41 |
mem->length+=length; |
|---|
| 42 |
} |
|---|
| 43 |
|
|---|
| 44 |
void ops_memory_add_int(ops_memory_t *mem,unsigned n,size_t length) |
|---|
| 45 |
{ |
|---|
| 46 |
unsigned char c[1]; |
|---|
| 47 |
|
|---|
| 48 |
while(length--) |
|---|
| 49 |
{ |
|---|
| 50 |
c[0]=n >> (length*8); |
|---|
| 51 |
ops_memory_add(mem,c,1); |
|---|
| 52 |
} |
|---|
| 53 |
} |
|---|
| 54 |
|
|---|
| 55 |
void ops_memory_add_mpi(ops_memory_t *out,const BIGNUM *bn) |
|---|
| 56 |
{ |
|---|
| 57 |
unsigned length=BN_num_bits(bn); |
|---|
| 58 |
unsigned char buf[8192]; |
|---|
| 59 |
|
|---|
| 60 |
assert(length <= 65535); |
|---|
| 61 |
BN_bn2bin(bn,buf); |
|---|
| 62 |
ops_memory_add_int(out,length,2); |
|---|
| 63 |
ops_memory_add(out,buf,(length+7)/8); |
|---|
| 64 |
} |
|---|
| 65 |
|
|---|
| 66 |
void ops_memory_release(ops_memory_t *mem) |
|---|
| 67 |
{ |
|---|
| 68 |
free(mem->buf); |
|---|
| 69 |
mem->buf=NULL; |
|---|
| 70 |
} |
|---|