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