5 Author: Pekka Riikonen <priikone@silcnet.org>
7 Copyright (C) 2008 Pekka Riikonen
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; version 2 of the License.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
20 #include "silcruntime.h"
22 /****************************** Global Storage ******************************/
24 /* Set global variable */
26 void *silc_global_set_var(const char *name, SilcUInt32 variable_size,
27 void *initial_value, SilcBool in_tls)
29 SilcTls tls = silc_thread_get_tls();
34 SILC_LOG_DEBUG(("Adding %s variable '%s' of %d bytes",
35 in_tls ? "Tls" : "global", name, variable_size));
38 silc_set_errno(SILC_ERR_INVALID_ARGUMENT);
43 /* Initialize Tls for this thread */
44 tls = silc_thread_tls_init();
50 if (!tls->variables) {
51 tls->variables = silc_hash_table_alloc(NULL, 0,
52 silc_hash_string, NULL,
53 silc_hash_string_compare, NULL,
54 silc_hash_destructor, NULL,
60 if (!tls->tls_variables) {
61 tls->tls_variables = silc_hash_table_alloc(NULL, 0,
62 silc_hash_string, NULL,
63 silc_hash_string_compare, NULL,
64 silc_hash_destructor, NULL,
66 if (!tls->tls_variables)
71 /* Allocate the variable */
72 var = silc_malloc(variable_size);
76 /* Initialize the variable */
78 memcpy(var, initial_value, variable_size);
80 memset(var, 0, variable_size);
82 var_name = silc_strdup(name);
88 /* Add the variable */
90 silc_mutex_lock(tls->lock);
91 ret = silc_hash_table_set(tls->variables, var_name, var);
92 silc_mutex_unlock(tls->lock);
94 ret = silc_hash_table_set(tls->tls_variables, var_name, var);
106 /* Get global variable */
108 void *silc_global_get_var(const char *name, SilcBool in_tls)
110 SilcTls tls = silc_thread_get_tls();
114 SILC_LOG_DEBUG(("Find %s variable named '%s'", in_tls ? "Tls" : "global",
118 silc_set_errno(SILC_ERR_NOT_FOUND);
122 if (!in_tls && !tls->variables) {
123 silc_set_errno(SILC_ERR_NOT_FOUND);
127 if (in_tls && !tls->tls_variables) {
128 silc_set_errno(SILC_ERR_NOT_FOUND);
133 silc_mutex_lock(tls->lock);
134 ret = silc_hash_table_find(tls->variables, (void *)name, NULL, &variable);
135 silc_mutex_unlock(tls->lock);
137 ret = silc_hash_table_find(tls->tls_variables, (void *)name, NULL,
147 /* Delete global variable */
149 SilcBool silc_global_del_var(const char *name, SilcBool in_tls)
151 SilcTls tls = silc_thread_get_tls();
153 SILC_LOG_DEBUG(("Delete %s variable '%s'", in_tls ? "Tls" : "global", name));
156 silc_set_errno(SILC_ERR_NOT_FOUND);
160 if (!in_tls && !tls->variables) {
161 silc_set_errno(SILC_ERR_NOT_FOUND);
165 if (in_tls && !tls->tls_variables) {
166 silc_set_errno(SILC_ERR_NOT_FOUND);
170 return silc_hash_table_del(in_tls ? tls->tls_variables : tls->variables,