Added include stdlib.h
[yaz-moved-to-github.git] / src / nmem.c
1 /*
2  * Copyright (C) 1995-2005, Index Data ApS
3  * See the file LICENSE for details.
4  *
5  * $Id: nmem.c,v 1.13 2005-01-17 13:03:27 adam Exp $
6  */
7
8 /**
9  * \file nmem.c
10  * \brief Implements Nibble Memory
11  *
12  * This is a simple and fairly wasteful little module for nibble memory
13  * allocation. Evemtually we'll put in something better.
14  *
15  * FIXME - it also has some semaphore stuff, and stuff to handle errno.
16  *         These should be moved to some other place!
17  */
18 #if HAVE_CONFIG_H
19 #include <config.h>
20 #endif
21
22 #include <assert.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <stddef.h>
27 #include <yaz/xmalloc.h>
28 #include <yaz/nmem.h>
29 #include <yaz/log.h>
30 #include <yaz/oid.h>
31
32 #ifdef WIN32
33 #include <windows.h>
34 #endif
35
36 #if YAZ_POSIX_THREADS
37 #include <pthread.h>
38 #endif
39
40 #if YAZ_GNU_THREADS
41 #include <pth.h>
42 #endif
43
44 #define NMEM_CHUNK (4*1024)
45
46 struct align {
47     char x;
48     union {
49         char c;
50         short s;
51         int i;
52         long l;
53 #if HAVE_LONG_LONG
54         long long ll;
55 #endif
56         float f;
57         double d;
58     } u;
59 };
60
61 #define NMEM_ALIGN (offsetof(struct align, u))
62
63 static int log_level=0;
64 static int log_level_initialized=0;
65
66 #ifdef WIN32
67 static CRITICAL_SECTION critical_section;
68 #define NMEM_ENTER EnterCriticalSection(&critical_section)
69 #define NMEM_LEAVE LeaveCriticalSection(&critical_section)
70 struct nmem_mutex {
71     CRITICAL_SECTION m_handle;
72 };
73 #elif YAZ_POSIX_THREADS
74 static pthread_mutex_t nmem_mutex = PTHREAD_MUTEX_INITIALIZER;
75 #define NMEM_ENTER pthread_mutex_lock(&nmem_mutex);
76 #define NMEM_LEAVE pthread_mutex_unlock(&nmem_mutex);
77 struct nmem_mutex {
78     pthread_mutex_t m_handle;
79 };
80 #elif YAZ_GNU_THREADS
81 static pth_mutex_t nmem_mutex = PTH_MUTEX_INIT;
82 #define NMEM_ENTER pth_mutex_acquire(&nmem_mutex, 0, 0)
83 #define NMEM_LEAVE pth_mutex_release(&nmem_mutex)
84 struct nmem_mutex {
85     pth_mutex_t m_handle;
86 };
87 #else
88 #define NMEM_ENTER
89 #define NMEM_LEAVE
90 struct nmem_mutex {
91     int dummy;
92 };
93 #endif
94
95 YAZ_EXPORT void nmem_mutex_create(NMEM_MUTEX *p)
96 {
97     if (!log_level_initialized)
98     {
99         log_level=yaz_log_module_level("nmem");
100         log_level_initialized=1;
101     }
102
103     NMEM_ENTER;
104     if (!*p)
105     {
106         *p = (NMEM_MUTEX) malloc (sizeof(**p));
107 #ifdef WIN32
108         InitializeCriticalSection(&(*p)->m_handle);
109 #elif YAZ_POSIX_THREADS
110         pthread_mutex_init (&(*p)->m_handle, 0);
111 #elif YAZ_GNU_THREADS
112         pth_mutex_init (&(*p)->m_handle);
113 #endif
114     }
115     NMEM_LEAVE;
116 }
117
118 YAZ_EXPORT void nmem_mutex_enter(NMEM_MUTEX p)
119 {
120     if (p)
121     {
122 #ifdef WIN32
123         EnterCriticalSection(&p->m_handle);
124 #elif YAZ_POSIX_THREADS
125         pthread_mutex_lock(&p->m_handle);
126 #endif
127     }
128 }
129
130 YAZ_EXPORT void nmem_mutex_leave(NMEM_MUTEX p)
131 {
132     if (p)
133     {
134 #ifdef WIN32
135         LeaveCriticalSection(&p->m_handle);
136 #elif YAZ_POSIX_THREADS
137         pthread_mutex_unlock(&p->m_handle);
138 #endif
139     }
140 }
141
142 YAZ_EXPORT void nmem_mutex_destroy(NMEM_MUTEX *p)
143 {
144     NMEM_ENTER;
145     if (*p)
146     {
147 #ifdef WIN32
148         DeleteCriticalSection(&(*p)->m_handle);
149 #endif
150         free (*p);
151         *p = 0;
152     }
153     NMEM_LEAVE;
154 }
155
156 static nmem_block *freelist = NULL;        /* "global" freelists */
157 static nmem_control *cfreelist = NULL;
158 static int nmem_active_no = 0;
159 static int nmem_init_flag = 0;
160
161 #if NMEM_DEBUG
162 struct nmem_debug_info {
163     void *p;
164     char file[40];
165     int line;
166     struct nmem_debug_info *next;
167 };
168   
169 struct nmem_debug_info *nmem_debug_list = 0;  
170 #endif
171
172 static void free_block(nmem_block *p)
173 {  
174     memset(p->buf, 'Y', p->size);
175     p->next = freelist;
176     freelist = p;
177     if (log_level)
178         yaz_log (log_level, "nmem free_block p=%p", p);
179 }
180
181 #if NMEM_DEBUG
182 void nmem_print_list (void)
183 {
184     if(log_level)
185         nmem_print_list_l(log_level);
186 }
187
188 void nmem_print_list_l (int level)
189 {
190     struct nmem_debug_info *p;
191
192     yaz_log (level, "nmem print list");
193     NMEM_ENTER;
194     for (p = nmem_debug_list; p; p = p->next)
195         yaz_log (level, " %s:%d p=%p size=%d", p->file, p->line, p->p,
196                  nmem_total(p->p));
197     NMEM_LEAVE;
198 }
199 #endif
200 /*
201  * acquire a block with a minimum of size free bytes.
202  */
203 static nmem_block *get_block(int size)
204 {
205     nmem_block *r, *l;
206
207     if (log_level)
208         yaz_log (log_level, "nmem get_block size=%d", size);
209
210     for (r = freelist, l = 0; r; l = r, r = r->next)
211         if (r->size >= size)
212             break;
213     if (r)
214     {
215         if (log_level)
216             yaz_log (log_level, "nmem get_block found free block p=%p", r);
217         if (l)
218             l->next = r->next;
219         else
220             freelist = r->next;
221     }
222     else
223     {
224         int get = NMEM_CHUNK;
225
226         if (get < size)
227             get = size;
228         if(log_level)
229             yaz_log (log_level, "nmem get_block alloc new block size=%d", get);
230
231         r = (nmem_block *)xmalloc(sizeof(*r));
232         r->buf = (char *)xmalloc(r->size = get);
233     }
234     r->top = 0;
235     return r;
236 }
237
238 void nmem_reset(NMEM n)
239 {
240     nmem_block *t;
241     
242     yaz_log (log_level, "nmem_reset p=%p", n);
243     if (!n)
244         return;
245     NMEM_ENTER;
246     while (n->blocks)
247     {
248         t = n->blocks;
249         n->blocks = n->blocks->next;
250         free_block(t);
251     }
252     n->total = 0;
253     NMEM_LEAVE;
254 }
255
256 #if NMEM_DEBUG
257 void *nmem_malloc_f (const char *file, int line, NMEM n, int size)
258 #else
259 void *nmem_malloc(NMEM n, int size)
260 #endif
261 {
262     struct nmem_block *p;
263     char *r;
264
265 #if NMEM_DEBUG
266     if (log_level)
267         yaz_log (log_level, "%s:%d: nmem_malloc p=%p size=%d", 
268                 file, line, n, size);
269 #endif
270     if (!n)
271     {
272         yaz_log (YLOG_FATAL, "calling nmem_malloc with an null pointer");
273         abort ();
274     }
275 #ifdef WIN32
276     assert (nmem_init_flag);
277 #endif
278     NMEM_ENTER;
279     p = n->blocks;
280     if (!p || p->size - p->top < size)
281     {
282         p = get_block(size);
283         p->next = n->blocks;
284         n->blocks = p;
285     }
286     r = p->buf + p->top;
287     /* align size */
288     p->top += (size + (NMEM_ALIGN - 1)) & ~(NMEM_ALIGN - 1);
289     n->total += size;
290     NMEM_LEAVE;
291     return r;
292 }
293
294 int nmem_total(NMEM n)
295 {
296     return n->total;
297 }
298
299 #if NMEM_DEBUG
300 NMEM nmem_create_f(const char *file, int line)
301 #else
302 NMEM nmem_create(void)
303 #endif
304 {
305     NMEM r;
306 #if NMEM_DEBUG
307     struct nmem_debug_info *debug_p;
308 #endif
309     if (!log_level_initialized)
310     {
311         log_level=yaz_log_module_level("nmem");
312         log_level_initialized=1;
313     }
314     
315     NMEM_ENTER;
316     nmem_active_no++;
317     r = cfreelist;
318     if (r)
319         cfreelist = cfreelist->next;
320     else
321         r = (nmem_control *)xmalloc(sizeof(*r));
322     NMEM_LEAVE;
323
324 #if NMEM_DEBUG
325     yaz_log (YLOG_DEBUG, "%s:%d: nmem_create %d p=%p", file, line,
326                      nmem_active_no, r);
327 #endif
328     r->blocks = 0;
329     r->total = 0;
330     r->next = 0;
331
332 #if NMEM_DEBUG
333     for (debug_p = nmem_debug_list; debug_p; debug_p = debug_p->next)
334         if (debug_p->p == r)
335         {
336             yaz_log (YLOG_FATAL, "multi used block in nmem");
337             abort ();
338         }
339     debug_p = xmalloc (sizeof(*debug_p));
340     strncpy (debug_p->file, file, sizeof(debug_p->file)-1);
341     debug_p->file[sizeof(debug_p->file)-1] = '\0';
342     debug_p->line = line;
343     debug_p->p = r;
344     debug_p->next = nmem_debug_list;
345     nmem_debug_list = debug_p;
346
347     nmem_print_list();
348 #endif
349     return r;
350 }
351
352 #if NMEM_DEBUG
353 void nmem_destroy_f(const char *file, int line, NMEM n)
354 #else
355 void nmem_destroy(NMEM n)
356 #endif
357 {
358 #if NMEM_DEBUG
359     struct nmem_debug_info **debug_p;
360     int ok = 0;
361 #endif
362     if (!n)
363         return;
364     
365 #if NMEM_DEBUG
366     yaz_log (log_level, "%s:%d: nmem_destroy %d p=%p", file, line,
367                      nmem_active_no-1, n);
368     NMEM_ENTER;
369     for (debug_p = &nmem_debug_list; *debug_p; debug_p = &(*debug_p)->next)
370         if ((*debug_p)->p == n)
371         {
372             struct nmem_debug_info *debug_save = *debug_p;
373             *debug_p = (*debug_p)->next;
374             xfree (debug_save);
375             ok = 1;
376             break;
377         }
378     NMEM_LEAVE;
379     nmem_print_list();
380     if (!ok)
381     {
382         yaz_log (YLOG_WARN, "%s:%d destroying unallocated nmem block p=%p",
383                  file, line, n);
384         return;
385     }
386 #endif
387     nmem_reset(n);
388     NMEM_ENTER;
389     nmem_active_no--;
390     n->next = cfreelist;
391     cfreelist = n;
392     NMEM_LEAVE;
393 }
394
395 void nmem_transfer (NMEM dst, NMEM src)
396 {
397     nmem_block *t;
398     while ((t = src->blocks))
399     {
400         src->blocks = t->next;
401         t->next = dst->blocks;
402         dst->blocks = t;
403     }
404     dst->total += src->total;
405     src->total = 0;
406 }
407
408 void nmem_critical_enter (void)
409 {
410     NMEM_ENTER;
411 }
412
413 void nmem_critical_leave (void)
414 {
415     NMEM_LEAVE;
416 }
417
418 void nmem_init (void)
419 {
420     if (!log_level_initialized)
421     {
422         log_level=yaz_log_module_level("nmem");
423         log_level_initialized=1;
424     }
425     
426     if (++nmem_init_flag == 1)
427     {
428 #ifdef WIN32
429         InitializeCriticalSection(&critical_section);
430 #elif YAZ_GNU_THREADS
431         yaz_log (log_level, "pth_init"); /* ??? */
432         pth_init ();
433 #endif
434         nmem_active_no = 0;
435         freelist = NULL;
436         cfreelist = NULL;
437     }
438 }
439
440 void nmem_exit (void)
441 {
442     if (--nmem_init_flag == 0)
443     {
444         oid_exit();
445         while (freelist)
446         {
447             struct nmem_block *fl = freelist;
448             freelist = freelist->next;
449             xfree (fl->buf);
450             xfree (fl);
451         }
452         while (cfreelist)
453         {
454             struct nmem_control *cfl = cfreelist;
455             cfreelist = cfreelist->next;
456             xfree (cfl);
457         }
458 #ifdef WIN32
459         DeleteCriticalSection(&critical_section);
460 #endif
461     }
462 }
463
464
465 #ifdef WIN32
466 BOOL WINAPI DllMain (HINSTANCE hinstDLL,
467                      DWORD reason,
468                      LPVOID reserved)
469 {
470     switch (reason)
471     {
472     case DLL_PROCESS_ATTACH:
473         nmem_init ();
474         break;
475     case DLL_PROCESS_DETACH:
476         nmem_exit ();
477     }
478     return TRUE;
479 }
480 #endif
481
482 int yaz_errno(void)
483 {
484     return errno;
485 }
486
487 void yaz_set_errno(int v)
488 {
489     errno = v;
490 }
491
492 void yaz_strerror(char *buf, int max)
493 {
494 #ifdef WIN32
495     DWORD err;
496 #endif
497     char *cp;
498     if (!log_level_initialized)
499     {
500         log_level = yaz_log_module_level("nmem");
501         log_level_initialized = 1;
502     }
503     
504 #ifdef WIN32
505     err = GetLastError();
506     if (err)
507     {
508         FormatMessage(
509                 FORMAT_MESSAGE_FROM_SYSTEM,
510                 NULL,
511                 err,
512                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default lang */
513                 (LPTSTR) buf,
514                 max-1,
515                 NULL);
516     }
517     else
518         *buf = '\0';
519 #else
520 /* UNIX */
521 #if HAVE_STRERROR_R
522 #if YAZ_POSIX_THREADS
523     *buf = '\0';
524     strerror_r(errno, buf, max);
525     /* if buffer is unset - use strerror anyway (GLIBC bug) */
526     if (*buf == '\0')
527         strcpy(buf, strerror(yaz_errno()));
528 #else
529     strcpy(buf, strerror(yaz_errno()));
530 #endif
531 #else
532     strcpy(buf, strerror(yaz_errno()));
533 #endif
534 /* UNIX */
535 #endif
536     if ((cp = strrchr(buf, '\n')))
537         *cp = '\0';
538     if ((cp = strrchr(buf, '\r')))
539         *cp = '\0';
540 }