Fix obsolete comment regarding FSM truncation.
[PostgreSQL.git] / src / interfaces / ecpg / ecpglib / memory.c
blobe831cbe35507dfa07cdfd47d48fad7639ef9e690
1 /* $PostgreSQL$ */
3 #define POSTGRES_ECPG_INTERNAL
4 #include "postgres_fe.h"
6 #include "ecpg-pthread-win32.h"
7 #include "ecpgtype.h"
8 #include "ecpglib.h"
9 #include "ecpgerrno.h"
10 #include "extern.h"
12 void
13 ecpg_free(void *ptr)
15 free(ptr);
18 char *
19 ecpg_alloc(long size, int lineno)
21 char *new = (char *) calloc(1L, size);
23 if (!new)
25 ecpg_raise(lineno, ECPG_OUT_OF_MEMORY, ECPG_SQLSTATE_ECPG_OUT_OF_MEMORY, NULL);
26 return NULL;
29 return (new);
32 char *
33 ecpg_realloc(void *ptr, long size, int lineno)
35 char *new = (char *) realloc(ptr, size);
37 if (!new)
39 ecpg_raise(lineno, ECPG_OUT_OF_MEMORY, ECPG_SQLSTATE_ECPG_OUT_OF_MEMORY, NULL);
40 return NULL;
43 return (new);
46 char *
47 ecpg_strdup(const char *string, int lineno)
49 char *new;
51 if (string == NULL)
52 return NULL;
54 new = strdup(string);
55 if (!new)
57 ecpg_raise(lineno, ECPG_OUT_OF_MEMORY, ECPG_SQLSTATE_ECPG_OUT_OF_MEMORY, NULL);
58 return NULL;
61 return (new);
64 /* keep a list of memory we allocated for the user */
65 struct auto_mem
67 void *pointer;
68 struct auto_mem *next;
71 #ifdef ENABLE_THREAD_SAFETY
72 static pthread_key_t auto_mem_key;
73 static pthread_once_t auto_mem_once = PTHREAD_ONCE_INIT;
75 static void
76 auto_mem_destructor(void *arg)
78 ECPGfree_auto_mem();
81 static void
82 auto_mem_key_init(void)
84 pthread_key_create(&auto_mem_key, auto_mem_destructor);
87 static struct auto_mem *
88 get_auto_allocs(void)
90 pthread_once(&auto_mem_once, auto_mem_key_init);
91 return (struct auto_mem *) pthread_getspecific(auto_mem_key);
94 static void
95 set_auto_allocs(struct auto_mem * am)
97 pthread_setspecific(auto_mem_key, am);
99 #else
100 static struct auto_mem *auto_allocs = NULL;
102 #define get_auto_allocs() (auto_allocs)
103 #define set_auto_allocs(am) do { auto_allocs = (am); } while(0)
104 #endif
106 void
107 ecpg_add_mem(void *ptr, int lineno)
109 struct auto_mem *am = (struct auto_mem *) ecpg_alloc(sizeof(struct auto_mem), lineno);
111 am->pointer = ptr;
112 am->next = get_auto_allocs();
113 set_auto_allocs(am);
116 void
117 ECPGfree_auto_mem(void)
119 struct auto_mem *am = get_auto_allocs();
121 /* free all memory we have allocated for the user */
122 if (am)
126 struct auto_mem *act = am;
128 am = am->next;
129 ecpg_free(act->pointer);
130 ecpg_free(act);
131 } while (am);
132 set_auto_allocs(NULL);
136 void
137 ecpg_clear_auto_mem(void)
139 struct auto_mem *am = get_auto_allocs();
141 /* only free our own structure */
142 if (am)
146 struct auto_mem *act = am;
148 am = am->next;
149 ecpg_free(act);
150 } while (am);
151 set_auto_allocs(NULL);