1 /* $Id: $
2  *  Provide functions to operate with memory arrays.
3  *  Check to low memory when allocated.
4  *
5  * You should have received a copy of the GNU Lesser General Public
6  * License along with this library; see file COPYING. If not, write to the
7  * Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
8  *
9  * See also https://www.gnu.org, license may be found here.
10  */
11 
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 
16 #include "compiler.h"
17 
18 #ifndef __LITTLE_ENDIAN__
19 /*
20  *  put_dword
21  *
22  *  Writes a 4 byte word in little endian notation, independent of the local
23  *  system architecture.
24  */
put_dword(byte * ptr,dword value)25 void put_dword(byte * ptr, dword value)
26 {
27     ptr[0] = (value & 0xFF);
28     ptr[1] = (value >> 8) & 0xFF;
29     ptr[2] = (value >> 16) & 0xFF;
30     ptr[3] = (value >> 24) & 0xFF;
31 }
32 
33 /*
34  *  put_word
35  *
36  *  Writes a 4 byte word in little endian notation, independent of the local
37  *  system architecture.
38  */
put_word(byte * ptr,word value)39 void put_word(byte * ptr, word value)
40 {
41     ptr[0] = (value & 0xFF);
42     ptr[1] = (value >> 8) & 0xFF;
43 }
44 
45 #endif
46 /* safe malloc, realloc, calloc */
smalloc(size_t size)47 void * smalloc(size_t size)
48 {
49     void * ptr = (void *)malloc(size);
50 
51     if(ptr == NULL)
52     {
53         /* w_log(LL_CRIT, "out of memory"); */
54         abort();
55     }
56 
57     return ptr;
58 }
59 
srealloc(void * ptr,size_t size)60 void * srealloc(void * ptr, size_t size)
61 {
62     void * newptr = (void *)realloc(ptr, size);
63 
64     if(newptr == NULL)
65     {
66         /* w_log(LL_CRIT, "out of memory"); */
67         abort();
68     }
69 
70     return newptr;
71 }
72 
scalloc(size_t nmemb,size_t size)73 void * scalloc(size_t nmemb, size_t size)
74 {
75     void * ptr = smalloc(size * nmemb);
76 
77     memset(ptr, '\0', size * nmemb);
78     return ptr;
79 }
80 
memdup(void * p,size_t size)81 void * memdup(void * p, size_t size)
82 {
83     void * newp;
84 
85     newp = smalloc(size);
86     memcpy(newp, p, size);
87     return newp;
88 }
89