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