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