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