From 4725d7a4bc5ac1fdae3e86222cdc23eaaf6fb226 Mon Sep 17 00:00:00 2001 From: mquinson Date: Wed, 10 Sep 2008 08:52:04 +0000 Subject: [PATCH] reindent (with eclipse) git-svn-id: svn+ssh://scm.gforge.inria.fr/svn/simgrid/simgrid/trunk@5911 48e7efb5-ca39-0410-a469-dd3cf9ba447f --- src/xbt/asserts.c | 12 +- src/xbt/backtrace_linux.c | 16 +- src/xbt/backtrace_windows.c | 96 +-- src/xbt/config.c | 556 +++++++-------- src/xbt/cunit.c | 350 +++++----- src/xbt/dict.c | 478 ++++++------- src/xbt/dict_cursor.c | 16 +- src/xbt/dict_elm.c | 18 +- src/xbt/dict_multi.c | 62 +- src/xbt/dict_private.h | 6 +- src/xbt/dynar.c | 1116 +++++++++++++++---------------- src/xbt/error.c | 20 +- src/xbt/ex.c | 278 ++++---- src/xbt/fifo.c | 28 +- src/xbt/graph.c | 140 ++-- src/xbt/graphxml_parse.c | 12 +- src/xbt/heap.c | 40 +- src/xbt/log.c | 530 +++++++-------- src/xbt/log_private.h | 10 +- src/xbt/mallocator.c | 14 +- src/xbt/set.c | 98 +-- src/xbt/snprintf.c | 820 +++++++++++------------ src/xbt/swag.c | 30 +- src/xbt/xbt_context.c | 40 +- src/xbt/xbt_context_java.h | 10 +- src/xbt/xbt_context_private.h | 122 ++-- src/xbt/xbt_log_appender_file.c | 2 +- src/xbt/xbt_log_layout_format.c | 644 +++++++++--------- src/xbt/xbt_log_layout_simple.c | 94 +-- src/xbt/xbt_main.c | 26 +- src/xbt/xbt_matrix.c | 152 ++--- src/xbt/xbt_os_thread.c | 1072 ++++++++++++++--------------- src/xbt/xbt_os_time.c | 68 +- src/xbt/xbt_peer.c | 42 +- src/xbt/xbt_queue.c | 232 +++---- src/xbt/xbt_rl_synchro.c | 146 ++-- src/xbt/xbt_rl_time.c | 4 +- src/xbt/xbt_sg_stubs.c | 56 +- src/xbt/xbt_sg_synchro.c | 124 ++-- src/xbt/xbt_sg_time.c | 42 +- src/xbt/xbt_sha.c | 206 +++--- src/xbt/xbt_str.c | 216 +++--- src/xbt/xbt_virtu.c | 2 +- 43 files changed, 4023 insertions(+), 4023 deletions(-) diff --git a/src/xbt/asserts.c b/src/xbt/asserts.c index f312dda3b7..dd1a3015ff 100644 --- a/src/xbt/asserts.c +++ b/src/xbt/asserts.c @@ -12,10 +12,10 @@ XBT_LOG_EXTERNAL_CATEGORY(xbt); XBT_LOG_DEFAULT_CATEGORY(xbt); - + /** - * @brief Kill the program with an error message - * \param msg + * @brief Kill the program with an error message + * \param msg * * Things are so messed up that the only thing to do now, is to stop the program. * @@ -24,11 +24,11 @@ XBT_LOG_DEFAULT_CATEGORY(xbt); * If you want to pass arguments to the format, you can always write xbt_assert1(0,"fmt",args) */ void xbt_die (const char *msg) { - CRITICAL1("%s",msg); - xbt_abort(); + CRITICAL1("%s",msg); + xbt_abort(); } /** @brief Kill the program in silence */ void xbt_abort(void) { - abort(); + abort(); } diff --git a/src/xbt/backtrace_linux.c b/src/xbt/backtrace_linux.c index 1bec9b2223..c4ef0dceaa 100644 --- a/src/xbt/backtrace_linux.c +++ b/src/xbt/backtrace_linux.c @@ -19,7 +19,7 @@ void xbt_backtrace_current(xbt_ex_t * e) { e->used = backtrace((void **) e->bt, XBT_BACKTRACE_SIZE); } - + void xbt_ex_setup_backtrace(xbt_ex_t * e) { int i; @@ -44,12 +44,12 @@ void xbt_ex_setup_backtrace(xbt_ex_t * e) /* To search for the right executable path when not trivial */ struct stat stat_buf; char *binary_name = NULL; - + xbt_assert0(e && e->used,"Backtrace not setup yet, cannot set it up for display"); - + backtrace_syms = backtrace_symbols(e->bt, e->used); addrs = xbt_new(char *, e->used); - + e->bt_strings = NULL; /* Some arches only have stubs of backtrace, no implementation (hppa comes to mind) */ @@ -184,7 +184,7 @@ void xbt_ex_setup_backtrace(xbt_ex_t * e) if (found) { DEBUG3("%#lx in [%#lx-%#lx]", addr, first, last); DEBUG0 - ("Symbol found, map lines not further displayed (even if looking for next ones)"); + ("Symbol found, map lines not further displayed (even if looking for next ones)"); } } fclose(maps); @@ -192,13 +192,13 @@ void xbt_ex_setup_backtrace(xbt_ex_t * e) if (!found) { VERB0 - ("Problem while reading the maps file. Following backtrace will be mangled."); + ("Problem while reading the maps file. Following backtrace will be mangled."); DEBUG1("No dynamic. Static symbol: %s", backtrace_syms[i]); e->bt_strings[i] = bprintf("** In ?? (%s)", backtrace_syms[i]); continue; } - /* Ok, Found the offset of the maps line containing the searched symbol. + /* Ok, Found the offset of the maps line containing the searched symbol. We now need to substract this from the address we got from backtrace. */ @@ -206,7 +206,7 @@ void xbt_ex_setup_backtrace(xbt_ex_t * e) addrs[i] = bprintf("0x%0*lx", addr_len - 2, addr - offset); DEBUG2("offset=%#lx new addr=%s", offset, addrs[i]); - /* Got it. We have our new address. Let's get the library path and we + /* Got it. We have our new address. Let's get the library path and we are set */ p = xbt_strdup(backtrace_syms[i]); if (p[0] == '[') { diff --git a/src/xbt/backtrace_windows.c b/src/xbt/backtrace_windows.c index bfb14aa3eb..e2e60e6dd7 100644 --- a/src/xbt/backtrace_windows.c +++ b/src/xbt/backtrace_windows.c @@ -9,16 +9,16 @@ /* This program is free software; you can redistribute it and/or modify it * under the terms of the license (GNU LGPL) which comes with this package. */ -/* +/* * Win32 (x86) implementation backtrace, backtrace_symbols: * support for application self-debugging. */ #if defined(_XBT_BORLAND_COMPILER) || defined(_XBT_VISUALC_COMPILER) - /* native windows build */ +/* native windows build */ # include #else - /* gcc-based cross-compiling */ +/* gcc-based cross-compiling */ # include "xbt/wine_dbghelp.h" #endif @@ -37,8 +37,8 @@ static fun_function_table_access_t fun_function_table_access; /* SymGetLineFromAddr() */ typedef BOOL(WINAPI * fun_get_line_from_addr_t) (HANDLE, DWORD, - PDWORD, - PIMAGEHLP_LINE); + PDWORD, + PIMAGEHLP_LINE); static fun_get_line_from_addr_t fun_get_line_from_addr; /* SymGetModuleBase() */ @@ -55,16 +55,16 @@ static fun_set_options_t fun_set_options; /* Pointer function to SymGetSymFromAddr() */ typedef BOOL(WINAPI *fun_get_sym_from_addr_t) (HANDLE, DWORD, PDWORD, - OUT PIMAGEHLP_SYMBOL); + OUT PIMAGEHLP_SYMBOL); static fun_get_sym_from_addr_t fun_get_sym_from_addr; /* Pointer function to StackWalk() */ typedef BOOL(WINAPI * fun_stack_walk_t) (DWORD, HANDLE, HANDLE, - LPSTACKFRAME, PVOID, - PREAD_PROCESS_MEMORY_ROUTINE, - PFUNCTION_TABLE_ACCESS_ROUTINE, - PGET_MODULE_BASE_ROUTINE, - PTRANSLATE_ADDRESS_ROUTINE); + LPSTACKFRAME, PVOID, + PREAD_PROCESS_MEMORY_ROUTINE, + PFUNCTION_TABLE_ACCESS_ROUTINE, + PGET_MODULE_BASE_ROUTINE, + PTRANSLATE_ADDRESS_ROUTINE); static fun_stack_walk_t fun_stack_walk; static HINSTANCE hlp_dbg_instance = NULL; @@ -72,7 +72,7 @@ static HANDLE process_handle = NULL; /* Module creation/destruction: nothing to do on linux */ -void xbt_backtrace_init(void) { +void xbt_backtrace_init(void) { process_handle = GetCurrentProcess(); if (hlp_dbg_instance) { @@ -85,52 +85,52 @@ void xbt_backtrace_init(void) { if (!hlp_dbg_instance) return; - + /* get the pointers to debug help library exported functions */ - fun_initialize = - (fun_initialize_t) GetProcAddress(hlp_dbg_instance, "SymInitialize"); - fun_cleanup = - (fun_cleanup_t) GetProcAddress(hlp_dbg_instance, "SymCleanup"); - fun_function_table_access = - (fun_function_table_access_t) GetProcAddress(hlp_dbg_instance, "SymFunctionTableAccess"); - fun_get_line_from_addr = - (fun_get_line_from_addr_t) GetProcAddress(hlp_dbg_instance, "SymGetLineFromAddr"); - fun_get_module_base = - (fun_get_module_base_t) GetProcAddress(hlp_dbg_instance, "SymGetModuleBase"); - fun_get_options = - (fun_get_options_t) GetProcAddress(hlp_dbg_instance, "SymGetOptions"); - fun_get_sym_from_addr = - (fun_get_sym_from_addr_t) GetProcAddress(hlp_dbg_instance, "SymGetSymFromAddr"); - fun_set_options = - (fun_set_options_t) GetProcAddress(hlp_dbg_instance, "SymSetOptions"); - fun_stack_walk = - (fun_stack_walk_t) GetProcAddress(hlp_dbg_instance, "StackWalk"); + fun_initialize = + (fun_initialize_t) GetProcAddress(hlp_dbg_instance, "SymInitialize"); + fun_cleanup = + (fun_cleanup_t) GetProcAddress(hlp_dbg_instance, "SymCleanup"); + fun_function_table_access = + (fun_function_table_access_t) GetProcAddress(hlp_dbg_instance, "SymFunctionTableAccess"); + fun_get_line_from_addr = + (fun_get_line_from_addr_t) GetProcAddress(hlp_dbg_instance, "SymGetLineFromAddr"); + fun_get_module_base = + (fun_get_module_base_t) GetProcAddress(hlp_dbg_instance, "SymGetModuleBase"); + fun_get_options = + (fun_get_options_t) GetProcAddress(hlp_dbg_instance, "SymGetOptions"); + fun_get_sym_from_addr = + (fun_get_sym_from_addr_t) GetProcAddress(hlp_dbg_instance, "SymGetSymFromAddr"); + fun_set_options = + (fun_set_options_t) GetProcAddress(hlp_dbg_instance, "SymSetOptions"); + fun_stack_walk = + (fun_stack_walk_t) GetProcAddress(hlp_dbg_instance, "StackWalk"); /* Check that everything worked well */ if (!fun_initialize || !fun_cleanup || - !fun_function_table_access || + !fun_function_table_access || !fun_get_line_from_addr || !fun_get_module_base || !fun_get_options || !fun_get_sym_from_addr || !fun_set_options || !fun_stack_walk - ) { + ) { FreeLibrary(hlp_dbg_instance); hlp_dbg_instance = NULL; return; } (*fun_set_options) ((*fun_get_options) () | - SYMOPT_LOAD_LINES | SYMOPT_DEFERRED_LOADS); + SYMOPT_LOAD_LINES | SYMOPT_DEFERRED_LOADS); if (!(*fun_initialize) (process_handle, 0, 1)) { FreeLibrary(hlp_dbg_instance); hlp_dbg_instance = NULL; } } -void xbt_backtrace_exit(void) { +void xbt_backtrace_exit(void) { if (!hlp_dbg_instance) return; @@ -176,7 +176,7 @@ void xbt_ex_setup_backtrace(xbt_ex_t * e) char **backtrace_syms; xbt_assert0(e && e->used,"Backtrace not setup yet, cannot set it up for display"); - + backtrace_syms = backtrace_symbols(e->bt, e->used); e->bt_strings = NULL; /* parse the output and build a new backtrace */ @@ -199,8 +199,8 @@ int backtrace(void **buffer, int size) unsigned long offset = 0; IMAGEHLP_LINE line_info = { 0 }; byte - __buffer[(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR) + - sizeof(ULONG64) - 1) / sizeof(ULONG64)]; + __buffer[(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR) + + sizeof(ULONG64) - 1) / sizeof(ULONG64)]; CONTEXT context = { CONTEXT_FULL }; GetThreadContext(GetCurrentThread(), &context); @@ -213,7 +213,7 @@ int backtrace(void **buffer, int size) _asm mov eax, esp _asm mov context.Esp, eax _asm mov context.Ebp, ebp - + if ((NULL == hlp_dbg_instance) || (size <= 0) || (NULL == buffer)) { errno = EINVAL; return 0; @@ -246,13 +246,13 @@ int backtrace(void **buffer, int size) stack_frame->AddrStack.Mode = AddrModeFlat; if ((*fun_stack_walk) (IMAGE_FILE_MACHINE_I386, - process_handle, - GetCurrentThread(), - stack_frame, - &context, - NULL, - fun_function_table_access, - fun_get_module_base, NULL) + process_handle, + GetCurrentThread(), + stack_frame, + &context, + NULL, + fun_function_table_access, + fun_get_module_base, NULL) && !first) { if (stack_frame->AddrReturn.Offset) { @@ -288,8 +288,8 @@ char **backtrace_symbols(void *const *buffer, int size) IMAGEHLP_LINE line_info = { 0 }; IMAGEHLP_MODULE module = { 0 }; byte - __buffer[(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR) + - sizeof(ULONG64) - 1) / sizeof(ULONG64)]; + __buffer[(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR) + + sizeof(ULONG64) - 1) / sizeof(ULONG64)]; if ((NULL == hlp_dbg_instance) || (size <= 0) || (NULL == buffer)) { errno = EINVAL; diff --git a/src/xbt/config.c b/src/xbt/config.c index 1b13546ebf..c20d935027 100644 --- a/src/xbt/config.c +++ b/src/xbt/config.c @@ -22,7 +22,7 @@ XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_cfg,xbt,"configuration support"); -/* xbt_cfgelm_t: the typedef corresponding to a config variable. +/* xbt_cfgelm_t: the typedef corresponding to a config variable. Both data and DTD are mixed, but fixing it now would prevent me to ever defend my thesis. */ @@ -31,25 +31,25 @@ typedef struct { /* Allowed type of the variable */ e_xbt_cfgelm_type_t type; int min,max; - + /* Callbacks */ xbt_cfg_cb_t cb_set; xbt_cfg_cb_t cb_rm; - /* actual content + /* actual content (cannot be an union because type peer uses both str and i) */ xbt_dynar_t content; } s_xbt_cfgelm_t,*xbt_cfgelm_t; static const char *xbt_cfgelm_type_name[xbt_cfgelm_type_count]= - {"int","double","string","peer","any"}; +{"int","double","string","peer","any"}; /* Internal stuff used in cache to free a variable */ static void xbt_cfgelm_free(void *data); /* Retrieve the variable we'll modify */ static xbt_cfgelm_t xbt_cfgelm_get(xbt_cfg_t cfg, const char *name, - e_xbt_cfgelm_type_t type); + e_xbt_cfgelm_type_t type); /*----[ Memory management ]-----------------------------------------------*/ @@ -73,10 +73,10 @@ xbt_cfg_t xbt_cfg_new(void) { void xbt_cfg_cpy(xbt_cfg_t tocopy,xbt_cfg_t *whereto) { - xbt_dict_cursor_t cursor=NULL; + xbt_dict_cursor_t cursor=NULL; xbt_cfgelm_t variable=NULL; char *name=NULL; - + DEBUG1("Copy cfg set %p",tocopy); *whereto=NULL; xbt_assert0(tocopy,"cannot copy NULL config"); @@ -101,10 +101,10 @@ void xbt_cfg_free(xbt_cfg_t *cfg) { */ void xbt_cfg_dump(const char *name,const char *indent,xbt_cfg_t cfg) { xbt_dict_t dict = (xbt_dict_t) cfg; - xbt_dict_cursor_t cursor=NULL; + xbt_dict_cursor_t cursor=NULL; xbt_cfgelm_t variable=NULL; char *key=NULL; - int i; + int i; int size; int ival; char *sval; @@ -119,42 +119,42 @@ void xbt_cfg_dump(const char *name,const char *indent,xbt_cfg_t cfg) { size = xbt_dynar_length(variable->content); printf("%d_to_%d_%s. Actual size=%d. prerm=%p,postset=%p, List of values:\n", - variable->min,variable->max,xbt_cfgelm_type_name[variable->type], - size, + variable->min,variable->max,xbt_cfgelm_type_name[variable->type], + size, variable->cb_rm, variable->cb_set); switch (variable->type) { - - case xbt_cfgelm_int: - for (i=0; icontent,i,int); - printf ("%s %d\n",indent,ival); - } - break; - case xbt_cfgelm_double: - for (i=0; icontent,i,double); - printf ("%s %f\n",indent,dval); - } - break; + case xbt_cfgelm_int: + for (i=0; icontent,i,int); + printf ("%s %d\n",indent,ival); + } + break; - case xbt_cfgelm_string: - for (i=0; icontent,i,char*); - printf ("%s %s\n",indent,sval); - } - break; + case xbt_cfgelm_double: + for (i=0; icontent,i,double); + printf ("%s %f\n",indent,dval); + } + break; - case xbt_cfgelm_peer: - for (i=0; icontent,i,xbt_peer_t); - printf ("%s %s:%d\n",indent,hval->name,hval->port); - } - break; + case xbt_cfgelm_string: + for (i=0; icontent,i,char*); + printf ("%s %s\n",indent,sval); + } + break; - default: - printf("%s Invalid type!!\n",indent); + case xbt_cfgelm_peer: + for (i=0; icontent,i,xbt_peer_t); + printf ("%s %s:%d\n",indent,hval->name,hval->port); + } + break; + + default: + printf("%s Invalid type!!\n",indent); } } @@ -191,9 +191,9 @@ void xbt_cfgelm_free(void *data) { void xbt_cfg_register(xbt_cfg_t cfg, - const char *name, e_xbt_cfgelm_type_t type, - int min, int max, - xbt_cfg_cb_t cb_set, xbt_cfg_cb_t cb_rm){ + const char *name, e_xbt_cfgelm_type_t type, + int min, int max, + xbt_cfg_cb_t cb_set, xbt_cfg_cb_t cb_rm){ xbt_cfgelm_t res; xbt_assert(cfg); @@ -205,11 +205,11 @@ xbt_cfg_register(xbt_cfg_t cfg, if (res) { WARN1("Config elem %s registered twice.",name); /* Will be removed by the insertion of the new one */ - } + } res=xbt_new(s_xbt_cfgelm_t,1); DEBUG7("Register cfg elm %s (%d to %d %s (=%d) @%p in set %p)", - name,min,max,xbt_cfgelm_type_name[type],type,res,cfg); + name,min,max,xbt_cfgelm_type_name[type],type,res,cfg); res->type=type; res->min=min; @@ -218,34 +218,34 @@ xbt_cfg_register(xbt_cfg_t cfg, res->cb_rm = cb_rm; switch (type) { - case xbt_cfgelm_int: - res->content = xbt_dynar_new(sizeof(int), NULL); - break; + case xbt_cfgelm_int: + res->content = xbt_dynar_new(sizeof(int), NULL); + break; - case xbt_cfgelm_double: - res->content = xbt_dynar_new(sizeof(double), NULL); - break; + case xbt_cfgelm_double: + res->content = xbt_dynar_new(sizeof(double), NULL); + break; - case xbt_cfgelm_string: - res->content = xbt_dynar_new(sizeof(char*),xbt_free_ref); - break; + case xbt_cfgelm_string: + res->content = xbt_dynar_new(sizeof(char*),xbt_free_ref); + break; - case xbt_cfgelm_peer: - res->content = xbt_dynar_new(sizeof(xbt_peer_t),xbt_peer_free_voidp); - break; + case xbt_cfgelm_peer: + res->content = xbt_dynar_new(sizeof(xbt_peer_t),xbt_peer_free_voidp); + break; - default: - ERROR1("%d is an invalide type code",type); + default: + ERROR1("%d is an invalide type code",type); } - + xbt_dict_set((xbt_dict_t)cfg,name,res,&xbt_cfgelm_free); } -/** @brief Unregister an element from a config set. - * +/** @brief Unregister an element from a config set. + * * @arg cfg the config set * @arg name the name of the elem to be freed - * + * * Note that it removes both the description and the actual content. * Throws not_found when no such element exists. */ @@ -262,7 +262,7 @@ xbt_cfg_unregister(xbt_cfg_t cfg,const char *name) { * @arg cfg the config set * @arg entry a string describing the element to register * - * The string may consist in several variable descriptions separated by a space. + * The string may consist in several variable descriptions separated by a space. * Each of them must use the following syntax: \:\_to_\_\ * with type being one of 'string','int', 'peer' or 'double'. */ @@ -278,32 +278,32 @@ xbt_cfg_register_str(xbt_cfg_t cfg,const char *entry) { tok=strchr(entrycpy, ':'); xbt_assert2(tok,"Invalid config element descriptor: %s%s", - entry, - "; Should be :_to__"); + entry, + "; Should be :_to__"); *(tok++)='\0'; min=strtol(tok, &tok, 10); xbt_assert1(tok,"Invalid minimum in config element descriptor %s",entry); xbt_assert2(strcmp(tok,"_to_"), - "Invalid config element descriptor : %s%s", - entry, - "; Should be :_to__"); + "Invalid config element descriptor : %s%s", + entry, + "; Should be :_to__"); tok += strlen("_to_"); max=strtol(tok, &tok, 10); xbt_assert1(tok,"Invalid maximum in config element descriptor %s",entry); xbt_assert2( *(tok++) =='_', - "Invalid config element descriptor: %s%s",entry, - "; Should be :_to__"); + "Invalid config element descriptor: %s%s",entry, + "; Should be :_to__"); - for (type=0; - typecontent); - if (variable->min > size) { + if (variable->min > size) { xbt_dict_cursor_free(&cursor); THROW4(mismatch_error,0, - "Config elem %s needs at least %d %s, but there is only %d values.", - name, - variable->min, - xbt_cfgelm_type_name[variable->type], - size); + "Config elem %s needs at least %d %s, but there is only %d values.", + name, + variable->min, + xbt_cfgelm_type_name[variable->type], + size); } if (variable->max > 0 && variable->max < size) { xbt_dict_cursor_free(&cursor); THROW4(mismatch_error,0, - "Config elem %s accepts at most %d %s, but there is %d values.", - name, - variable->max, - xbt_cfgelm_type_name[variable->type], - size); + "Config elem %s accepts at most %d %s, but there is %d values.", + name, + variable->max, + xbt_cfgelm_type_name[variable->type], + size); } } @@ -349,20 +349,20 @@ xbt_cfg_check(xbt_cfg_t cfg) { } static xbt_cfgelm_t xbt_cfgelm_get(xbt_cfg_t cfg, - const char *name, - e_xbt_cfgelm_type_t type){ + const char *name, + e_xbt_cfgelm_type_t type){ xbt_cfgelm_t res=NULL; res = xbt_dict_get_or_null((xbt_dict_t)cfg,name); if (!res) THROW1(not_found_error,0, - "No registered variable '%s' in this config set",name); + "No registered variable '%s' in this config set",name); xbt_assert3(type == xbt_cfgelm_any || res->type == type, - "You tried to access to the config element %s as an %s, but its type is %s.", - name, - xbt_cfgelm_type_name[type], - xbt_cfgelm_type_name[res->type]); + "You tried to access to the config element %s as an %s, but its type is %s.", + name, + xbt_cfgelm_type_name[type], + xbt_cfgelm_type_name[res->type]); return res; } @@ -370,12 +370,12 @@ static xbt_cfgelm_t xbt_cfgelm_get(xbt_cfg_t cfg, /** @brief Get the type of this variable in that configuration set * * \arg cfg the config set - * \arg name the name of the element + * \arg name the name of the element * \arg type the result * */ -e_xbt_cfgelm_type_t +e_xbt_cfgelm_type_t xbt_cfg_get_type(xbt_cfg_t cfg, const char *name) { xbt_cfgelm_t variable = NULL; @@ -383,7 +383,7 @@ xbt_cfg_get_type(xbt_cfg_t cfg, const char *name) { variable = xbt_dict_get_or_null((xbt_dict_t)cfg,name); if (!variable) THROW1(not_found_error,0, - "Can't get the type of '%s' since this variable does not exist",name); + "Can't get the type of '%s' since this variable does not exist",name); INFO1("type in variable = %d",variable->type); @@ -407,7 +407,7 @@ xbt_cfg_set_vargs(xbt_cfg_t cfg, const char *name, va_list pa) { e_xbt_cfgelm_type_t type=0; /* Set a dummy value to make gcc happy. It cannot get uninitialized */ xbt_ex_t e; - + TRY { type = xbt_cfg_get_type(cfg,name); } CATCH(e) { @@ -419,29 +419,29 @@ xbt_cfg_set_vargs(xbt_cfg_t cfg, const char *name, va_list pa) { } switch (type) { - case xbt_cfgelm_peer: - str = va_arg(pa, char *); - i=va_arg(pa,int); - xbt_cfg_set_peer(cfg,name,str,i); - break; - - case xbt_cfgelm_string: - str=va_arg(pa, char *); - xbt_cfg_set_string(cfg, name, str); - break; - - case xbt_cfgelm_int: - i=va_arg(pa,int); - xbt_cfg_set_int(cfg,name,i); - break; - - case xbt_cfgelm_double: - d=va_arg(pa,double); - xbt_cfg_set_double(cfg,name,d); - break; - - default: - xbt_assert2(0,"Config element variable %s not valid (type=%d)",name,type); + case xbt_cfgelm_peer: + str = va_arg(pa, char *); + i=va_arg(pa,int); + xbt_cfg_set_peer(cfg,name,str,i); + break; + + case xbt_cfgelm_string: + str=va_arg(pa, char *); + xbt_cfg_set_string(cfg, name, str); + break; + + case xbt_cfgelm_int: + i=va_arg(pa,int); + xbt_cfg_set_int(cfg,name,i); + break; + + case xbt_cfgelm_double: + d=va_arg(pa,double); + xbt_cfg_set_double(cfg,name,d); + break; + + default: + xbt_assert2(0,"Config element variable %s not valid (type=%d)",name,type); } } @@ -465,7 +465,7 @@ void xbt_cfg_set(xbt_cfg_t cfg, const char *name, ...) { * \arg cfg config set to fill * \arg options a string containing the content to add to the config set. This * is a '\\t',' ' or '\\n' separated list of variables. Each individual variable is - * like "[name]:[value]" where [name] is the name of an already registred + * like "[name]:[value]" where [name] is the name of an already registred * variable, and [value] conforms to the data type under which this variable was * registred. * @@ -496,12 +496,12 @@ xbt_cfg_set_parse(xbt_cfg_t cfg, const char *options) { option=optionlist_cpy; while (1) { /* breaks in the code */ - if (!option) + if (!option) break; name=option; len=strlen(name); DEBUG3("Still to parse and set: '%s'. len=%d; option-name=%ld", - name,len,(long)(option-name)); + name,len,(long)(option-name)); /* Pass the value */ while (option-name<=(len-1) && *option != ' ' && *option != '\n' && *option != '\t') { @@ -514,17 +514,17 @@ xbt_cfg_set_parse(xbt_cfg_t cfg, const char *options) { } else { DEBUG3("Boundary on '%c'. len=%d;option-name=%ld", - *option,len,(long)(option-name)); + *option,len,(long)(option-name)); /* Pass the following blank chars */ *(option++)='\0'; - while (option-name<(len-1) && - (*option == ' ' || *option == '\n' || *option == '\t')) { - /* fprintf(stderr,"Ignore a blank char.\n");*/ - option++; + while (option-name<(len-1) && + (*option == ' ' || *option == '\n' || *option == '\t')) { + /* fprintf(stderr,"Ignore a blank char.\n");*/ + option++; } if (option-name == len-1) - option=NULL; /* don't do next iteration */ + option=NULL; /* don't do next iteration */ } DEBUG2("parse now:'%s'; parse later:'%s'",name,option); @@ -532,13 +532,13 @@ xbt_cfg_set_parse(xbt_cfg_t cfg, const char *options) { continue; if (!strlen(name)) break; - + val=strchr(name,':'); if (!val) { free(optionlist_cpy); xbt_assert1(FALSE, - "Option '%s' badly formated. Should be of the form 'name:value'", - name); + "Option '%s' badly formated. Should be of the form 'name:value'", + name); } *(val++)='\0'; @@ -548,69 +548,69 @@ xbt_cfg_set_parse(xbt_cfg_t cfg, const char *options) { variable = xbt_dict_get((xbt_dict_t)cfg,name); } CATCH(e) { /* put it back on what won't get freed, ie within "options" and out of "optionlist_cpy" */ - name = (char*) (optionlist_cpy-name + options); + name = (char*) (optionlist_cpy-name + options); free(optionlist_cpy); if (e.category == not_found_error) { - xbt_ex_free(e); - THROW1(not_found_error,0,"No registrated variable corresponding to '%s'.",name); + xbt_ex_free(e); + THROW1(not_found_error,0,"No registrated variable corresponding to '%s'.",name); } RETHROW; } TRY { switch (variable->type) { - case xbt_cfgelm_string: - xbt_cfg_set_string(cfg, name, val); /* throws */ - break; - - case xbt_cfgelm_int: - i=strtol(val, &val, 0); - if (val==NULL) { - free(optionlist_cpy); - xbt_assert1(FALSE, - "Value of option %s not valid. Should be an integer", - name); - } - - xbt_cfg_set_int(cfg,name,i); /* throws */ - break; - - case xbt_cfgelm_double: - d=strtod(val, &val); - if (val==NULL) { - free(optionlist_cpy); - xbt_assert1(FALSE, - "Value of option %s not valid. Should be a double", - name); - } - - xbt_cfg_set_double(cfg,name,d); /* throws */ - break; - - case xbt_cfgelm_peer: - str=val; - val=strchr(val,':'); - if (!val) { - free(optionlist_cpy); - xbt_assert1(FALSE, - "Value of option %s not valid. Should be an peer (machine:port)", - name); - } - - *(val++)='\0'; - i=strtol(val, &val, 0); - if (val==NULL) { - free(optionlist_cpy); - xbt_assert1(FALSE, - "Value of option %s not valid. Should be an peer (machine:port)", - name); - } - - xbt_cfg_set_peer(cfg,name,str,i); /* throws */ - break; - - default: - THROW1(unknown_error,0,"Type of config element %s is not valid.",name); + case xbt_cfgelm_string: + xbt_cfg_set_string(cfg, name, val); /* throws */ + break; + + case xbt_cfgelm_int: + i=strtol(val, &val, 0); + if (val==NULL) { + free(optionlist_cpy); + xbt_assert1(FALSE, + "Value of option %s not valid. Should be an integer", + name); + } + + xbt_cfg_set_int(cfg,name,i); /* throws */ + break; + + case xbt_cfgelm_double: + d=strtod(val, &val); + if (val==NULL) { + free(optionlist_cpy); + xbt_assert1(FALSE, + "Value of option %s not valid. Should be a double", + name); + } + + xbt_cfg_set_double(cfg,name,d); /* throws */ + break; + + case xbt_cfgelm_peer: + str=val; + val=strchr(val,':'); + if (!val) { + free(optionlist_cpy); + xbt_assert1(FALSE, + "Value of option %s not valid. Should be an peer (machine:port)", + name); + } + + *(val++)='\0'; + i=strtol(val, &val, 0); + if (val==NULL) { + free(optionlist_cpy); + xbt_assert1(FALSE, + "Value of option %s not valid. Should be an peer (machine:port)", + name); + } + + xbt_cfg_set_peer(cfg,name,str,i); /* throws */ + break; + + default: + THROW1(unknown_error,0,"Type of config element %s is not valid.",name); } } CATCH(e) { free(optionlist_cpy); @@ -626,7 +626,7 @@ xbt_cfg_set_parse(xbt_cfg_t cfg, const char *options) { * \arg cfg the config set * \arg name the name of the variable * \arg val the value of the variable - */ + */ void xbt_cfg_set_int(xbt_cfg_t cfg,const char*name, int val) { xbt_cfgelm_t variable; @@ -637,14 +637,14 @@ xbt_cfg_set_int(xbt_cfg_t cfg,const char*name, int val) { if (variable->max == 1) { if (variable->cb_rm && xbt_dynar_length(variable->content)) (*variable->cb_rm)(name, 0); - + xbt_dynar_set(variable->content,0,&val); } else { if (variable->max && xbt_dynar_length(variable->content) == (unsigned long)variable->max) THROW3(mismatch_error,0, "Cannot add value %d to the config element %s since it's already full (size=%d)", - val,name,variable->max); - + val,name,variable->max); + xbt_dynar_push(variable->content,&val); } @@ -653,11 +653,11 @@ xbt_cfg_set_int(xbt_cfg_t cfg,const char*name, int val) { } /** @brief Set or add a double value to \a name within \a cfg - * + * * \arg cfg the config set * \arg name the name of the variable * \arg val the doule to set - */ + */ void xbt_cfg_set_double(xbt_cfg_t cfg,const char*name, double val) { @@ -669,14 +669,14 @@ xbt_cfg_set_double(xbt_cfg_t cfg,const char*name, double val) { if (variable->max == 1) { if (variable->cb_rm && xbt_dynar_length(variable->content)) (*variable->cb_rm)(name, 0); - + xbt_dynar_set(variable->content,0,&val); } else { if (variable->max && xbt_dynar_length(variable->content) == variable->max) THROW3(mismatch_error,0, "Cannot add value %f to the config element %s since it's already full (size=%d)", - val,name,variable->max); - + val,name,variable->max); + xbt_dynar_push(variable->content,&val); } @@ -685,40 +685,40 @@ xbt_cfg_set_double(xbt_cfg_t cfg,const char*name, double val) { } /** @brief Set or add a string value to \a name within \a cfg - * + * * \arg cfg the config set * \arg name the name of the variable * \arg val the value to be added * - */ + */ void -xbt_cfg_set_string(xbt_cfg_t cfg,const char*name, const char*val) { +xbt_cfg_set_string(xbt_cfg_t cfg,const char*name, const char*val) { xbt_cfgelm_t variable; char *newval = xbt_strdup(val); VERB2("Configuration setting: %s=%s",name,val); variable = xbt_cfgelm_get(cfg,name,xbt_cfgelm_string); DEBUG5("Variable: %d to %d %s (=%d) @%p", - variable->min,variable->max,xbt_cfgelm_type_name[variable->type],variable->type,variable); + variable->min,variable->max,xbt_cfgelm_type_name[variable->type],variable->type,variable); if (variable->max == 1) { if (xbt_dynar_length(variable->content)) { - if (variable->cb_rm) - (*variable->cb_rm)(name, 0); - else if (variable->type == xbt_cfgelm_string) { - char * sval=xbt_dynar_get_as(variable->content,0,char*); - free(sval); - } + if (variable->cb_rm) + (*variable->cb_rm)(name, 0); + else if (variable->type == xbt_cfgelm_string) { + char * sval=xbt_dynar_get_as(variable->content,0,char*); + free(sval); + } } - + xbt_dynar_set(variable->content,0,&newval); } else { if (variable->max && xbt_dynar_length(variable->content) == variable->max) THROW3(mismatch_error,0, "Cannot add value %s to the config element %s since it's already full (size=%d)", - name,val,variable->max); - + name,val,variable->max); + xbt_dynar_push(variable->content,&newval); } @@ -727,18 +727,18 @@ xbt_cfg_set_string(xbt_cfg_t cfg,const char*name, const char*val) { } /** @brief Set or add an peer value to \a name within \a cfg - * + * * \arg cfg the config set * \arg name the name of the variable * \arg peer the peer * \arg port the port number * * \e peer values are composed of a string (peername) and an integer (port) - */ + */ void -xbt_cfg_set_peer(xbt_cfg_t cfg,const char*name, - const char *peer,int port) { +xbt_cfg_set_peer(xbt_cfg_t cfg,const char*name, + const char *peer,int port) { xbt_cfgelm_t variable; xbt_peer_t val=xbt_peer_new(peer,port); @@ -749,14 +749,14 @@ xbt_cfg_set_peer(xbt_cfg_t cfg,const char*name, if (variable->max == 1) { if (variable->cb_rm && xbt_dynar_length(variable->content)) (*variable->cb_rm)(name, 0); - + xbt_dynar_set(variable->content,0,&val); } else { if (variable->max && xbt_dynar_length(variable->content) == variable->max) THROW4(mismatch_error,0, "Cannot add value %s:%d to the config element %s since it's already full (size=%d)", - peer,port,name,variable->max); - + peer,port,name,variable->max); + xbt_dynar_push(variable->content,&val); } @@ -779,11 +779,11 @@ void xbt_cfg_rm_int(xbt_cfg_t cfg,const char*name, int val) { int seen; variable = xbt_cfgelm_get(cfg,name,xbt_cfgelm_int); - + if (xbt_dynar_length(variable->content) == variable->min) THROW3(mismatch_error,0, "Cannot remove value %d from the config element %s since it's already at its minimal size (=%d)", - val,name,variable->min); + val,name,variable->min); xbt_dynar_foreach(variable->content,cpt,seen) { if (seen == val) { @@ -794,7 +794,7 @@ void xbt_cfg_rm_int(xbt_cfg_t cfg,const char*name, int val) { } THROW2(not_found_error,0, - "Can't remove the value %d of config element %s: value not found.",val,name); + "Can't remove the value %d of config element %s: value not found.",val,name); } /** @brief Remove the provided \e val double value from a variable @@ -810,23 +810,23 @@ void xbt_cfg_rm_double(xbt_cfg_t cfg,const char*name, double val) { double seen; variable = xbt_cfgelm_get(cfg,name,xbt_cfgelm_double); - + if (xbt_dynar_length(variable->content) == variable->min) THROW3(mismatch_error,0, "Cannot remove value %f from the config element %s since it's already at its minimal size (=%d)", - val,name,variable->min); + val,name,variable->min); xbt_dynar_foreach(variable->content,cpt,seen) { if (seen == val) { xbt_dynar_cursor_rm(variable->content,&cpt); if (variable->cb_rm) - (*variable->cb_rm)(name, cpt); + (*variable->cb_rm)(name, cpt); return; } } THROW2(not_found_error,0, - "Can't remove the value %f of config element %s: value not found.",val,name); + "Can't remove the value %f of config element %s: value not found.",val,name); } /** @brief Remove the provided \e val string value from a variable @@ -842,27 +842,27 @@ xbt_cfg_rm_string(xbt_cfg_t cfg,const char*name, const char *val) { char *seen; variable = xbt_cfgelm_get(cfg,name,xbt_cfgelm_string); - + if (xbt_dynar_length(variable->content) == variable->min) THROW3(mismatch_error,0, "Cannot remove value %s from the config element %s since it's already at its minimal size (=%d)", - name,val,variable->min); - + name,val,variable->min); + xbt_dynar_foreach(variable->content,cpt,seen) { if (!strcpy(seen,val)) { if (variable->cb_rm) - (*variable->cb_rm)(name, cpt); + (*variable->cb_rm)(name, cpt); xbt_dynar_cursor_rm(variable->content,&cpt); return; } } THROW2(not_found_error,0, - "Can't remove the value %s of config element %s: value not found.",val,name); + "Can't remove the value %s of config element %s: value not found.",val,name); } /** @brief Remove the provided \e val peer value from a variable - * + * * \arg cfg the config set * \arg name the name of the variable * \arg peer the peername @@ -876,12 +876,12 @@ xbt_cfg_rm_peer(xbt_cfg_t cfg,const char*name, const char *peer,int port) { xbt_peer_t seen; variable = xbt_cfgelm_get(cfg,name,xbt_cfgelm_peer); - + if (xbt_dynar_length(variable->content) == variable->min) THROW4(mismatch_error,0, "Cannot remove value %s:%d from the config element %s since it's already at its minimal size (=%d)", - peer,port,name,variable->min); - + peer,port,name,variable->min); + xbt_dynar_foreach(variable->content,cpt,seen) { if (!strcpy(seen->name,peer) && seen->port == port) { if (variable->cb_rm) (*variable->cb_rm)(name, cpt); @@ -891,8 +891,8 @@ xbt_cfg_rm_peer(xbt_cfg_t cfg,const char*name, const char *peer,int port) { } THROW3(not_found_error,0, - "Can't remove the value %s:%d of config element %s: value not found.", - peer,port,name); + "Can't remove the value %s:%d of config element %s: value not found.", + peer,port,name); } /** @brief Remove the \e pos th value from the provided variable */ @@ -902,18 +902,18 @@ void xbt_cfg_rm_at (xbt_cfg_t cfg, const char *name, int pos) { xbt_cfgelm_t variable; variable = xbt_cfgelm_get(cfg,name,xbt_cfgelm_any); - + if (xbt_dynar_length(variable->content) == variable->min) THROW3(mismatch_error,0, "Cannot remove %dth value from the config element %s since it's already at its minimal size (=%d)", - pos,name,variable->min); - - if (variable->cb_rm) (*variable->cb_rm)(name, pos); + pos,name,variable->min); + + if (variable->cb_rm) (*variable->cb_rm)(name, pos); xbt_dynar_remove_at(variable->content, pos, NULL); } /** @brief Remove all the values from a variable - * + * * \arg cfg the config set * \arg name the name of the variable */ @@ -931,7 +931,7 @@ xbt_cfg_empty(xbt_cfg_t cfg,const char*name) { xbt_ex_free(e); THROW1(not_found_error,0, - "Can't empty '%s' since this config element does not exist", name); + "Can't empty '%s' since this config element does not exist", name); } if (variable) { @@ -955,31 +955,31 @@ xbt_cfg_empty(xbt_cfg_t cfg,const char*name) { * \arg val the wanted value * * Returns the first value from the config set under the given name. - * If there is more than one value, it will issue a warning. Consider using + * If there is more than one value, it will issue a warning. Consider using * xbt_cfg_get_dynar() instead. * * \warning the returned value is the actual content of the config set */ -int +int xbt_cfg_get_int (xbt_cfg_t cfg, const char *name) { xbt_cfgelm_t variable = xbt_cfgelm_get(cfg,name,xbt_cfgelm_int); if (xbt_dynar_length(variable->content) > 1) { WARN2("You asked for the first value of the config element '%s', but there is %lu values", - name, xbt_dynar_length(variable->content)); + name, xbt_dynar_length(variable->content)); } return xbt_dynar_get_as(variable->content, 0, int); } /** @brief Retrieve a double value of a variable (get a warning if not uniq) - * + * * \arg cfg the config set * \arg name the name of the variable * \arg val the wanted value * * Returns the first value from the config set under the given name. - * If there is more than one value, it will issue a warning. Consider using + * If there is more than one value, it will issue a warning. Consider using * xbt_cfg_get_dynar() instead. * * \warning the returned value is the actual content of the config set @@ -991,7 +991,7 @@ xbt_cfg_get_double(xbt_cfg_t cfg, const char *name) { if (xbt_dynar_length(variable->content) > 1) { WARN2("You asked for the first value of the config element '%s', but there is %lu values\n", - name, xbt_dynar_length(variable->content)); + name, xbt_dynar_length(variable->content)); } return xbt_dynar_get_as(variable->content, 0, double); @@ -1004,7 +1004,7 @@ xbt_cfg_get_double(xbt_cfg_t cfg, const char *name) { * \arg val the wanted value * * Returns the first value from the config set under the given name. - * If there is more than one value, it will issue a warning. Consider using + * If there is more than one value, it will issue a warning. Consider using * xbt_cfg_get_dynar() instead. * * \warning the returned value is the actual content of the config set @@ -1015,7 +1015,7 @@ char* xbt_cfg_get_string(xbt_cfg_t cfg, const char *name) { if (xbt_dynar_length(variable->content) > 1) { WARN2("You asked for the first value of the config element '%s', but there is %lu values\n", - name, xbt_dynar_length(variable->content)); + name, xbt_dynar_length(variable->content)); } return xbt_dynar_get_as(variable->content, 0, char *); @@ -1036,7 +1036,7 @@ char* xbt_cfg_get_string(xbt_cfg_t cfg, const char *name) { */ void xbt_cfg_get_peer (xbt_cfg_t cfg, const char *name, - char **peer, int *port) { + char **peer, int *port) { xbt_cfgelm_t variable; xbt_peer_t val; @@ -1044,7 +1044,7 @@ void xbt_cfg_get_peer (xbt_cfg_t cfg, const char *name, if (xbt_dynar_length(variable->content) > 1) { WARN2("You asked for the first value of the config element '%s', but there is %lu values\n", - name, xbt_dynar_length(variable->content)); + name, xbt_dynar_length(variable->content)); } val = xbt_dynar_get_as(variable->content, 0, xbt_peer_t); @@ -1053,12 +1053,12 @@ void xbt_cfg_get_peer (xbt_cfg_t cfg, const char *name, } /** @brief Retrieve the dynar of all the values stored in a variable - * + * * \arg cfg where to search in * \arg name what to search for * \arg dynar result * - * Get the data stored in the config set. + * Get the data stored in the config set. * * \warning the returned value is the actual content of the config set */ @@ -1072,7 +1072,7 @@ xbt_dynar_t xbt_cfg_get_dynar (xbt_cfg_t cfg, const char *name) { if (e.category == not_found_error) { xbt_ex_free(e); THROW1(not_found_error,0, - "No registered variable %s in this config set",name); + "No registered variable %s in this config set",name); } RETHROW; } @@ -1084,7 +1084,7 @@ xbt_dynar_t xbt_cfg_get_dynar (xbt_cfg_t cfg, const char *name) { /** @brief Retrieve one of the integer value of a variable */ int xbt_cfg_get_int_at(xbt_cfg_t cfg, const char *name, int pos) { - + xbt_cfgelm_t variable = xbt_cfgelm_get(cfg,name,xbt_cfgelm_int); return xbt_dynar_get_as(variable->content, pos, int); } @@ -1092,7 +1092,7 @@ xbt_cfg_get_int_at(xbt_cfg_t cfg, const char *name, int pos) { /** @brief Retrieve one of the double value of a variable */ double xbt_cfg_get_double_at(xbt_cfg_t cfg, const char *name, int pos) { - + xbt_cfgelm_t variable = xbt_cfgelm_get(cfg,name,xbt_cfgelm_double); return xbt_dynar_get_as(variable->content, pos, double); } @@ -1101,7 +1101,7 @@ xbt_cfg_get_double_at(xbt_cfg_t cfg, const char *name, int pos) { /** @brief Retrieve one of the string value of a variable */ char* xbt_cfg_get_string_at(xbt_cfg_t cfg, const char *name, int pos) { - + xbt_cfgelm_t variable = xbt_cfgelm_get(cfg,name,xbt_cfgelm_string); return xbt_dynar_get_as(variable->content, pos, char*); } @@ -1110,7 +1110,7 @@ xbt_cfg_get_string_at(xbt_cfg_t cfg, const char *name, int pos) { void xbt_cfg_get_peer_at(xbt_cfg_t cfg, const char *name, int pos, char **peer, int *port) { - + xbt_cfgelm_t variable = xbt_cfgelm_get(cfg,name,xbt_cfgelm_int); xbt_peer_t val = xbt_dynar_get_ptr(variable->content, pos); @@ -1126,7 +1126,7 @@ xbt_cfg_get_peer_at(xbt_cfg_t cfg, const char *name, int pos, XBT_TEST_SUITE("config","Configuration support"); static xbt_cfg_t make_set(){ - xbt_cfg_t set=NULL; + xbt_cfg_t set=NULL; set = xbt_cfg_new(); xbt_cfg_register_str(set,"speed:1_to_2_int"); @@ -1147,14 +1147,14 @@ XBT_TEST_UNIT("memuse",test_config_memuse,"Alloc and free a config set") { XBT_TEST_UNIT("validation",test_config_validation,"Validation tests") { xbt_cfg_t set = set=make_set(); xbt_ex_t e; - + xbt_test_add0("Having too few elements for speed"); xbt_cfg_set_parse(set, "peername:veloce user:mquinson\nuser:oaumage\tuser:alegrand"); TRY { xbt_cfg_check(set); } CATCH(e) { - if (e.category != mismatch_error || - strncmp(e.msg,"Config elem speed needs",strlen("Config elem speed needs"))) + if (e.category != mismatch_error || + strncmp(e.msg,"Config elem speed needs",strlen("Config elem speed needs"))) xbt_test_fail1("Got an exception. msg=%s",e.msg); xbt_ex_free(e); } @@ -1164,14 +1164,14 @@ XBT_TEST_UNIT("validation",test_config_validation,"Validation tests") { xbt_test_add0("Having too much values of 'speed'"); - set=make_set(); + set=make_set(); xbt_cfg_set_parse(set,"peername:toto:42 user:alegrand"); TRY { xbt_cfg_set_parse(set,"speed:42 speed:24 speed:34"); } CATCH(e) { if (e.category != mismatch_error || - strncmp(e.msg,"Cannot add value 34 to the config elem speed", - strlen("Config elem speed needs"))) + strncmp(e.msg,"Cannot add value 34 to the config elem speed", + strlen("Config elem speed needs"))) xbt_test_fail1("Got an exception. msg=%s",e.msg); xbt_ex_free(e); } @@ -1184,30 +1184,30 @@ XBT_TEST_UNIT("validation",test_config_validation,"Validation tests") { XBT_TEST_UNIT("use",test_config_use,"Data retrieving tests") { xbt_test_add0("Get a single value"); - { + { /* get_single_value */ int ival; xbt_cfg_t myset=make_set(); - + xbt_cfg_set_parse(myset,"peername:toto:42 speed:42"); - ival = xbt_cfg_get_int(myset,"speed"); - if (ival != 42) + ival = xbt_cfg_get_int(myset,"speed"); + if (ival != 42) xbt_test_fail1("Speed value = %d, I expected 42",ival); xbt_cfg_free(&myset); } xbt_test_add0("Get multiple values"); - { + { /* get_multiple_value */ - xbt_dynar_t dyn; + xbt_dynar_t dyn; xbt_cfg_t myset=make_set(); - + xbt_cfg_set_parse(myset, "peername:veloce user:foo\nuser:bar\tuser:toto"); xbt_cfg_set_parse(myset,"speed:42"); - xbt_cfg_check(myset); + xbt_cfg_check(myset); dyn = xbt_cfg_get_dynar(myset,"user"); - if (xbt_dynar_length(dyn) != 3) + if (xbt_dynar_length(dyn) != 3) xbt_test_fail1("Dynar length = %lu, I expected 3", xbt_dynar_length(dyn)); if (strcmp(xbt_dynar_get_as(dyn,0,char*),"foo")) @@ -1218,15 +1218,15 @@ XBT_TEST_UNIT("use",test_config_use,"Data retrieving tests") { if (strcmp(xbt_dynar_get_as(dyn,2,char*),"toto")) xbt_test_fail1("Dynar[2] = %s, I expected toto", xbt_dynar_get_as(dyn,2,char*)); - xbt_cfg_free(&myset); + xbt_cfg_free(&myset); } - + xbt_test_add0("Access to a non-existant entry"); - { + { /* non-existant_entry */ xbt_cfg_t myset=make_set(); xbt_ex_t e; - + TRY { xbt_cfg_set_parse(myset, "color:blue"); } CATCH(e) { @@ -1234,7 +1234,7 @@ XBT_TEST_UNIT("use",test_config_use,"Data retrieving tests") { xbt_test_exception(e); xbt_ex_free(e); } - xbt_cfg_free(&myset); + xbt_cfg_free(&myset); } } #endif /* SIMGRID_TEST */ diff --git a/src/xbt/cunit.c b/src/xbt/cunit.c index ac0ca354a8..5cf79168ec 100644 --- a/src/xbt/cunit.c +++ b/src/xbt/cunit.c @@ -16,7 +16,7 @@ #include "xbt/dynar.h" /* collection of all suites */ -static xbt_dynar_t _xbt_test_suites = NULL; +static xbt_dynar_t _xbt_test_suites = NULL; /* global statistics */ static int _xbt_test_nb_tests = 0; static int _xbt_test_test_failed = 0; @@ -48,7 +48,7 @@ static void xbt_test_log_dump(xbt_test_log_t log) { if (log) fprintf(stderr," log %p(%s:%d)=%s\n",log,log->file,log->line,log->text); else - fprintf(stderr," log=NULL\n"); + fprintf(stderr," log=NULL\n"); } /* test suite test check */ @@ -67,13 +67,13 @@ static void xbt_test_test_dump(xbt_test_test_t test){ xbt_test_log_t log; unsigned int it_log; fprintf(stderr," test %p(%s:%d)=%s (%s)\n", - test,test->file,test->line,test->title, - test->failed?"failed":"not failed"); + test,test->file,test->line,test->title, + test->failed?"failed":"not failed"); xbt_dynar_foreach(test->logs,it_log,log) - xbt_test_log_dump(log); + xbt_test_log_dump(log); } else - fprintf(stderr," test=NULL\n"); + fprintf(stderr," test=NULL\n"); } /* test suite test unit */ @@ -95,11 +95,11 @@ static void xbt_test_unit_dump(xbt_test_unit_t unit) { xbt_test_test_t test; unsigned int it_test; fprintf(stderr," UNIT %s: %s (%s)\n", - unit->name,unit->title, - (unit->enabled?"enabled":"disabled")); + unit->name,unit->title, + (unit->enabled?"enabled":"disabled")); if (unit->enabled) xbt_dynar_foreach(unit->tests,it_test,test) - xbt_test_test_dump(test); + xbt_test_test_dump(test); } else { fprintf(stderr," unit=NULL\n"); } @@ -129,17 +129,17 @@ static void xbt_test_suite_free(void *s) { } static void xbt_test_unit_free(void *unit) { - xbt_test_unit_t u = *(xbt_test_unit_t*)unit; - /* name is static */ - free(u->title); - xbt_dynar_free(&u->tests); - free(u); + xbt_test_unit_t u = *(xbt_test_unit_t*)unit; + /* name is static */ + free(u->title); + xbt_dynar_free(&u->tests); + free(u); } static void xbt_test_test_free(void *test) { - xbt_test_test_t t = *(xbt_test_test_t*)test; - free(t->title); - xbt_dynar_free(&(t->logs)); - free(t); + xbt_test_test_t t = *(xbt_test_test_t*)test; + free(t->title); + xbt_dynar_free(&(t->logs)); + free(t); } static void xbt_test_log_free(void *log) { xbt_test_log_t l= *(xbt_test_log_t*) log; @@ -152,7 +152,7 @@ xbt_test_suite_t xbt_test_suite_new(const char *name, const char *fmt, ...) { xbt_test_suite_t suite = xbt_new0(struct s_xbt_test_suite,1); va_list ap; - if (!_xbt_test_suites) + if (!_xbt_test_suites) _xbt_test_suites = xbt_dynar_new(sizeof(xbt_test_suite_t),xbt_test_suite_free); va_start(ap, fmt); @@ -177,15 +177,15 @@ xbt_test_suite_t xbt_test_suite_by_name(const char *name,const char *fmt, ...) { if (_xbt_test_suites) xbt_dynar_foreach(_xbt_test_suites, it_suite, suite) - if (!strcmp(suite->name,name)) - return suite; - + if (!strcmp(suite->name,name)) + return suite; + va_start(ap, fmt); vasprintf(&bufname,fmt, ap); va_end(ap); suite = xbt_test_suite_new(name,bufname,NULL); free(bufname); - + return suite; } @@ -194,11 +194,11 @@ void xbt_test_suite_dump(xbt_test_suite_t suite) { xbt_test_unit_t unit; unsigned int it_unit; fprintf(stderr,"TESTSUITE %s: %s (%s)\n", - suite->name, suite->title, - suite->enabled?"enabled":"disabled"); + suite->name, suite->title, + suite->enabled?"enabled":"disabled"); if (suite->enabled) xbt_dynar_foreach(suite->units,it_unit,unit) - xbt_test_unit_dump(unit); + xbt_test_unit_dump(unit); } else { fprintf(stderr,"TESTSUITE IS NULL!\n"); } @@ -208,7 +208,7 @@ void xbt_test_suite_dump(xbt_test_suite_t suite) { void xbt_test_suite_push(xbt_test_suite_t suite, const char *name, ts_test_cb_t func, const char *fmt, ...) { xbt_test_unit_t unit; va_list ap; - + xbt_assert(suite); xbt_assert(func); xbt_assert(fmt); @@ -223,7 +223,7 @@ void xbt_test_suite_push(xbt_test_suite_t suite, const char *name, ts_test_cb_t unit->line = 0; unit->enabled = 1; unit->tests = xbt_dynar_new(sizeof(xbt_test_test_t), xbt_test_test_free); - + xbt_dynar_push(suite->units, &unit); return; } @@ -251,8 +251,8 @@ static int xbt_test_suite_run(xbt_test_suite_t suite) { int i; xbt_assert2(suite_len<68,"suite title \"%s\" too long (%d should be less than 68", - suite->title,suite_len); - + suite->title,suite_len); + suite_title[0]=' '; for (i=1;i<79;i++) suite_title[i]='='; @@ -261,12 +261,12 @@ static int xbt_test_suite_run(xbt_test_suite_t suite) { sprintf(suite_title + 40 - (suite_len+4)/2, "[ %s ]", suite->title); suite_title[40 + (suite_len+5)/2] = '='; - if (!suite->enabled) + if (!suite->enabled) sprintf(suite_title+ 70," DISABLED "); fprintf(stderr, "\n%s\n",suite_title); } - if (suite->enabled) { + if (suite->enabled) { /* iterate through all tests */ xbt_dynar_foreach(suite->units, it_unit, unit) { /* init unit case counters */ @@ -274,97 +274,97 @@ static int xbt_test_suite_run(xbt_test_suite_t suite) { unit->test_ignore = 0; unit->test_failed = 0; unit->test_expect = 0; - + /* display unit title */ asprintf(&cp," Unit: %s ......................................" - "......................................", unit->title); + "......................................", unit->title); cp[70] = '\0'; fprintf(stderr, "%s", cp); free(cp); - + /* run the test case function */ _xbt_test_current_unit = unit; if (unit->enabled) - unit->func(); - + unit->func(); + /* iterate through all performed tests to determine status */ xbt_dynar_foreach(unit->tests,it_test, test) { - if (test->ignored) { - unit->test_ignore++; - } else { - unit->nb_tests++; - - if ( test->failed && !test->expected_failure) unit->test_failed++; - if (!test->failed && test->expected_failure) unit->test_failed++; - if (test->expected_failure) - unit->test_expect++; - } + if (test->ignored) { + unit->test_ignore++; + } else { + unit->nb_tests++; + + if ( test->failed && !test->expected_failure) unit->test_failed++; + if (!test->failed && test->expected_failure) unit->test_failed++; + if (test->expected_failure) + unit->test_expect++; + } } - - + + /* Display whether this unit went well */ if (unit->test_failed > 0 || unit->test_expect) { - /* some tests failed (or were supposed to), so do detailed reporting of test case */ - if (unit->test_failed > 0) { - fprintf(stderr, ".. failed\n"); - } else if (unit->nb_tests) { - fprintf(stderr, "...... ok\n"); /* successful, but show about expected */ - } else { - fprintf(stderr, ".... skip\n"); /* shouldn't happen, but I'm a bit lost with this logic */ - } - xbt_dynar_foreach(unit->tests,it_test, test) { - file = (test->file != NULL ? test->file : unit->file); - line = (test->line != 0 ? test->line : unit->line); - fprintf(stderr, " %s: %s [%s:%d]\n", - (test->ignored?" SKIP":(test->expected_failure?(test->failed?"EFAIL":"EPASS"): - (test->failed?" FAIL":" PASS"))), - test->title, file, line); - - if ( (test->expected_failure && !test->failed) || (!test->expected_failure && test->failed) ) { - xbt_dynar_foreach(test->logs,it_log,log) { - file = (log->file != NULL ? log->file : file); - line = (log->line != 0 ? log->line : line); - fprintf(stderr, " %s:%d: %s\n", - file, line,log->text); - - } - } - } - fprintf(stderr, " Summary: %d of %d tests failed",unit->test_failed, unit->nb_tests); - if (unit->test_ignore) { - fprintf(stderr," (%d tests ignored)\n",unit->test_ignore); - } else { - fprintf(stderr,"\n"); - } - + /* some tests failed (or were supposed to), so do detailed reporting of test case */ + if (unit->test_failed > 0) { + fprintf(stderr, ".. failed\n"); + } else if (unit->nb_tests) { + fprintf(stderr, "...... ok\n"); /* successful, but show about expected */ + } else { + fprintf(stderr, ".... skip\n"); /* shouldn't happen, but I'm a bit lost with this logic */ + } + xbt_dynar_foreach(unit->tests,it_test, test) { + file = (test->file != NULL ? test->file : unit->file); + line = (test->line != 0 ? test->line : unit->line); + fprintf(stderr, " %s: %s [%s:%d]\n", + (test->ignored?" SKIP":(test->expected_failure?(test->failed?"EFAIL":"EPASS"): + (test->failed?" FAIL":" PASS"))), + test->title, file, line); + + if ( (test->expected_failure && !test->failed) || (!test->expected_failure && test->failed) ) { + xbt_dynar_foreach(test->logs,it_log,log) { + file = (log->file != NULL ? log->file : file); + line = (log->line != 0 ? log->line : line); + fprintf(stderr, " %s:%d: %s\n", + file, line,log->text); + + } + } + } + fprintf(stderr, " Summary: %d of %d tests failed",unit->test_failed, unit->nb_tests); + if (unit->test_ignore) { + fprintf(stderr," (%d tests ignored)\n",unit->test_ignore); + } else { + fprintf(stderr,"\n"); + } + } else if (!unit->enabled) { - fprintf(stderr, " disabled\n"); /* no test were run */ + fprintf(stderr, " disabled\n"); /* no test were run */ } else if (unit->nb_tests) { - fprintf(stderr, "...... ok\n"); /* successful */ + fprintf(stderr, "...... ok\n"); /* successful */ } else { - fprintf(stderr, ".... skip\n"); /* no test were run */ + fprintf(stderr, ".... skip\n"); /* no test were run */ } - + /* Accumulate test counts into the suite */ suite->nb_tests += unit->nb_tests; suite->test_failed += unit->test_failed; suite->test_ignore += unit->test_ignore; suite->test_expect += unit->test_expect; - + _xbt_test_nb_tests += unit->nb_tests; _xbt_test_test_failed += unit->test_failed; _xbt_test_test_ignore += unit->test_ignore; - _xbt_test_test_expect += unit->test_expect; - + _xbt_test_test_expect += unit->test_expect; + /* What's the conclusion of this test anyway? */ if (unit->nb_tests) { - suite->nb_units++; - if (unit->test_failed) - suite->unit_failed++; + suite->nb_units++; + if (unit->test_failed) + suite->unit_failed++; } else if (!unit->enabled) { - suite->unit_disabled++; + suite->unit_disabled++; } else { - suite->unit_ignore++; + suite->unit_ignore++; } } } @@ -383,18 +383,18 @@ static int xbt_test_suite_run(xbt_test_suite_t suite) { _xbt_test_suite_ignore++; } - + /* print test suite summary */ if (suite->enabled) { fprintf(stderr, - " =====================================================================%s\n", - (suite->nb_units ? (suite->unit_failed ? "== FAILED":"====== OK") - : (suite->unit_disabled ? " DISABLED":"==== SKIP"))); - fprintf(stderr, " Summary: Units: %.0f%% ok (%d units: ", - suite->nb_units?((1-(double)suite->unit_failed/(double)suite->nb_units)*100.0):100.0, - suite->nb_units); - + " =====================================================================%s\n", + (suite->nb_units ? (suite->unit_failed ? "== FAILED":"====== OK") + : (suite->unit_disabled ? " DISABLED":"==== SKIP"))); + fprintf(stderr, " Summary: Units: %.0f%% ok (%d units: ", + suite->nb_units?((1-(double)suite->unit_failed/(double)suite->nb_units)*100.0):100.0, + suite->nb_units); + if (suite->nb_units != suite->unit_failed) { fprintf(stderr, "%s%d ok",(first?"":", "),suite->nb_units - suite->unit_failed); first = 0; @@ -412,8 +412,8 @@ static int xbt_test_suite_run(xbt_test_suite_t suite) { first = 0; } fprintf(stderr,")\n Tests: %.0f%% ok (%d tests: ", - suite->nb_tests?((1-(double)suite->test_failed/(double)suite->nb_tests)*100.0):100.0, - suite->nb_tests); + suite->nb_tests?((1-(double)suite->test_failed/(double)suite->nb_tests)*100.0):100.0, + suite->nb_tests); first=1; if (suite->nb_tests != suite->test_failed) { @@ -470,7 +470,7 @@ static void apply_selection(char *selection) { strcpy(dir, sel); done=1; } - + if (dir[0] == '-') { enabling = 0; memmove(dir,dir+1,strlen(dir)); @@ -482,7 +482,7 @@ static void apply_selection(char *selection) { p =strchr(dir,':'); if (p) { - strcpy(unitname,p+1); + strcpy(unitname,p+1); strncpy(suitename,dir,p-dir); suitename[p-dir]='\0'; } else { @@ -495,52 +495,52 @@ static void apply_selection(char *selection) { /* Deal with the specific case of 'all' pseudo serie */ if (!strcmp("all",suitename)) { if (unitname[0]!='\0') { - fprintf(stderr,"The 'all' pseudo-suite does not accept any unit specification\n"); - exit(1); + fprintf(stderr,"The 'all' pseudo-suite does not accept any unit specification\n"); + exit(1); } xbt_dynar_foreach(_xbt_test_suites,it_suite,suite) { - xbt_dynar_foreach(suite->units,it_unit,unit) { - unit->enabled = enabling; - } - suite->enabled = enabling; + xbt_dynar_foreach(suite->units,it_unit,unit) { + unit->enabled = enabling; + } + suite->enabled = enabling; } } else { unsigned int it; for (it=0; it< xbt_dynar_length(_xbt_test_suites); it++) { - xbt_test_suite_t thissuite=xbt_dynar_get_as(_xbt_test_suites,it,xbt_test_suite_t); - if (!strcmp(suitename,thissuite->name)) { - /* Do not disable the whole suite when we just want to disable a child */ - if (enabling || (unitname[0]=='\0')) - thissuite->enabled = enabling; - - if (unitname[0]=='\0') { - xbt_dynar_foreach(thissuite->units,it_unit,unit){ - unit->enabled = enabling; - } - } else { /* act on one child only */ - unsigned int it2_unit; - /* search it, first (we won't reuse it for external loop which gets broken) */ - for (it2_unit=0; it2_unit< xbt_dynar_length(thissuite->units); it2_unit++) { - xbt_test_unit_t thisunit=xbt_dynar_get_as(thissuite->units,it2_unit,xbt_test_unit_t); - if (!strcmp(thisunit->name,unitname)) { - thisunit->enabled = enabling; - break; - } - } /* search relevant unit */ - if (it2_unit==xbt_dynar_length(thissuite->units)) { - fprintf(stderr,"Suite '%s' has no unit of name '%s'. Cannot apply the selection\n", - suitename,unitname); - exit(1); - } - } /* act on childs (either all or one) */ - - break;/* found the relevant serie. We are happy */ - } + xbt_test_suite_t thissuite=xbt_dynar_get_as(_xbt_test_suites,it,xbt_test_suite_t); + if (!strcmp(suitename,thissuite->name)) { + /* Do not disable the whole suite when we just want to disable a child */ + if (enabling || (unitname[0]=='\0')) + thissuite->enabled = enabling; + + if (unitname[0]=='\0') { + xbt_dynar_foreach(thissuite->units,it_unit,unit){ + unit->enabled = enabling; + } + } else { /* act on one child only */ + unsigned int it2_unit; + /* search it, first (we won't reuse it for external loop which gets broken) */ + for (it2_unit=0; it2_unit< xbt_dynar_length(thissuite->units); it2_unit++) { + xbt_test_unit_t thisunit=xbt_dynar_get_as(thissuite->units,it2_unit,xbt_test_unit_t); + if (!strcmp(thisunit->name,unitname)) { + thisunit->enabled = enabling; + break; + } + } /* search relevant unit */ + if (it2_unit==xbt_dynar_length(thissuite->units)) { + fprintf(stderr,"Suite '%s' has no unit of name '%s'. Cannot apply the selection\n", + suitename,unitname); + exit(1); + } + } /* act on childs (either all or one) */ + + break;/* found the relevant serie. We are happy */ + } } /* search relevant series */ if (it==xbt_dynar_length(_xbt_test_suites)) { - fprintf(stderr,"No suite of name '%s' found. Cannot apply the selection\n",suitename); - exit(1); + fprintf(stderr,"No suite of name '%s' found. Cannot apply the selection\n",suitename); + exit(1); } } @@ -554,8 +554,8 @@ void xbt_test_dump(char *selection) { unsigned int it_suite; xbt_test_suite_t suite; - xbt_dynar_foreach(_xbt_test_suites,it_suite,suite) - xbt_test_suite_dump(suite); + xbt_dynar_foreach(_xbt_test_suites,it_suite,suite) + xbt_test_suite_dump(suite); } else { printf(" No suite defined."); } @@ -568,17 +568,17 @@ int xbt_test_run(char *selection) { unsigned int it_suite; xbt_test_suite_t suite; int first=1; - + /* Run all the suites */ - xbt_dynar_foreach(_xbt_test_suites,it_suite,suite) - xbt_test_suite_run(suite); + xbt_dynar_foreach(_xbt_test_suites,it_suite,suite) + xbt_test_suite_run(suite); /* Display some more statistics */ fprintf(stderr,"\n\n TOTAL: Suites: %.0f%% ok (%d suites: ", - _xbt_test_nb_suites - ? ((1-(double)_xbt_test_suite_failed/(double)_xbt_test_nb_suites)*100.0) - : 100.0, - _xbt_test_nb_suites); + _xbt_test_nb_suites + ? ((1-(double)_xbt_test_suite_failed/(double)_xbt_test_nb_suites)*100.0) + : 100.0, + _xbt_test_nb_suites); if (_xbt_test_nb_suites != _xbt_test_suite_failed) { fprintf(stderr, "%d ok",_xbt_test_nb_suites - _xbt_test_suite_failed); first = 0; @@ -587,14 +587,14 @@ int xbt_test_run(char *selection) { fprintf(stderr, "%s%d failed",(first?"":", "),_xbt_test_suite_failed); first = 0; } - + if (_xbt_test_suite_ignore) { fprintf(stderr, "%s%d ignored",(first?"":", "),_xbt_test_suite_ignore); first = 0; } fprintf(stderr,")\n Units: %.0f%% ok (%d units: ", - _xbt_test_nb_units?((1-(double)_xbt_test_unit_failed/(double)_xbt_test_nb_units)*100.0):100.0, - _xbt_test_nb_units); + _xbt_test_nb_units?((1-(double)_xbt_test_unit_failed/(double)_xbt_test_nb_units)*100.0):100.0, + _xbt_test_nb_units); first=1; if (_xbt_test_nb_units != _xbt_test_unit_failed) { fprintf(stderr, "%s%d ok",(first?"":", "),_xbt_test_nb_units - _xbt_test_unit_failed); @@ -609,8 +609,8 @@ int xbt_test_run(char *selection) { first = 0; } fprintf(stderr,")\n Tests: %.0f%% ok (%d tests: ", - _xbt_test_nb_tests?((1-(double)_xbt_test_test_failed/(double)_xbt_test_nb_tests)*100.0):100.0, - _xbt_test_nb_tests); + _xbt_test_nb_tests?((1-(double)_xbt_test_test_failed/(double)_xbt_test_nb_tests)*100.0):100.0, + _xbt_test_nb_tests); first=1; if (_xbt_test_nb_tests != _xbt_test_test_failed) { fprintf(stderr, "%s%d ok",(first?"":", "),_xbt_test_nb_tests - _xbt_test_test_failed); @@ -627,7 +627,7 @@ int xbt_test_run(char *selection) { if (_xbt_test_test_expect) { fprintf(stderr, "%s%d expected to fail",(first?"":", "),_xbt_test_test_expect); } - + fprintf(stderr,")\n"); } else { fprintf(stderr,"No unit to run!\n"); @@ -636,7 +636,7 @@ int xbt_test_run(char *selection) { return _xbt_test_unit_failed; } void xbt_test_exit(void) { - xbt_dynar_free(&_xbt_test_suites); + xbt_dynar_free(&_xbt_test_suites); } /* annotate test case with test */ @@ -644,7 +644,7 @@ void _xbt_test_add(const char*file,int line, const char *fmt, ...) { xbt_test_unit_t unit=_xbt_test_current_unit; xbt_test_test_t test; va_list ap; - + xbt_assert(unit); xbt_assert(fmt); @@ -668,13 +668,13 @@ void _xbt_test_fail(const char*file,int line,const char *fmt, ...) { xbt_test_test_t test; xbt_test_log_t log; va_list ap; - + xbt_assert(unit); xbt_assert(fmt); xbt_assert1(xbt_dynar_length(_xbt_test_current_unit->tests), - "Test failed even before being declared (broken unit: %s)", - unit->title); + "Test failed even before being declared (broken unit: %s)", + unit->title); log = xbt_new(struct s_xbt_test_log,1); va_start(ap, fmt); @@ -696,8 +696,8 @@ void xbt_test_exception(xbt_ex_t e) { void xbt_test_expect_failure(void) { xbt_test_test_t test; xbt_assert1(xbt_dynar_length(_xbt_test_current_unit->tests), - "Cannot expect the failure of a test before declaring it (broken unit: %s)", - _xbt_test_current_unit->title); + "Cannot expect the failure of a test before declaring it (broken unit: %s)", + _xbt_test_current_unit->title); test = xbt_dynar_getlast_as(_xbt_test_current_unit->tests,xbt_test_test_t); test->expected_failure = 1; } @@ -705,11 +705,11 @@ void xbt_test_skip(void) { xbt_test_test_t test; xbt_assert1(xbt_dynar_length(_xbt_test_current_unit->tests), - "Test skiped even before being declared (broken unit: %s)", - _xbt_test_current_unit->title); + "Test skiped even before being declared (broken unit: %s)", + _xbt_test_current_unit->title); test = xbt_dynar_getlast_as(_xbt_test_current_unit->tests, - xbt_test_test_t); + xbt_test_test_t); test->ignored = 1; } @@ -724,7 +724,7 @@ void _xbt_test_log(const char*file,int line,const char *fmt, ...) { xbt_assert(fmt); xbt_assert1(xbt_dynar_length(_xbt_test_current_unit->tests), - "Test logged into even before being declared (broken test unit: %s)",unit->title); + "Test logged into even before being declared (broken test unit: %s)",unit->title); log = xbt_new(struct s_xbt_test_log,1); va_start(ap, fmt); @@ -745,13 +745,13 @@ void _xbt_test_log(const char*file,int line,const char *fmt, ...) { XBT_TEST_SUITE("cunit","Testsuite mechanism autotest"); XBT_TEST_UNIT("expect",test_expected_failure,"expected failures") { - xbt_test_add0("Skipped test"); - xbt_test_skip(); + xbt_test_add0("Skipped test"); + xbt_test_skip(); - xbt_test_add2("%s %s","EXPECTED","FAILURE"); - xbt_test_expect_failure(); - xbt_test_log2("%s %s","Test","log"); - xbt_test_fail0("EXPECTED FAILURE"); + xbt_test_add2("%s %s","EXPECTED","FAILURE"); + xbt_test_expect_failure(); + xbt_test_log2("%s %s","Test","log"); + xbt_test_fail0("EXPECTED FAILURE"); } #endif /* SIMGRID_TEST */ diff --git a/src/xbt/dict.c b/src/xbt/dict.c index 2ddab300f2..0e02729428 100644 --- a/src/xbt/dict.c +++ b/src/xbt/dict.c @@ -19,7 +19,7 @@ #include "dict_private.h" XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_dict,xbt, - "Dictionaries provide the same functionnalities than hash tables"); + "Dictionaries provide the same functionnalities than hash tables"); /*####[ Private prototypes ]#################################################*/ static xbt_mallocator_t dict_mallocator = NULL; @@ -43,13 +43,13 @@ xbt_dict_t xbt_dict_new(void) { if (dict_mallocator == NULL) { /* first run */ dict_mallocator = xbt_mallocator_new(256, - dict_mallocator_new_f, - dict_mallocator_free_f, - dict_mallocator_reset_f); + dict_mallocator_new_f, + dict_mallocator_free_f, + dict_mallocator_reset_f); dict_elm_mallocator = xbt_mallocator_new(256, - dict_elm_mallocator_new_f, - dict_elm_mallocator_free_f, - dict_elm_mallocator_reset_f); + dict_elm_mallocator_new_f, + dict_elm_mallocator_free_f, + dict_elm_mallocator_reset_f); } dict = xbt_mallocator_get(dict_mallocator); @@ -73,7 +73,7 @@ void xbt_dict_free(xbt_dict_t *dict) { int table_size; xbt_dictelm_t *table; -// if ( *dict ) xbt_dict_dump_sizes(*dict); + // if ( *dict ) xbt_dict_dump_sizes(*dict); if (dict != NULL && *dict != NULL) { table_size = (*dict)->table_size; @@ -81,10 +81,10 @@ void xbt_dict_free(xbt_dict_t *dict) { for (i = 0; (*dict)->count && i < table_size; i++) { current = table[i]; while (current != NULL) { - previous = current; - current = current->next; - xbt_dictelm_free(previous); - (*dict)->count--; + previous = current; + current = current->next; + xbt_dictelm_free(previous); + (*dict)->count--; } } xbt_free(table); @@ -96,21 +96,21 @@ void xbt_dict_free(xbt_dict_t *dict) { /** * Returns the amount of elements in the dict */ -unsigned int xbt_dict_size(xbt_dict_t dict) { - return dict->count; +unsigned int xbt_dict_size(xbt_dict_t dict) { + return dict->count; } /** * Returns the hash code of a string. */ static XBT_INLINE unsigned int xbt_dict_hash_ext(const char *str, int str_len) { - - -#ifdef DJB2_HASH_FUNCTION + + +#ifdef DJB2_HASH_FUNCTION /* fast implementation of djb2 algorithm */ int c; register unsigned int hash = 5381; - + while (str_len--) { c = *str++; hash = ((hash << 5) + hash) + c; /* hash * 33 + c */ @@ -119,54 +119,54 @@ static XBT_INLINE unsigned int xbt_dict_hash_ext(const char *str, int str_len) { register unsigned int hash = 0x811c9dc5; unsigned char *bp = (unsigned char *)str; /* start of buffer */ unsigned char *be = bp + str_len; /* beyond end of buffer */ - + while (bp < be) { - /* multiply by the 32 bit FNV magic prime mod 2^32 */ - hash += (hash<<1) + (hash<<4) + (hash<<7) + (hash<<8) + (hash<<24); - - /* xor the bottom with the current octet */ - hash ^= (unsigned int)*bp++; + /* multiply by the 32 bit FNV magic prime mod 2^32 */ + hash += (hash<<1) + (hash<<4) + (hash<<7) + (hash<<8) + (hash<<24); + + /* xor the bottom with the current octet */ + hash ^= (unsigned int)*bp++; } -# else +# else register unsigned int hash = 0; - - while (str_len--) { - hash += (*str) * (*str); - str++; + + while (str_len--) { + hash += (*str) * (*str); + str++; } #endif - + return hash; } static XBT_INLINE unsigned int xbt_dict_hash(const char *str) { -#ifdef DJB2_HASH_FUNCTION +#ifdef DJB2_HASH_FUNCTION /* fast implementation of djb2 algorithm */ int c; register unsigned int hash = 5381; - + while ( (c = *str++) ) { hash = ((hash << 5) + hash) + c; /* hash * 33 + c */ } - + # elif defined(FNV_HASH_FUNCTION) register unsigned int hash = 0x811c9dc5; - + while (*str) { - /* multiply by the 32 bit FNV magic prime mod 2^32 */ - hash += (hash<<1) + (hash<<4) + (hash<<7) + (hash<<8) + (hash<<24); - - /* xor the bottom with the current octet */ - hash ^= (unsigned int)*str++; + /* multiply by the 32 bit FNV magic prime mod 2^32 */ + hash += (hash<<1) + (hash<<4) + (hash<<7) + (hash<<8) + (hash<<24); + + /* xor the bottom with the current octet */ + hash ^= (unsigned int)*str++; } - -# else + +# else register unsigned int hash = 0; - - while (*str) { - hash += (*str) * (*str); - str++; + + while (*str) { + hash += (*str) * (*str); + str++; } #endif return hash; @@ -174,47 +174,47 @@ static XBT_INLINE unsigned int xbt_dict_hash(const char *str) { /* Expend the size of the dict */ static void xbt_dict_rehash(xbt_dict_t dict) { - const int oldsize = dict->table_size + 1; - register int newsize = oldsize * 2; - register int i; - register xbt_dictelm_t *currcell; - register xbt_dictelm_t *twincell; - register xbt_dictelm_t bucklet; - register xbt_dictelm_t *pprev; - - currcell = (xbt_dictelm_t*) xbt_realloc((char*)dict->table, newsize * sizeof(xbt_dictelm_t)); - memset(&currcell[oldsize], 0, oldsize * sizeof(xbt_dictelm_t)); /* zero second half */ - dict->table_size = --newsize; - dict->table = currcell; - DEBUG2("REHASH (%d->%d)",oldsize,newsize); - - for (i=0; itable_size + 1; + register int newsize = oldsize * 2; + register int i; + register xbt_dictelm_t *currcell; + register xbt_dictelm_t *twincell; + register xbt_dictelm_t bucklet; + register xbt_dictelm_t *pprev; + + currcell = (xbt_dictelm_t*) xbt_realloc((char*)dict->table, newsize * sizeof(xbt_dictelm_t)); + memset(&currcell[oldsize], 0, oldsize * sizeof(xbt_dictelm_t)); /* zero second half */ + dict->table_size = --newsize; + dict->table = currcell; + DEBUG2("REHASH (%d->%d)",oldsize,newsize); + + for (i=0; ihash_code & newsize) != i) { /* Move to b */ - *pprev = bucklet->next; - bucklet->next = *twincell; - if (!*twincell) - dict->fill++; - *twincell = bucklet; - continue; - } else { - pprev = &bucklet->next; - } - + if ((bucklet->hash_code & newsize) != i) { /* Move to b */ + *pprev = bucklet->next; + bucklet->next = *twincell; + if (!*twincell) + dict->fill++; + *twincell = bucklet; + continue; + } else { + pprev = &bucklet->next; } - - if (!*currcell) /* everything moved */ - dict->fill--; - } + + } + + if (!*currcell) /* everything moved */ + dict->fill--; + } } /** @@ -223,25 +223,25 @@ static void xbt_dict_rehash(xbt_dict_t dict) { * \param key the key to set the new data * \param key_len the size of the \a key * \param data the data to add in the dict - * \param free_ctn function to call with (\a key as argument) when + * \param free_ctn function to call with (\a key as argument) when * \a key is removed from the dictionnary * - * Set the \a data in the structure under the \a key, which can be any kind + * Set the \a data in the structure under the \a key, which can be any kind * of data, as long as its length is provided in \a key_len. */ -XBT_INLINE void xbt_dict_set_ext(xbt_dict_t dict, - const char *key, int key_len, - void *data, void_f_pvoid_t free_ctn) { +XBT_INLINE void xbt_dict_set_ext(xbt_dict_t dict, + const char *key, int key_len, + void *data, void_f_pvoid_t free_ctn) { unsigned int hash_code = xbt_dict_hash_ext(key,key_len); xbt_dictelm_t current, previous = NULL; xbt_assert(dict); - + DEBUG5("ADD %.*s hash = %d, size = %d, & = %d",key_len,key,hash_code, dict->table_size, hash_code & dict->table_size); current = dict->table[hash_code & dict->table_size]; while (current != NULL && - (hash_code != current->hash_code || key_len != current->key_len || memcmp(key, current->key, key_len))) { + (hash_code != current->hash_code || key_len != current->key_len || memcmp(key, current->key, key_len))) { previous = current; current = current->next; } @@ -254,17 +254,17 @@ XBT_INLINE void xbt_dict_set_ext(xbt_dict_t dict, dict->table[hash_code & dict->table_size] = current; dict->fill++; if ((dict->fill * 100) / (dict->table_size + 1) > MAX_FILL_PERCENT) - xbt_dict_rehash(dict); + xbt_dict_rehash(dict); } else { previous->next = current; } } else { - + DEBUG6("Replace %.*s by %.*s under key %.*s", - key_len,(char*)current->content, - key_len,(char*)data, - key_len,(char*)key); + key_len,(char*)current->content, + key_len,(char*)data, + key_len,(char*)key); /* there is already an element with the same key: overwrite it */ if (current->content != NULL && current->free_f != NULL) { current->free_f(current->content); @@ -280,16 +280,16 @@ XBT_INLINE void xbt_dict_set_ext(xbt_dict_t dict, * \param dict the dict * \param key the key to set the new data * \param data the data to add in the dict - * \param free_ctn function to call with (\a key as argument) when + * \param free_ctn function to call with (\a key as argument) when * \a key is removed from the dictionnary * - * set the \a data in the structure under the \a key, which is a + * set the \a data in the structure under the \a key, which is a * null terminated string. */ void xbt_dict_set(xbt_dict_t dict, - const char *key, - void *data, - void_f_pvoid_t free_ctn) { + const char *key, + void *data, + void_f_pvoid_t free_ctn) { xbt_dict_set_ext(dict, key, strlen(key), data, free_ctn); } @@ -305,17 +305,17 @@ void xbt_dict_set(xbt_dict_t dict, * Search the given \a key. Throws not_found_error when not found. */ void *xbt_dict_get_ext(xbt_dict_t dict, - const char *key, int key_len) { + const char *key, int key_len) { unsigned int hash_code = xbt_dict_hash_ext(key,key_len); xbt_dictelm_t current; xbt_assert(dict); - + current = dict->table[hash_code & dict->table_size]; while (current != NULL && - (hash_code != current->hash_code || key_len != current->key_len || memcmp(key, current->key, key_len))) { + (hash_code != current->hash_code || key_len != current->key_len || memcmp(key, current->key, key_len))) { current = current->next; } @@ -326,18 +326,18 @@ void *xbt_dict_get_ext(xbt_dict_t dict, } /** - * \brief Retrieve data from the dict (null-terminated key) + * \brief Retrieve data from the dict (null-terminated key) * * \param dict the dealer of data * \param key the key to find data * \return the data that we are looking for * - * Search the given \a key. Throws not_found_error when not found. - * Check xbt_dict_get_or_null() for a version returning NULL without exception when + * Search the given \a key. Throws not_found_error when not found. + * Check xbt_dict_get_or_null() for a version returning NULL without exception when * not found. */ void *xbt_dict_get(xbt_dict_t dict, - const char *key) { + const char *key) { unsigned int hash_code = xbt_dict_hash(key); xbt_dictelm_t current; @@ -358,18 +358,18 @@ void *xbt_dict_get(xbt_dict_t dict, * \brief like xbt_dict_get(), but returning NULL when not found */ void *xbt_dict_get_or_null(xbt_dict_t dict, - const char *key) { + const char *key) { unsigned int hash_code = xbt_dict_hash(key); xbt_dictelm_t current; xbt_assert(dict); current = dict->table[hash_code & dict->table_size]; - while (current != NULL && - hash_code != current->hash_code && strcmp(key, current->key)) + while (current != NULL && + hash_code != current->hash_code && strcmp(key, current->key)) current = current->next; - - if (current == NULL) + + if (current == NULL) return NULL; return current->content; @@ -386,8 +386,8 @@ void *xbt_dict_get_or_null(xbt_dict_t dict, * Remove the entry associated with the given \a key (throws not_found) */ void xbt_dict_remove_ext(xbt_dict_t dict, - const char *key, - int key_len) { + const char *key, + int key_len) { unsigned int hash_code = xbt_dict_hash_ext(key,key_len); @@ -395,10 +395,10 @@ void xbt_dict_remove_ext(xbt_dict_t dict, xbt_assert(dict); -// fprintf(stderr,"RM %.*s hash = %d, size = %d, & = %d\n",key_len,key,hash_code, dict->table_size, hash_code & dict->table_size); + // fprintf(stderr,"RM %.*s hash = %d, size = %d, & = %d\n",key_len,key,hash_code, dict->table_size, hash_code & dict->table_size); current = dict->table[hash_code & dict->table_size]; while (current != NULL && - (hash_code != current->hash_code || key_len != current->key_len || strncmp(key, current->key, key_len))) { + (hash_code != current->hash_code || key_len != current->key_len || strncmp(key, current->key, key_len))) { previous = current; /* save the previous node */ current = current->next; } @@ -411,9 +411,9 @@ void xbt_dict_remove_ext(xbt_dict_t dict, } else { dict->table[hash_code & dict->table_size] = current->next; } - + if (!dict->table[hash_code & dict->table_size]) - dict->fill--; + dict->fill--; xbt_dictelm_free(current); dict->count--; @@ -441,10 +441,10 @@ void xbt_dict_reset(xbt_dict_t dict) { xbt_dictelm_t current, previous = NULL; xbt_assert(dict); - + if (dict->count == 0) return; - + for (i = 0; i <= dict->table_size; i++) { current = dict->table[i]; while (current != NULL) { @@ -470,7 +470,7 @@ int xbt_dict_length(xbt_dict_t dict) { } /** - * \brief Outputs the content of the structure (debuging purpose) + * \brief Outputs the content of the structure (debuging purpose) * * \param dict the exibitionist * \param output a function to dump each data in the tree @@ -480,7 +480,7 @@ int xbt_dict_length(xbt_dict_t dict) { */ void xbt_dict_dump(xbt_dict_t dict, - void_f_pvoid_t output) { + void_f_pvoid_t output) { int i; xbt_dictelm_t element; printf("Dict %p:\n", dict); @@ -488,18 +488,18 @@ void xbt_dict_dump(xbt_dict_t dict, for (i = 0; i < dict->table_size; i++) { element = dict->table[i]; if (element) { - printf("[\n"); - while (element != NULL) { - printf(" %s -> ", element->key); - if (output != NULL) { - (*output)(element->content); - } - printf("\n"); - element = element->next; - } - printf("]\n"); + printf("[\n"); + while (element != NULL) { + printf(" %s -> ", element->key); + if (output != NULL) { + (*output)(element->content); + } + printf("\n"); + element = element->next; + } + printf("]\n"); } else { - printf("[]\n"); + printf("[]\n"); } } } @@ -514,49 +514,49 @@ void xbt_dict_dump_sizes(xbt_dict_t dict) { unsigned int size; xbt_dictelm_t element; xbt_dynar_t sizes = xbt_dynar_new(sizeof(int),NULL); - + printf("Dict %p: %d bucklets, %d used cells (of %d) ", dict, dict->count, dict->fill,dict->table_size); if (dict != NULL) { for (i = 0; i < dict->table_size; i++) { element = dict->table[i]; size = 0; if (element) { - while (element != NULL) { - size ++; - element = element->next; - } + while (element != NULL) { + size ++; + element = element->next; + } } if (xbt_dynar_length(sizes) <= size) { - int prevsize = 1; - xbt_dynar_set(sizes,size,&prevsize); + int prevsize = 1; + xbt_dynar_set(sizes,size,&prevsize); } else { - int prevsize; - xbt_dynar_get_cpy(sizes,size,&prevsize); - prevsize++; - xbt_dynar_set(sizes,size,&prevsize); - } + int prevsize; + xbt_dynar_get_cpy(sizes,size,&prevsize); + prevsize++; + xbt_dynar_set(sizes,size,&prevsize); + } } if (!all_sizes) - all_sizes = xbt_dynar_new(sizeof(int), NULL); - + all_sizes = xbt_dynar_new(sizeof(int), NULL); + xbt_dynar_foreach(sizes,count,size) { - /* Copy values of this one into all_sizes */ - int prevcount; - if (xbt_dynar_length(all_sizes) <= count) { - prevcount = size; - xbt_dynar_set(all_sizes,count,&prevcount); - } else { - xbt_dynar_get_cpy(all_sizes,count,&prevcount); - prevcount += size; - xbt_dynar_set(all_sizes,count,&prevcount); - } - - /* Report current sizes */ - if (count==0) - continue; - if (size==0) - continue; - printf("%delm x %u cells; ",count,size); + /* Copy values of this one into all_sizes */ + int prevcount; + if (xbt_dynar_length(all_sizes) <= count) { + prevcount = size; + xbt_dynar_set(all_sizes,count,&prevcount); + } else { + xbt_dynar_get_cpy(all_sizes,count,&prevcount); + prevcount += size; + xbt_dynar_set(all_sizes,count,&prevcount); + } + + /* Report current sizes */ + if (count==0) + continue; + if (size==0) + continue; + printf("%delm x %u cells; ",count,size); } } printf("\n"); @@ -575,21 +575,21 @@ void xbt_dict_exit(void) { dict_elm_mallocator = NULL; } if (all_sizes) { - unsigned int count; - int size; - double avg = 0; - int total_count = 0; - printf("Overall stats:"); - xbt_dynar_foreach(all_sizes,count,size) { - if (count==0) - continue; - if (size==0) - continue; - printf("%delm x %d cells; ",count,size); - avg += count * size; - total_count += size; - } - printf("; %f elm per cell\n",avg/(double)total_count); + unsigned int count; + int size; + double avg = 0; + int total_count = 0; + printf("Overall stats:"); + xbt_dynar_foreach(all_sizes,count,size) { + if (count==0) + continue; + if (size==0) + continue; + printf("%delm x %d cells; ",count,size); + avg += count * size; + total_count += size; + } + printf("; %f elm per cell\n",avg/(double)total_count); } } @@ -633,7 +633,7 @@ static void debuged_add_ext(xbt_dict_t head,const char*key,const char*data_to_fi } } static void debuged_add(xbt_dict_t head,const char*key) { - debuged_add_ext(head,key,key); + debuged_add_ext(head,key,key); } static void fill(xbt_dict_t *head) { @@ -654,7 +654,7 @@ static void fill(xbt_dict_t *head) { static void search_ext(xbt_dict_t head,const char*key, const char *data) { void *found; - + xbt_test_add1("Search %s",key); found=xbt_dict_get(head,key); xbt_test_log1("Found %s",(char *)found); @@ -683,13 +683,13 @@ static void traverse(xbt_dict_t head) { int i = 0; xbt_dict_foreach(head,cursor,key,data) { - if (!key || !data || strcmp(key,data)) { - xbt_test_log3("Seen #%d: %s->%s",++i,PRINTF_STR(key),PRINTF_STR(data)); + if (!key || !data || strcmp(key,data)) { + xbt_test_log3("Seen #%d: %s->%s",++i,PRINTF_STR(key),PRINTF_STR(data)); } else { - xbt_test_log2("Seen #%d: %s",++i,PRINTF_STR(key)); + xbt_test_log2("Seen #%d: %s",++i,PRINTF_STR(key)); } xbt_test_assert2(!data || !strcmp(key,data), - "Key(%s) != value(%s). Abording",key,data); + "Key(%s) != value(%s). Abording",key,data); } } @@ -699,11 +699,11 @@ static void search_not_found(xbt_dict_t head, const char *data) { xbt_test_add1("Search %s (expected not to be found)",data); - TRY { + TRY { data = xbt_dict_get(head, data); THROW1(unknown_error,0,"Found something which shouldn't be there (%s)",data); } CATCH(e) { - if (e.category != not_found_error) + if (e.category != not_found_error) xbt_test_exception(e); xbt_ex_free(e); ok=1; @@ -720,7 +720,7 @@ static void count(xbt_dict_t dict, int length) { xbt_test_add1("Count elements (expecting %d)", length); xbt_test_assert2(xbt_dict_length(dict) == length, "Announced length(%d) != %d.", xbt_dict_length(dict), length); - + xbt_dict_foreach(dict,cursor,key,data) { effective++; } @@ -742,7 +742,7 @@ XBT_TEST_UNIT("basic",test_dict_basic,"Basic usage: change, retrieve, traverse") TRY { debuged_remove(head,"12346"); } CATCH(e) { - if (e.category != not_found_error) + if (e.category != not_found_error) xbt_test_exception(e); xbt_ex_free(e); } @@ -751,7 +751,7 @@ XBT_TEST_UNIT("basic",test_dict_basic,"Basic usage: change, retrieve, traverse") xbt_test_add0("Traverse the full dictionnary"); fill(&head); count(head, 7); - + debuged_add_ext(head,"toto","tutu"); search_ext(head,"toto","tutu"); debuged_remove(head,"toto"); @@ -784,7 +784,7 @@ XBT_TEST_UNIT("basic",test_dict_basic,"Basic usage: change, retrieve, traverse") xbt_test_add0("Traverse the resulting dictionnary"); traverse(head); - + /* RETRIEVE */ xbt_test_add0("Search 123"); data = xbt_dict_get(head,"123"); @@ -822,7 +822,7 @@ XBT_TEST_UNIT("remove",test_dict_remove,"Removing some values"){ TRY { debuged_remove(head,"Does not exist"); } CATCH(e) { - if (e.category != not_found_error) + if (e.category != not_found_error) xbt_test_exception(e); xbt_ex_free(e); } @@ -843,22 +843,22 @@ XBT_TEST_UNIT("remove",test_dict_remove,"Removing some values"){ TRY { debuged_remove(head,"12346"); } CATCH(e) { - if (e.category != not_found_error) + if (e.category != not_found_error) xbt_test_exception(e); - xbt_ex_free(e); + xbt_ex_free(e); traverse(head); - } + } debuged_remove(head,"1234"); traverse(head); debuged_remove(head,"123457"); traverse(head); debuged_remove(head,"123"); traverse(head); TRY { debuged_remove(head,"12346"); } CATCH(e) { - if (e.category != not_found_error) + if (e.category != not_found_error) xbt_test_exception(e); xbt_ex_free(e); } traverse(head); - + xbt_test_add0("Free dict, create new fresh one, and then reset the dict"); xbt_dict_free(&head); fill(&head); @@ -868,7 +868,7 @@ XBT_TEST_UNIT("remove",test_dict_remove,"Removing some values"){ xbt_test_add0("Free the dictionnary twice"); xbt_dict_free(&head); - xbt_dict_free(&head); + xbt_dict_free(&head); } XBT_TEST_UNIT("nulldata",test_dict_nulldata,"NULL data management"){ @@ -885,14 +885,14 @@ XBT_TEST_UNIT("nulldata",test_dict_nulldata,"NULL data management"){ int found=0; xbt_dict_foreach(head,cursor,key,data) { - if (!key || !data || strcmp(key,data)) { - xbt_test_log2("Seen: %s->%s",PRINTF_STR(key),PRINTF_STR(data)); + if (!key || !data || strcmp(key,data)) { + xbt_test_log2("Seen: %s->%s",PRINTF_STR(key),PRINTF_STR(data)); } else { - xbt_test_log1("Seen: %s",PRINTF_STR(key)); + xbt_test_log1("Seen: %s",PRINTF_STR(key)); } - + if (!strcmp(key,"null")) - found = 1; + found = 1; } xbt_test_assert0(found,"the key 'null', associated to NULL is not found"); } @@ -912,7 +912,7 @@ static int countelems(xbt_dict_t head) { } return res; } - + XBT_TEST_UNIT("crash",test_dict_crash,"Crash test"){ xbt_dict_t head=NULL; int i,j,k, nb; @@ -932,18 +932,18 @@ XBT_TEST_UNIT("crash",test_dict_crash,"Crash test"){ char *data = NULL; key=xbt_malloc(SIZEOFKEY); - do { - for (k=0;k0) printf("Test %d\n",i); /* else if (i%10) printf("."); else printf("%d",i/10);*/ - + for (j=0;j0) printf (" Add {"); - + for (l=0 ; l0) printf("%p=%s %s ",key, key,(l0) printf("%p=%s %s ",key, key,(l0) printf("in multitree %p.\n",mdict); - + xbt_multidict_set(mdict,keys,xbt_strdup(key),free); data = xbt_multidict_get(mdict,keys); xbt_test_assert2(data && !strcmp((char*)data,key), - "Retrieved value (%s) does not match the entrered one (%s)\n", - (char*)data,key); + "Retrieved value (%s) does not match the entrered one (%s)\n", + (char*)data,key); } xbt_dict_free(&mdict); } - + xbt_dynar_free(&keys); -/* if (verbose>0) + /* if (verbose>0) xbt_dict_dump(mdict,&xbt_dict_print);*/ - + xbt_dict_free(&mdict); xbt_dynar_free(&keys); diff --git a/src/xbt/dict_cursor.c b/src/xbt/dict_cursor.c index 4a2986b620..eb93f6928c 100644 --- a/src/xbt/dict_cursor.c +++ b/src/xbt/dict_cursor.c @@ -30,7 +30,7 @@ struct xbt_dict_cursor_ { #undef xbt_dict_CURSOR_DEBUG /*#define xbt_dict_CURSOR_DEBUG 1*/ -/** @brief Creator +/** @brief Creator * @param dict the dict */ xbt_dict_cursor_t xbt_dict_cursor_new(const xbt_dict_t dict) { @@ -84,7 +84,7 @@ void xbt_dict_cursor_rewind(xbt_dict_cursor_t cursor) { * @param[out] cursor dest address */ void xbt_dict_cursor_first(const xbt_dict_t dict, - xbt_dict_cursor_t *cursor){ + xbt_dict_cursor_t *cursor){ DEBUG0("xbt_dict_cursor_first"); if (!*cursor) { DEBUG0("Create the cursor on first use"); @@ -100,7 +100,7 @@ void xbt_dict_cursor_first(const xbt_dict_t dict, /** - * \brief Move to the next element. + * \brief Move to the next element. */ void xbt_dict_cursor_step(xbt_dict_cursor_t cursor) { @@ -121,14 +121,14 @@ void xbt_dict_cursor_step(xbt_dict_cursor_t cursor) { current = current->next; DEBUG1("next element: %p", current); } - + while (current == NULL && ++line <= cursor->dict->table_size) { DEBUG0("current is NULL, take the next line"); current = cursor->dict->table[line]; DEBUG1("element in the next line: %p", current); } DEBUG2("search finished, current = %p, line = %d", current, line); - + cursor->current = current; cursor->line = line; } @@ -140,8 +140,8 @@ void xbt_dict_cursor_step(xbt_dict_cursor_t cursor) { * @returns true if it's ok, false if there is no more data */ int xbt_dict_cursor_get_or_free(xbt_dict_cursor_t *cursor, - char **key, - void **data) { + char **key, + void **data) { xbt_dictelm_t current; @@ -156,7 +156,7 @@ int xbt_dict_cursor_get_or_free(xbt_dict_cursor_t *cursor, xbt_dict_cursor_free(cursor); return FALSE; } - + *key = current->key; *data = current->content; return TRUE; diff --git a/src/xbt/dict_elm.c b/src/xbt/dict_elm.c index eb1f890656..4cdb299b9e 100644 --- a/src/xbt/dict_elm.c +++ b/src/xbt/dict_elm.c @@ -20,34 +20,34 @@ XBT_LOG_NEW_SUBCATEGORY(xbt_dict_collapse,xbt_dict,"Dictionaries internals: post xbt_mallocator_t dict_elm_mallocator = NULL; xbt_dictelm_t xbt_dictelm_new(const char *key, - int key_len, - unsigned int hash_code, - void *content, - void_f_pvoid_t free_f) { + int key_len, + unsigned int hash_code, + void *content, + void_f_pvoid_t free_f) { xbt_dictelm_t element = xbt_mallocator_get(dict_elm_mallocator); - + element->key = xbt_new(char, key_len + 1); strncpy(element->key, key, key_len); element->key[key_len] = '\0'; element->key_len = key_len; element->hash_code = hash_code; - + element->content = content; element->free_f = free_f; element->next = NULL; - + return element; } void xbt_dictelm_free(xbt_dictelm_t element) { if (element != NULL) { xbt_free(element->key); - + if (element->free_f != NULL && element->content != NULL) { element->free_f(element->content); } - + xbt_mallocator_release(dict_elm_mallocator, element); } } diff --git a/src/xbt/dict_multi.c b/src/xbt/dict_multi.c index dc3d196fc9..10e07767da 100644 --- a/src/xbt/dict_multi.c +++ b/src/xbt/dict_multi.c @@ -31,11 +31,11 @@ void xbt_multidict_set_ext(xbt_dict_t mdict, xbt_dynar_t keys, xbt_dynar_t lens, void *data, void_f_pvoid_t free_ctn) { - + xbt_ex_t e; xbt_dict_t thislevel,nextlevel=NULL; int i; - + unsigned long int thislen; char *thiskey; int keys_len=xbt_dynar_length(keys); @@ -45,13 +45,13 @@ xbt_multidict_set_ext(xbt_dict_t mdict, DEBUG2("xbt_multidict_set(%p,%d)", mdict, keys_len); - for (i=0 , thislevel = mdict ; - i= 1, "Can't get a zero-long key set in a multidict"); - + DEBUG2("xbt_multidict_get(%p, %ld)", mdict, xbt_dynar_length(keys)); - for (i=0 , thislevel=mdict ; - i -#include "xbt/dynar_private.h" /* type definition, which we share with the +#include "xbt/dynar_private.h" /* type definition, which we share with the code in charge of sending this across the net */ -/* IMPLEMENTATION NOTE ON SYNCHRONIZATION: every functions which name is prefixed by _ - * assumes that the dynar is already locked if we have to. +/* IMPLEMENTATION NOTE ON SYNCHRONIZATION: every functions which name is prefixed by _ + * assumes that the dynar is already locked if we have to. * Other functions (public ones) check for this. */ XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_dyn,xbt,"Dynamic arrays"); #define _dynar_lock(dynar) \ - if (dynar->mutex) \ - xbt_mutex_acquire(dynar->mutex) + if (dynar->mutex) \ + xbt_mutex_acquire(dynar->mutex) #define _dynar_unlock(dynar) \ - if (dynar->mutex) \ - xbt_mutex_release(dynar->mutex) + if (dynar->mutex) \ + xbt_mutex_release(dynar->mutex) #define _sanity_check_dynar(dynar) \ - xbt_assert0(dynar, \ - "dynar is NULL") + xbt_assert0(dynar, \ + "dynar is NULL") #define _sanity_check_idx(idx) \ - xbt_assert1(idx >= 0, \ - "dynar idx(=%d) < 0", \ - (int) (idx)) + xbt_assert1(idx >= 0, \ + "dynar idx(=%d) < 0", \ + (int) (idx)) #define _check_inbound_idx(dynar, idx) \ - if (idx>=dynar->used) \ - THROW2(bound_error,idx, \ - "dynar is not that long. You asked %d, but it's only %lu long", \ - (int) (idx), (unsigned long) dynar->used) + if (idx>=dynar->used) \ + THROW2(bound_error,idx, \ + "dynar is not that long. You asked %d, but it's only %lu long", \ + (int) (idx), (unsigned long) dynar->used) #define _check_sloppy_inbound_idx(dynar, idx) \ - if (idx>dynar->used) \ - THROW2(bound_error,idx, \ - "dynar is not that long. You asked %d, but it's only %lu long (could have been equal to it)", \ - (int) (idx), (unsigned long) dynar->used) + if (idx>dynar->used) \ + THROW2(bound_error,idx, \ + "dynar is not that long. You asked %d, but it's only %lu long (could have been equal to it)", \ + (int) (idx), (unsigned long) dynar->used) #define _check_populated_dynar(dynar) \ - if (dynar->used == 0) \ - THROW1(bound_error,0, \ - "dynar %p is empty", dynar) + if (dynar->used == 0) \ + THROW1(bound_error,0, \ + "dynar %p is empty", dynar) static void _dynar_map(const xbt_dynar_t dynar, - void_f_pvoid_t const op); + void_f_pvoid_t const op); -static XBT_INLINE +static XBT_INLINE void _xbt_clear_mem(void * const ptr, - const unsigned long length) { + const unsigned long length) { memset(ptr, 0, length); } static XBT_INLINE void _xbt_dynar_expand(xbt_dynar_t const dynar, - const unsigned long nb) { + const unsigned long nb) { const unsigned long old_size = dynar->size; if (nb > old_size) { @@ -99,7 +99,7 @@ _xbt_dynar_expand(xbt_dynar_t const dynar, static XBT_INLINE void * _xbt_dynar_elm(const xbt_dynar_t dynar, - const unsigned long idx) { + const unsigned long idx) { char * const data = (char*) dynar->data; const unsigned long elmsize = dynar->elmsize; @@ -109,8 +109,8 @@ _xbt_dynar_elm(const xbt_dynar_t dynar, static XBT_INLINE void _xbt_dynar_get_elm(void * const dst, - const xbt_dynar_t dynar, - const unsigned long idx) { + const xbt_dynar_t dynar, + const unsigned long idx) { void * const elm = _xbt_dynar_elm(dynar, idx); memcpy(dst, elm, dynar->elmsize); @@ -119,15 +119,15 @@ _xbt_dynar_get_elm(void * const dst, static XBT_INLINE void _xbt_dynar_put_elm(const xbt_dynar_t dynar, - const unsigned long idx, - const void * const src) { + const unsigned long idx, + const void * const src) { void * const elm = _xbt_dynar_elm(dynar, idx); const unsigned long elmsize = dynar->elmsize; memcpy(elm, src, elmsize); } -static XBT_INLINE +static XBT_INLINE void _xbt_dynar_remove_at(xbt_dynar_t const dynar, const unsigned long idx, @@ -144,14 +144,14 @@ _xbt_dynar_remove_at(xbt_dynar_t const dynar, _xbt_dynar_get_elm(object, dynar, idx); } else if (dynar->free_f) { if (dynar->elmsize <= SIZEOF_MAX) { - char elm[SIZEOF_MAX]; - _xbt_dynar_get_elm(elm, dynar, idx); - (*dynar->free_f)(elm); + char elm[SIZEOF_MAX]; + _xbt_dynar_get_elm(elm, dynar, idx); + (*dynar->free_f)(elm); } else { - char *elm=malloc(dynar->elmsize); - _xbt_dynar_get_elm(elm, dynar, idx); - (*dynar->free_f)(elm); - free(elm); + char *elm=malloc(dynar->elmsize); + _xbt_dynar_get_elm(elm, dynar, idx); + (*dynar->free_f)(elm); + free(elm); } } @@ -159,7 +159,7 @@ _xbt_dynar_remove_at(xbt_dynar_t const dynar, offset = nb_shift * dynar->elmsize; memmove(_xbt_dynar_elm(dynar, idx), - _xbt_dynar_elm(dynar, idx+1), + _xbt_dynar_elm(dynar, idx+1), offset); dynar->used--; @@ -168,11 +168,11 @@ _xbt_dynar_remove_at(xbt_dynar_t const dynar, void xbt_dynar_dump(xbt_dynar_t dynar) { INFO5("Dynar dump: size=%lu; used=%lu; elmsize=%lu; data=%p; free_f=%p", - dynar->size, dynar->used, dynar->elmsize, dynar->data, dynar->free_f); -} + dynar->size, dynar->used, dynar->elmsize, dynar->data, dynar->free_f); +} /** @brief Constructor - * + * * \param elmsize size of each element in the dynar * \param free_f function to call each time we want to get rid of an element (or NULL if nothing to do). * @@ -180,10 +180,10 @@ xbt_dynar_dump(xbt_dynar_t dynar) { * pointer of pointer. That is to say that dynars can contain either base * types (int, char, double, etc) or pointer of pointers (struct **). */ -xbt_dynar_t +xbt_dynar_t xbt_dynar_new(const unsigned long elmsize, - void_f_pvoid_t const free_f) { - + void_f_pvoid_t const free_f) { + xbt_dynar_t dynar = xbt_new0(s_xbt_dynar_t,1); dynar->size = 0; @@ -196,21 +196,21 @@ xbt_dynar_new(const unsigned long elmsize, return dynar; } -/** @brief Creates a synchronized dynar. - * +/** @brief Creates a synchronized dynar. + * * Just like #xbt_dynar_new, but each access to the structure will be protected by a mutex - * + * */ -xbt_dynar_t +xbt_dynar_t xbt_dynar_new_sync(const unsigned long elmsize, - void_f_pvoid_t const free_f) { - xbt_dynar_t res = xbt_dynar_new(elmsize,free_f); - res->mutex = xbt_mutex_init(); - return res; + void_f_pvoid_t const free_f) { + xbt_dynar_t res = xbt_dynar_new(elmsize,free_f); + res->mutex = xbt_mutex_init(); + return res; } /** @brief Destructor of the structure not touching to the content - * + * * \param dynar poor victim * * kilkil a dynar BUT NOT its content. Ie, the array is freed, but the content @@ -225,9 +225,9 @@ xbt_dynar_free_container(xbt_dynar_t *dynar) { free((*dynar)->data); } - if ((*dynar)->mutex) - xbt_mutex_destroy((*dynar)->mutex); - + if ((*dynar)->mutex) + xbt_mutex_destroy((*dynar)->mutex); + _xbt_clear_mem(*dynar, sizeof(s_xbt_dynar_t)); free(*dynar); @@ -242,24 +242,24 @@ xbt_dynar_free_container(xbt_dynar_t *dynar) { void xbt_dynar_reset(xbt_dynar_t const dynar) { _dynar_lock(dynar); - + _sanity_check_dynar(dynar); - + DEBUG1("Reset the dynar %p",(void*)dynar); if (dynar->free_f) { _dynar_map(dynar, dynar->free_f); } - /* + /* if (dynar->data) free(dynar->data); dynar->size = 0; - */ + */ dynar->used = 0; _dynar_unlock(dynar); -/* dynar->data = NULL;*/ + /* dynar->data = NULL;*/ } /** @@ -267,7 +267,7 @@ xbt_dynar_reset(xbt_dynar_t const dynar) { * \param dynar a dynar * \param empty_slots_wanted number of empty slots you want to keep at the end of the * internal array for further insertions - * + * * Reduces the internal array size of the dynar to the number of elements plus * \a empty_slots_wanted. * After removing elements from the dynar, you can call this function to make @@ -279,7 +279,7 @@ xbt_dynar_reset(xbt_dynar_t const dynar) { */ void xbt_dynar_shrink(xbt_dynar_t dynar, int empty_slots_wanted) { unsigned long size_wanted; - + _dynar_lock(dynar); size_wanted = dynar->used + empty_slots_wanted; @@ -291,7 +291,7 @@ void xbt_dynar_shrink(xbt_dynar_t dynar, int empty_slots_wanted) { } /** @brief Destructor - * + * * \param dynar poor victim * * kilkil a dynar and its content @@ -306,11 +306,11 @@ xbt_dynar_free(xbt_dynar_t * dynar) { } /** \brief free a dynar passed as void* (handy to store dynar in dynars or dict) */ void xbt_dynar_free_voidp(void *d) { - xbt_dynar_free( (xbt_dynar_t*) d); + xbt_dynar_free( (xbt_dynar_t*) d); } - + /** @brief Count of dynar's elements - * + * * \param dynar the dynar we want to mesure */ unsigned long @@ -326,8 +326,8 @@ xbt_dynar_length(const xbt_dynar_t dynar) { */ void xbt_dynar_get_cpy(const xbt_dynar_t dynar, - const unsigned long idx, - void * const dst) { + const unsigned long idx, + void * const dst) { _dynar_lock(dynar); _sanity_check_dynar(dynar); _sanity_check_idx(idx); @@ -343,7 +343,7 @@ xbt_dynar_get_cpy(const xbt_dynar_t dynar, * \param idx index of the slot we want to retrieve * \return the \a idx-th element of \a dynar. * - * \warning The returned value is the actual content of the dynar. + * \warning The returned value is the actual content of the dynar. * Make a copy before fooling with it. */ void* @@ -379,7 +379,7 @@ _xbt_dynar_set(xbt_dynar_t dynar, } /** @brief Set the Nth element of a dynar (expended if needed). Previous value at this position is NOT freed - * + * * \param dynar information dealer * \param idx index of the slot we want to modify * \param src What will be feeded to the dynar @@ -388,8 +388,8 @@ _xbt_dynar_set(xbt_dynar_t dynar, */ void xbt_dynar_set(xbt_dynar_t dynar, - const int idx, - const void * const src) { + const int idx, + const void * const src) { _dynar_lock(dynar); _xbt_dynar_set(dynar,idx,src); @@ -408,8 +408,8 @@ xbt_dynar_set(xbt_dynar_t dynar, */ void xbt_dynar_replace(xbt_dynar_t dynar, - const unsigned long idx, - const void * const object) { + const unsigned long idx, + const void * const object) { _dynar_lock(dynar); _sanity_check_dynar(dynar); _sanity_check_idx(idx); @@ -426,12 +426,12 @@ xbt_dynar_replace(xbt_dynar_t dynar, static XBT_INLINE void * _xbt_dynar_insert_at_ptr(xbt_dynar_t const dynar, - const unsigned long idx) { - void *res; - unsigned long old_used; - unsigned long new_used; - unsigned long nb_shift; - + const unsigned long idx) { + void *res; + unsigned long old_used; + unsigned long new_used; + unsigned long nb_shift; + _sanity_check_dynar(dynar); _sanity_check_idx(idx); _check_sloppy_inbound_idx(dynar, idx); @@ -444,9 +444,9 @@ _xbt_dynar_insert_at_ptr(xbt_dynar_t const dynar, nb_shift = old_used - idx; if (nb_shift) - memmove(_xbt_dynar_elm(dynar, idx+1), - _xbt_dynar_elm(dynar, idx), - nb_shift * dynar->elmsize); + memmove(_xbt_dynar_elm(dynar, idx+1), + _xbt_dynar_elm(dynar, idx), + nb_shift * dynar->elmsize); dynar->used = new_used; res = _xbt_dynar_elm(dynar,idx); @@ -454,15 +454,15 @@ _xbt_dynar_insert_at_ptr(xbt_dynar_t const dynar, } /** @brief Make room for a new element, and return a pointer to it - * - * You can then use regular affectation to set its value instead of relying + * + * You can then use regular affectation to set its value instead of relying * on the slow memcpy. This is what xbt_dynar_insert_at_as() does. */ void * xbt_dynar_insert_at_ptr(xbt_dynar_t const dynar, - const int idx) { + const int idx) { void *res; - + _dynar_lock(dynar); res = _xbt_dynar_insert_at_ptr(dynar,idx); _dynar_unlock(dynar); @@ -470,21 +470,21 @@ xbt_dynar_insert_at_ptr(xbt_dynar_t const dynar, } /** @brief Set the Nth dynar's element, expending the dynar and sliding the previous values to the right - * + * * Set the Nth element of a dynar, expanding the dynar if needed, and * moving the previously existing value and all subsequent ones to one * position right in the dynar. */ void xbt_dynar_insert_at(xbt_dynar_t const dynar, - const int idx, - const void * const src) { + const int idx, + const void * const src) { _dynar_lock(dynar); /* checks done in xbt_dynar_insert_at_ptr */ memcpy(_xbt_dynar_insert_at_ptr(dynar,idx), - src, - dynar->elmsize); + src, + dynar->elmsize); _dynar_unlock(dynar); } @@ -492,15 +492,15 @@ xbt_dynar_insert_at(xbt_dynar_t const dynar, * * Get the Nth element of a dynar, removing it from the dynar and moving * all subsequent values to one position left in the dynar. - * - * If the object argument of this function is a non-null pointer, the removed - * element is copied to this address. If not, the element is freed using the + * + * If the object argument of this function is a non-null pointer, the removed + * element is copied to this address. If not, the element is freed using the * free_f function passed at dynar creation. */ void xbt_dynar_remove_at(xbt_dynar_t const dynar, - const int idx, - void * const object) { + const int idx, + void * const object) { _dynar_lock(dynar); _xbt_dynar_remove_at(dynar, idx, object); @@ -513,16 +513,16 @@ xbt_dynar_remove_at(xbt_dynar_t const dynar, */ int xbt_dynar_search(xbt_dynar_t const dynar, - void *const elem) { + void *const elem) { unsigned long it; - + _dynar_lock(dynar); - for (it=0; it< dynar->used; it++) + for (it=0; it< dynar->used; it++) if (!memcmp(_xbt_dynar_elm(dynar, it),elem,dynar->elmsize)) { _dynar_unlock(dynar); return it; } - + _dynar_unlock(dynar); THROW2(not_found_error,0,"Element %p not part of dynar %p",elem,dynar); } @@ -530,33 +530,33 @@ xbt_dynar_search(xbt_dynar_t const dynar, /** @brief Returns a boolean indicating whether the element is part of the dynar */ int xbt_dynar_member(xbt_dynar_t const dynar, - void *const elem) { + void *const elem) { xbt_ex_t e; - + TRY { - xbt_dynar_search(dynar,elem); + xbt_dynar_search(dynar,elem); } CATCH(e) { - if (e.category == not_found_error) { - xbt_ex_free(e); - return 0; - } - RETHROW; + if (e.category == not_found_error) { + xbt_ex_free(e); + return 0; + } + RETHROW; } return 1; } /** @brief Make room at the end of the dynar for a new element, and return a pointer to it. * - * You can then use regular affectation to set its value instead of relying + * You can then use regular affectation to set its value instead of relying * on the slow memcpy. This is what xbt_dynar_push_as() does. */ void * xbt_dynar_push_ptr(xbt_dynar_t const dynar) { void *res; - /* we have to inline xbt_dynar_insert_at_ptr here to make sure that - dynar->used don't change between reading it and getting the lock + /* we have to inline xbt_dynar_insert_at_ptr here to make sure that + dynar->used don't change between reading it and getting the lock within xbt_dynar_insert_at_ptr */ _dynar_lock(dynar); res = _xbt_dynar_insert_at_ptr(dynar,dynar->used); @@ -567,24 +567,24 @@ xbt_dynar_push_ptr(xbt_dynar_t const dynar) { /** @brief Add an element at the end of the dynar */ void xbt_dynar_push(xbt_dynar_t const dynar, - const void * const src) { + const void * const src) { _dynar_lock(dynar); /* checks done in xbt_dynar_insert_at_ptr */ memcpy(_xbt_dynar_insert_at_ptr(dynar,dynar->used), - src, - dynar->elmsize); + src, + dynar->elmsize); _dynar_unlock(dynar); } /** @brief Mark the last dynar's element as unused and return a pointer to it. * - * You can then use regular affectation to set its value instead of relying + * You can then use regular affectation to set its value instead of relying * on the slow memcpy. This is what xbt_dynar_pop_as() does. */ void * xbt_dynar_pop_ptr(xbt_dynar_t const dynar) { void *res; - + _dynar_lock(dynar); _check_populated_dynar(dynar); DEBUG1("Pop %p",(void*)dynar); @@ -612,8 +612,8 @@ xbt_dynar_pop(xbt_dynar_t const dynar, */ void xbt_dynar_unshift(xbt_dynar_t const dynar, - const void * const src) { - + const void * const src) { + /* sanity checks done by insert_at */ xbt_dynar_insert_at(dynar, 0, src); } @@ -624,14 +624,14 @@ xbt_dynar_unshift(xbt_dynar_t const dynar, */ void xbt_dynar_shift(xbt_dynar_t const dynar, - void * const dst) { + void * const dst) { /* sanity checks done by remove_at */ xbt_dynar_remove_at(dynar, 0, dst); } static void _dynar_map(const xbt_dynar_t dynar, - void_f_pvoid_t const op) { + void_f_pvoid_t const op) { char elm[SIZEOF_MAX]; const unsigned long used = dynar->used; unsigned long i = 0; @@ -644,16 +644,16 @@ static void _dynar_map(const xbt_dynar_t dynar, /** @brief Apply a function to each member of a dynar * - * The mapped function may change the value of the element itself, - * but should not mess with the structure of the dynar. + * The mapped function may change the value of the element itself, + * but should not mess with the structure of the dynar. * * If the dynar is synchronized, it is locked during the whole map - * operation, so make sure your function don't call any function + * operation, so make sure your function don't call any function * from xbt_dynar_* on it, or you'll get a deadlock. */ void xbt_dynar_map(const xbt_dynar_t dynar, - void_f_pvoid_t const op) { + void_f_pvoid_t const op) { _dynar_lock(dynar); _sanity_check_dynar(dynar); @@ -666,38 +666,38 @@ xbt_dynar_map(const xbt_dynar_t dynar, /** @brief Put the cursor at the begining of the dynar. * * Actually, the cursor is set one step before the begining, so that you - * can iterate over the dynar with a for loop. + * can iterate over the dynar with a for loop. * * @warning Do not call this function directly, but only through xbt_dynar_foreach. */ void _xbt_dynar_cursor_first(const xbt_dynar_t dynar, - unsigned int * const cursor) { + unsigned int * const cursor) { _dynar_lock(dynar); DEBUG1("Set cursor on %p to the first position",(void*)dynar); *cursor = 0; } -/** @brief Move the cursor to the next value +/** @brief Move the cursor to the next value * * @warning Do not call this function directly, but only through xbt_dynar_foreach. */ void _xbt_dynar_cursor_step(const xbt_dynar_t dynar, - unsigned int * const cursor) { - + unsigned int * const cursor) { + (*cursor)++; } /** @brief Get the data currently pointed by the cursor - * + * * @warning Do not call this function directly, but only through xbt_dynar_foreach. */ int _xbt_dynar_cursor_get(const xbt_dynar_t dynar, - unsigned int * const cursor, - void * const dst) { + unsigned int * const cursor, + void * const dst) { _sanity_check_dynar(dynar); { @@ -717,13 +717,13 @@ _xbt_dynar_cursor_get(const xbt_dynar_t dynar, } -/** @brief Removes and free the entry pointed by the cursor +/** @brief Removes and free the entry pointed by the cursor * * This function can be used while traversing without problem. */ void xbt_dynar_cursor_rm(xbt_dynar_t dynar, - unsigned int * const cursor) { - + unsigned int * const cursor) { + _xbt_dynar_remove_at(dynar,(*cursor)--,NULL); } @@ -746,260 +746,260 @@ XBT_LOG_EXTERNAL_CATEGORY(xbt_dyn); XBT_LOG_DEFAULT_CATEGORY(xbt_dyn); XBT_TEST_UNIT("int",test_dynar_int,"Dynars of integers") { - /* Vars_decl [doxygen cruft] */ - xbt_dynar_t d; - int i,cpt; - unsigned int cursor; - int *iptr; - - xbt_test_add0("==== Traverse the empty dynar"); - d=xbt_dynar_new(sizeof(int),NULL); - xbt_dynar_foreach(d,cursor,i){ - xbt_assert0(0,"Damnit, there is something in the empty dynar"); - } - xbt_dynar_free(&d); - xbt_dynar_free(&d); - - xbt_test_add1("==== Push %d int, set them again 3 times, traverse them, shift them", - NB_ELEM); - /* Populate_ints [doxygen cruft] */ - /* 1. Populate the dynar */ - d=xbt_dynar_new(sizeof(int),NULL); - for (cpt=0; cpt< NB_ELEM; cpt++) { - xbt_dynar_push_as(d,int,cpt); /* This is faster (and possible only with scalars) */ - /* xbt_dynar_push(d,&cpt); This would also work */ - xbt_test_log2("Push %d, length=%lu",cpt, xbt_dynar_length(d)); - } - - /* 2. Traverse manually the dynar */ - for (cursor=0; cursor< NB_ELEM; cursor++) { - iptr=xbt_dynar_get_ptr(d,cursor); - xbt_test_assert2(cursor == *iptr, - "The retrieved value is not the same than the injected one (%d!=%d)", - cursor,cpt); - } - - /* 3. Traverse the dynar using the neat macro to that extend */ - xbt_dynar_foreach(d,cursor,cpt){ - xbt_test_assert2(cursor == cpt, - "The retrieved value is not the same than the injected one (%d!=%d)", - cursor,cpt); - } - /* end_of_traversal */ - - for (cpt=0; cpt< NB_ELEM; cpt++) - *(int*)xbt_dynar_get_ptr(d,cpt) = cpt; - - for (cpt=0; cpt< NB_ELEM; cpt++) - *(int*)xbt_dynar_get_ptr(d,cpt) = cpt; -/* xbt_dynar_set(d,cpt,&cpt);*/ - - for (cpt=0; cpt< NB_ELEM; cpt++) - *(int*)xbt_dynar_get_ptr(d,cpt) = cpt; - - cpt=0; - xbt_dynar_foreach(d,cursor,i){ - xbt_test_assert2(i == cpt, - "The retrieved value is not the same than the injected one (%d!=%d)", - i,cpt); - cpt++; - } - xbt_test_assert2(cpt == NB_ELEM, - "Cannot retrieve my %d values. Last got one is %d", - NB_ELEM, cpt); - - /* shifting [doxygen cruft] */ - /* 4. Shift all the values */ - for (cpt=0; cpt< NB_ELEM; cpt++) { - xbt_dynar_shift(d,&i); - xbt_test_assert2(i == cpt, - "The retrieved value is not the same than the injected one (%d!=%d)", - i,cpt); - xbt_test_log2("Pop %d, length=%lu",cpt, xbt_dynar_length(d)); - } - - /* 5. Free the resources */ - xbt_dynar_free(&d); - xbt_dynar_free(&d); - - - xbt_test_add1("==== Unshift/pop %d int",NB_ELEM); - d=xbt_dynar_new(sizeof(int),NULL); - for (cpt=0; cpt< NB_ELEM; cpt++) { - xbt_dynar_unshift(d,&cpt); - DEBUG2("Push %d, length=%lu",cpt, xbt_dynar_length(d)); - } - for (cpt=0; cpt< NB_ELEM; cpt++) { - i=xbt_dynar_pop_as(d,int); - xbt_test_assert2(i == cpt, - "The retrieved value is not the same than the injected one (%d!=%d)", - i,cpt); - xbt_test_log2("Pop %d, length=%lu",cpt, xbt_dynar_length(d)); - } - xbt_dynar_free(&d); - xbt_dynar_free(&d); - - - xbt_test_add1("==== Push %d int, insert 1000 int in the middle, shift everything",NB_ELEM); - d=xbt_dynar_new(sizeof(int),NULL); - for (cpt=0; cpt< NB_ELEM; cpt++) { - xbt_dynar_push_as(d,int,cpt); - DEBUG2("Push %d, length=%lu",cpt, xbt_dynar_length(d)); - } - for (cpt=0; cpt< 1000; cpt++) { - xbt_dynar_insert_at_as(d,2500,int,cpt); - DEBUG2("Push %d, length=%lu",cpt, xbt_dynar_length(d)); - } - - for (cpt=0; cpt< 2500; cpt++) { - xbt_dynar_shift(d,&i); - xbt_test_assert2(i == cpt, - "The retrieved value is not the same than the injected one at the begining (%d!=%d)", - i,cpt); - DEBUG2("Pop %d, length=%lu",cpt, xbt_dynar_length(d)); - } - for (cpt=999; cpt>=0; cpt--) { - xbt_dynar_shift(d,&i); - xbt_test_assert2(i == cpt, - "The retrieved value is not the same than the injected one in the middle (%d!=%d)", - i,cpt); - } - for (cpt=2500; cpt< NB_ELEM; cpt++) { - xbt_dynar_shift(d,&i); - xbt_test_assert2(i == cpt, - "The retrieved value is not the same than the injected one at the end (%d!=%d)", - i,cpt); - } - xbt_dynar_free(&d); - xbt_dynar_free(&d); - - - xbt_test_add1("==== Push %d int, remove 2000-4000. free the rest",NB_ELEM); - d=xbt_dynar_new(sizeof(int),NULL); - for (cpt=0; cpt< NB_ELEM; cpt++) - xbt_dynar_push_as(d,int,cpt); - - for (cpt=2000; cpt< 4000; cpt++) { - xbt_dynar_remove_at(d,2000,&i); - xbt_test_assert2(i == cpt, - "Remove a bad value. Got %d, expected %d", - i,cpt); - DEBUG2("remove %d, length=%lu",cpt, xbt_dynar_length(d)); - } - xbt_dynar_free(&d); - xbt_dynar_free(&d); + /* Vars_decl [doxygen cruft] */ + xbt_dynar_t d; + int i,cpt; + unsigned int cursor; + int *iptr; + + xbt_test_add0("==== Traverse the empty dynar"); + d=xbt_dynar_new(sizeof(int),NULL); + xbt_dynar_foreach(d,cursor,i){ + xbt_assert0(0,"Damnit, there is something in the empty dynar"); + } + xbt_dynar_free(&d); + xbt_dynar_free(&d); + + xbt_test_add1("==== Push %d int, set them again 3 times, traverse them, shift them", + NB_ELEM); + /* Populate_ints [doxygen cruft] */ + /* 1. Populate the dynar */ + d=xbt_dynar_new(sizeof(int),NULL); + for (cpt=0; cpt< NB_ELEM; cpt++) { + xbt_dynar_push_as(d,int,cpt); /* This is faster (and possible only with scalars) */ + /* xbt_dynar_push(d,&cpt); This would also work */ + xbt_test_log2("Push %d, length=%lu",cpt, xbt_dynar_length(d)); + } + + /* 2. Traverse manually the dynar */ + for (cursor=0; cursor< NB_ELEM; cursor++) { + iptr=xbt_dynar_get_ptr(d,cursor); + xbt_test_assert2(cursor == *iptr, + "The retrieved value is not the same than the injected one (%d!=%d)", + cursor,cpt); + } + + /* 3. Traverse the dynar using the neat macro to that extend */ + xbt_dynar_foreach(d,cursor,cpt){ + xbt_test_assert2(cursor == cpt, + "The retrieved value is not the same than the injected one (%d!=%d)", + cursor,cpt); + } + /* end_of_traversal */ + + for (cpt=0; cpt< NB_ELEM; cpt++) + *(int*)xbt_dynar_get_ptr(d,cpt) = cpt; + + for (cpt=0; cpt< NB_ELEM; cpt++) + *(int*)xbt_dynar_get_ptr(d,cpt) = cpt; + /* xbt_dynar_set(d,cpt,&cpt);*/ + + for (cpt=0; cpt< NB_ELEM; cpt++) + *(int*)xbt_dynar_get_ptr(d,cpt) = cpt; + + cpt=0; + xbt_dynar_foreach(d,cursor,i){ + xbt_test_assert2(i == cpt, + "The retrieved value is not the same than the injected one (%d!=%d)", + i,cpt); + cpt++; + } + xbt_test_assert2(cpt == NB_ELEM, + "Cannot retrieve my %d values. Last got one is %d", + NB_ELEM, cpt); + + /* shifting [doxygen cruft] */ + /* 4. Shift all the values */ + for (cpt=0; cpt< NB_ELEM; cpt++) { + xbt_dynar_shift(d,&i); + xbt_test_assert2(i == cpt, + "The retrieved value is not the same than the injected one (%d!=%d)", + i,cpt); + xbt_test_log2("Pop %d, length=%lu",cpt, xbt_dynar_length(d)); + } + + /* 5. Free the resources */ + xbt_dynar_free(&d); + xbt_dynar_free(&d); + + + xbt_test_add1("==== Unshift/pop %d int",NB_ELEM); + d=xbt_dynar_new(sizeof(int),NULL); + for (cpt=0; cpt< NB_ELEM; cpt++) { + xbt_dynar_unshift(d,&cpt); + DEBUG2("Push %d, length=%lu",cpt, xbt_dynar_length(d)); + } + for (cpt=0; cpt< NB_ELEM; cpt++) { + i=xbt_dynar_pop_as(d,int); + xbt_test_assert2(i == cpt, + "The retrieved value is not the same than the injected one (%d!=%d)", + i,cpt); + xbt_test_log2("Pop %d, length=%lu",cpt, xbt_dynar_length(d)); + } + xbt_dynar_free(&d); + xbt_dynar_free(&d); + + + xbt_test_add1("==== Push %d int, insert 1000 int in the middle, shift everything",NB_ELEM); + d=xbt_dynar_new(sizeof(int),NULL); + for (cpt=0; cpt< NB_ELEM; cpt++) { + xbt_dynar_push_as(d,int,cpt); + DEBUG2("Push %d, length=%lu",cpt, xbt_dynar_length(d)); + } + for (cpt=0; cpt< 1000; cpt++) { + xbt_dynar_insert_at_as(d,2500,int,cpt); + DEBUG2("Push %d, length=%lu",cpt, xbt_dynar_length(d)); + } + + for (cpt=0; cpt< 2500; cpt++) { + xbt_dynar_shift(d,&i); + xbt_test_assert2(i == cpt, + "The retrieved value is not the same than the injected one at the begining (%d!=%d)", + i,cpt); + DEBUG2("Pop %d, length=%lu",cpt, xbt_dynar_length(d)); + } + for (cpt=999; cpt>=0; cpt--) { + xbt_dynar_shift(d,&i); + xbt_test_assert2(i == cpt, + "The retrieved value is not the same than the injected one in the middle (%d!=%d)", + i,cpt); + } + for (cpt=2500; cpt< NB_ELEM; cpt++) { + xbt_dynar_shift(d,&i); + xbt_test_assert2(i == cpt, + "The retrieved value is not the same than the injected one at the end (%d!=%d)", + i,cpt); + } + xbt_dynar_free(&d); + xbt_dynar_free(&d); + + + xbt_test_add1("==== Push %d int, remove 2000-4000. free the rest",NB_ELEM); + d=xbt_dynar_new(sizeof(int),NULL); + for (cpt=0; cpt< NB_ELEM; cpt++) + xbt_dynar_push_as(d,int,cpt); + + for (cpt=2000; cpt< 4000; cpt++) { + xbt_dynar_remove_at(d,2000,&i); + xbt_test_assert2(i == cpt, + "Remove a bad value. Got %d, expected %d", + i,cpt); + DEBUG2("remove %d, length=%lu",cpt, xbt_dynar_length(d)); + } + xbt_dynar_free(&d); + xbt_dynar_free(&d); } /*******************************************************************************/ /*******************************************************************************/ /*******************************************************************************/ XBT_TEST_UNIT("double",test_dynar_double,"Dynars of doubles") { - xbt_dynar_t d; - int cpt; - unsigned int cursor; - double d1,d2; - - xbt_test_add0("==== Traverse the empty dynar"); - d=xbt_dynar_new(sizeof(int),NULL); - xbt_dynar_foreach(d,cursor,cpt){ - xbt_test_assert0(FALSE, - "Damnit, there is something in the empty dynar"); - } - xbt_dynar_free(&d); - xbt_dynar_free(&d); - - xbt_test_add0("==== Push/shift 5000 doubles"); - d=xbt_dynar_new(sizeof(double),NULL); - for (cpt=0; cpt< 5000; cpt++) { - d1=(double)cpt; - xbt_dynar_push(d,&d1); - } - xbt_dynar_foreach(d,cursor,d2){ - d1=(double)cursor; - xbt_test_assert2(d1 == d2, - "The retrieved value is not the same than the injected one (%f!=%f)", - d1,d2); - } - for (cpt=0; cpt< 5000; cpt++) { - d1=(double)cpt; - xbt_dynar_shift(d,&d2); - xbt_test_assert2(d1 == d2, - "The retrieved value is not the same than the injected one (%f!=%f)", - d1,d2); - } - xbt_dynar_free(&d); - xbt_dynar_free(&d); - - - xbt_test_add0("==== Unshift/pop 5000 doubles"); - d=xbt_dynar_new(sizeof(double),NULL); - for (cpt=0; cpt< 5000; cpt++) { - d1=(double)cpt; - xbt_dynar_unshift(d,&d1); - } - for (cpt=0; cpt< 5000; cpt++) { - d1=(double)cpt; - xbt_dynar_pop(d,&d2); - xbt_test_assert2 (d1 == d2, - "The retrieved value is not the same than the injected one (%f!=%f)", - d1,d2); - } - xbt_dynar_free(&d); - xbt_dynar_free(&d); - - - - xbt_test_add0("==== Push 5000 doubles, insert 1000 doubles in the middle, shift everything"); - d=xbt_dynar_new(sizeof(double),NULL); - for (cpt=0; cpt< 5000; cpt++) { - d1=(double)cpt; - xbt_dynar_push(d,&d1); - } - for (cpt=0; cpt< 1000; cpt++) { - d1=(double)cpt; - xbt_dynar_insert_at(d,2500,&d1); - } - - for (cpt=0; cpt< 2500; cpt++) { - d1=(double)cpt; - xbt_dynar_shift(d,&d2); - xbt_test_assert2(d1 == d2, - "The retrieved value is not the same than the injected one at the begining (%f!=%f)", - d1,d2); - DEBUG2("Pop %d, length=%lu",cpt, xbt_dynar_length(d)); - } - for (cpt=999; cpt>=0; cpt--) { - d1=(double)cpt; - xbt_dynar_shift(d,&d2); - xbt_test_assert2 (d1 == d2, - "The retrieved value is not the same than the injected one in the middle (%f!=%f)", - d1,d2); - } - for (cpt=2500; cpt< 5000; cpt++) { - d1=(double)cpt; - xbt_dynar_shift(d,&d2); - xbt_test_assert2 (d1 == d2, - "The retrieved value is not the same than the injected one at the end (%f!=%f)", - d1,d2); - } - xbt_dynar_free(&d); - xbt_dynar_free(&d); - - - xbt_test_add0("==== Push 5000 double, remove 2000-4000. free the rest"); - d=xbt_dynar_new(sizeof(double),NULL); - for (cpt=0; cpt< 5000; cpt++) { - d1=(double)cpt; - xbt_dynar_push(d,&d1); - } - for (cpt=2000; cpt< 4000; cpt++) { - d1=(double)cpt; - xbt_dynar_remove_at(d,2000,&d2); - xbt_test_assert2 (d1 == d2, - "Remove a bad value. Got %f, expected %f", - d2,d1); - } - xbt_dynar_free(&d); - xbt_dynar_free(&d); + xbt_dynar_t d; + int cpt; + unsigned int cursor; + double d1,d2; + + xbt_test_add0("==== Traverse the empty dynar"); + d=xbt_dynar_new(sizeof(int),NULL); + xbt_dynar_foreach(d,cursor,cpt){ + xbt_test_assert0(FALSE, + "Damnit, there is something in the empty dynar"); + } + xbt_dynar_free(&d); + xbt_dynar_free(&d); + + xbt_test_add0("==== Push/shift 5000 doubles"); + d=xbt_dynar_new(sizeof(double),NULL); + for (cpt=0; cpt< 5000; cpt++) { + d1=(double)cpt; + xbt_dynar_push(d,&d1); + } + xbt_dynar_foreach(d,cursor,d2){ + d1=(double)cursor; + xbt_test_assert2(d1 == d2, + "The retrieved value is not the same than the injected one (%f!=%f)", + d1,d2); + } + for (cpt=0; cpt< 5000; cpt++) { + d1=(double)cpt; + xbt_dynar_shift(d,&d2); + xbt_test_assert2(d1 == d2, + "The retrieved value is not the same than the injected one (%f!=%f)", + d1,d2); + } + xbt_dynar_free(&d); + xbt_dynar_free(&d); + + + xbt_test_add0("==== Unshift/pop 5000 doubles"); + d=xbt_dynar_new(sizeof(double),NULL); + for (cpt=0; cpt< 5000; cpt++) { + d1=(double)cpt; + xbt_dynar_unshift(d,&d1); + } + for (cpt=0; cpt< 5000; cpt++) { + d1=(double)cpt; + xbt_dynar_pop(d,&d2); + xbt_test_assert2 (d1 == d2, + "The retrieved value is not the same than the injected one (%f!=%f)", + d1,d2); + } + xbt_dynar_free(&d); + xbt_dynar_free(&d); + + + + xbt_test_add0("==== Push 5000 doubles, insert 1000 doubles in the middle, shift everything"); + d=xbt_dynar_new(sizeof(double),NULL); + for (cpt=0; cpt< 5000; cpt++) { + d1=(double)cpt; + xbt_dynar_push(d,&d1); + } + for (cpt=0; cpt< 1000; cpt++) { + d1=(double)cpt; + xbt_dynar_insert_at(d,2500,&d1); + } + + for (cpt=0; cpt< 2500; cpt++) { + d1=(double)cpt; + xbt_dynar_shift(d,&d2); + xbt_test_assert2(d1 == d2, + "The retrieved value is not the same than the injected one at the begining (%f!=%f)", + d1,d2); + DEBUG2("Pop %d, length=%lu",cpt, xbt_dynar_length(d)); + } + for (cpt=999; cpt>=0; cpt--) { + d1=(double)cpt; + xbt_dynar_shift(d,&d2); + xbt_test_assert2 (d1 == d2, + "The retrieved value is not the same than the injected one in the middle (%f!=%f)", + d1,d2); + } + for (cpt=2500; cpt< 5000; cpt++) { + d1=(double)cpt; + xbt_dynar_shift(d,&d2); + xbt_test_assert2 (d1 == d2, + "The retrieved value is not the same than the injected one at the end (%f!=%f)", + d1,d2); + } + xbt_dynar_free(&d); + xbt_dynar_free(&d); + + + xbt_test_add0("==== Push 5000 double, remove 2000-4000. free the rest"); + d=xbt_dynar_new(sizeof(double),NULL); + for (cpt=0; cpt< 5000; cpt++) { + d1=(double)cpt; + xbt_dynar_push(d,&d1); + } + for (cpt=2000; cpt< 4000; cpt++) { + d1=(double)cpt; + xbt_dynar_remove_at(d,2000,&d2); + xbt_test_assert2 (d1 == d2, + "Remove a bad value. Got %f, expected %f", + d2,d1); + } + xbt_dynar_free(&d); + xbt_dynar_free(&d); } @@ -1009,142 +1009,142 @@ XBT_TEST_UNIT("double",test_dynar_double,"Dynars of doubles") { /*******************************************************************************/ /*******************************************************************************/ XBT_TEST_UNIT("string",test_dynar_string,"Dyars of strings") { - xbt_dynar_t d; - int cpt; - unsigned int iter; - char buf[1024]; - char *s1,*s2; - - xbt_test_add0("==== Traverse the empty dynar"); - d=xbt_dynar_new(sizeof(char *),&xbt_free_ref); - xbt_dynar_foreach(d,iter,s1){ - xbt_test_assert0(FALSE, - "Damnit, there is something in the empty dynar"); - } - xbt_dynar_free(&d); - xbt_dynar_free(&d); - - xbt_test_add1("==== Push %d strings, set them again 3 times, shift them",NB_ELEM); - /* Populate_str [doxygen cruft] */ - d=xbt_dynar_new(sizeof(char*),&xbt_free_ref); - /* 1. Populate the dynar */ - for (cpt=0; cpt< NB_ELEM; cpt++) { - sprintf(buf,"%d",cpt); - s1=strdup(buf); - xbt_dynar_push(d,&s1); - } - for (cpt=0; cpt< NB_ELEM; cpt++) { - sprintf(buf,"%d",cpt); - s1=strdup(buf); - xbt_dynar_replace(d,cpt,&s1); - } - for (cpt=0; cpt< NB_ELEM; cpt++) { - sprintf(buf,"%d",cpt); - s1=strdup(buf); - xbt_dynar_replace(d,cpt,&s1); - } - for (cpt=0; cpt< NB_ELEM; cpt++) { - sprintf(buf,"%d",cpt); - s1=strdup(buf); - xbt_dynar_replace(d,cpt,&s1); - } - for (cpt=0; cpt< NB_ELEM; cpt++) { - sprintf(buf,"%d",cpt); - xbt_dynar_shift(d,&s2); - xbt_test_assert2 (!strcmp(buf,s2), - "The retrieved value is not the same than the injected one (%s!=%s)", - buf,s2); - free(s2); - } - xbt_dynar_free(&d); - xbt_dynar_free(&d); - - - xbt_test_add1("==== Unshift, traverse and pop %d strings",NB_ELEM); - d=xbt_dynar_new(sizeof(char**),&xbt_free_ref); - for (cpt=0; cpt< NB_ELEM; cpt++) { - sprintf(buf,"%d",cpt); - s1=strdup(buf); - xbt_dynar_unshift(d,&s1); - } - /* 2. Traverse the dynar with the macro */ - xbt_dynar_foreach(d,iter,s1) { - sprintf(buf,"%d",NB_ELEM - iter -1); - xbt_test_assert2 (!strcmp(buf,s1), - "The retrieved value is not the same than the injected one (%s!=%s)", - buf,s1); - } - /* 3. Traverse the dynar with the macro */ - for (cpt=0; cpt< NB_ELEM; cpt++) { - sprintf(buf,"%d",cpt); - xbt_dynar_pop(d,&s2); - xbt_test_assert2 (!strcmp(buf,s2), - "The retrieved value is not the same than the injected one (%s!=%s)", - buf,s2); - free(s2); - } - /* 4. Free the resources */ - xbt_dynar_free(&d); - xbt_dynar_free(&d); - - - xbt_test_add2("==== Push %d strings, insert %d strings in the middle, shift everything",NB_ELEM,NB_ELEM/5); - d=xbt_dynar_new(sizeof(char*),&xbt_free_ref); - for (cpt=0; cpt< NB_ELEM; cpt++) { - sprintf(buf,"%d",cpt); - s1=strdup(buf); - xbt_dynar_push(d,&s1); - } - for (cpt=0; cpt< NB_ELEM/5; cpt++) { - sprintf(buf,"%d",cpt); - s1=strdup(buf); - xbt_dynar_insert_at(d,NB_ELEM/2,&s1); - } - - for (cpt=0; cpt< NB_ELEM/2; cpt++) { - sprintf(buf,"%d",cpt); - xbt_dynar_shift(d,&s2); - xbt_test_assert2(!strcmp(buf,s2), - "The retrieved value is not the same than the injected one at the begining (%s!=%s)", - buf,s2); - free(s2); - } - for (cpt=(NB_ELEM/5)-1; cpt>=0; cpt--) { - sprintf(buf,"%d",cpt); - xbt_dynar_shift(d,&s2); - xbt_test_assert2 (!strcmp(buf,s2), - "The retrieved value is not the same than the injected one in the middle (%s!=%s)", - buf,s2); - free(s2); - } - for (cpt=NB_ELEM/2; cpt< NB_ELEM; cpt++) { - sprintf(buf,"%d",cpt); - xbt_dynar_shift(d,&s2); - xbt_test_assert2 (!strcmp(buf,s2), - "The retrieved value is not the same than the injected one at the end (%s!=%s)", - buf,s2); - free(s2); - } - xbt_dynar_free(&d); - xbt_dynar_free(&d); - - - xbt_test_add3("==== Push %d strings, remove %d-%d. free the rest",NB_ELEM,2*(NB_ELEM/5),4*(NB_ELEM/5)); - d=xbt_dynar_new(sizeof(char*),&xbt_free_ref); - for (cpt=0; cpt< NB_ELEM; cpt++) { - sprintf(buf,"%d",cpt); - s1=strdup(buf); - xbt_dynar_push(d,&s1); - } - for (cpt=2*(NB_ELEM/5); cpt< 4*(NB_ELEM/5); cpt++) { - sprintf(buf,"%d",cpt); - xbt_dynar_remove_at(d,2*(NB_ELEM/5),&s2); - xbt_test_assert2(!strcmp(buf,s2), - "Remove a bad value. Got %s, expected %s", - s2,buf); - free(s2); - } - xbt_dynar_free(&d); /* end_of_doxygen */ + xbt_dynar_t d; + int cpt; + unsigned int iter; + char buf[1024]; + char *s1,*s2; + + xbt_test_add0("==== Traverse the empty dynar"); + d=xbt_dynar_new(sizeof(char *),&xbt_free_ref); + xbt_dynar_foreach(d,iter,s1){ + xbt_test_assert0(FALSE, + "Damnit, there is something in the empty dynar"); + } + xbt_dynar_free(&d); + xbt_dynar_free(&d); + + xbt_test_add1("==== Push %d strings, set them again 3 times, shift them",NB_ELEM); + /* Populate_str [doxygen cruft] */ + d=xbt_dynar_new(sizeof(char*),&xbt_free_ref); + /* 1. Populate the dynar */ + for (cpt=0; cpt< NB_ELEM; cpt++) { + sprintf(buf,"%d",cpt); + s1=strdup(buf); + xbt_dynar_push(d,&s1); + } + for (cpt=0; cpt< NB_ELEM; cpt++) { + sprintf(buf,"%d",cpt); + s1=strdup(buf); + xbt_dynar_replace(d,cpt,&s1); + } + for (cpt=0; cpt< NB_ELEM; cpt++) { + sprintf(buf,"%d",cpt); + s1=strdup(buf); + xbt_dynar_replace(d,cpt,&s1); + } + for (cpt=0; cpt< NB_ELEM; cpt++) { + sprintf(buf,"%d",cpt); + s1=strdup(buf); + xbt_dynar_replace(d,cpt,&s1); + } + for (cpt=0; cpt< NB_ELEM; cpt++) { + sprintf(buf,"%d",cpt); + xbt_dynar_shift(d,&s2); + xbt_test_assert2 (!strcmp(buf,s2), + "The retrieved value is not the same than the injected one (%s!=%s)", + buf,s2); + free(s2); + } + xbt_dynar_free(&d); + xbt_dynar_free(&d); + + + xbt_test_add1("==== Unshift, traverse and pop %d strings",NB_ELEM); + d=xbt_dynar_new(sizeof(char**),&xbt_free_ref); + for (cpt=0; cpt< NB_ELEM; cpt++) { + sprintf(buf,"%d",cpt); + s1=strdup(buf); + xbt_dynar_unshift(d,&s1); + } + /* 2. Traverse the dynar with the macro */ + xbt_dynar_foreach(d,iter,s1) { + sprintf(buf,"%d",NB_ELEM - iter -1); + xbt_test_assert2 (!strcmp(buf,s1), + "The retrieved value is not the same than the injected one (%s!=%s)", + buf,s1); + } + /* 3. Traverse the dynar with the macro */ + for (cpt=0; cpt< NB_ELEM; cpt++) { + sprintf(buf,"%d",cpt); + xbt_dynar_pop(d,&s2); + xbt_test_assert2 (!strcmp(buf,s2), + "The retrieved value is not the same than the injected one (%s!=%s)", + buf,s2); + free(s2); + } + /* 4. Free the resources */ + xbt_dynar_free(&d); + xbt_dynar_free(&d); + + + xbt_test_add2("==== Push %d strings, insert %d strings in the middle, shift everything",NB_ELEM,NB_ELEM/5); + d=xbt_dynar_new(sizeof(char*),&xbt_free_ref); + for (cpt=0; cpt< NB_ELEM; cpt++) { + sprintf(buf,"%d",cpt); + s1=strdup(buf); + xbt_dynar_push(d,&s1); + } + for (cpt=0; cpt< NB_ELEM/5; cpt++) { + sprintf(buf,"%d",cpt); + s1=strdup(buf); + xbt_dynar_insert_at(d,NB_ELEM/2,&s1); + } + + for (cpt=0; cpt< NB_ELEM/2; cpt++) { + sprintf(buf,"%d",cpt); + xbt_dynar_shift(d,&s2); + xbt_test_assert2(!strcmp(buf,s2), + "The retrieved value is not the same than the injected one at the begining (%s!=%s)", + buf,s2); + free(s2); + } + for (cpt=(NB_ELEM/5)-1; cpt>=0; cpt--) { + sprintf(buf,"%d",cpt); + xbt_dynar_shift(d,&s2); + xbt_test_assert2 (!strcmp(buf,s2), + "The retrieved value is not the same than the injected one in the middle (%s!=%s)", + buf,s2); + free(s2); + } + for (cpt=NB_ELEM/2; cpt< NB_ELEM; cpt++) { + sprintf(buf,"%d",cpt); + xbt_dynar_shift(d,&s2); + xbt_test_assert2 (!strcmp(buf,s2), + "The retrieved value is not the same than the injected one at the end (%s!=%s)", + buf,s2); + free(s2); + } + xbt_dynar_free(&d); + xbt_dynar_free(&d); + + + xbt_test_add3("==== Push %d strings, remove %d-%d. free the rest",NB_ELEM,2*(NB_ELEM/5),4*(NB_ELEM/5)); + d=xbt_dynar_new(sizeof(char*),&xbt_free_ref); + for (cpt=0; cpt< NB_ELEM; cpt++) { + sprintf(buf,"%d",cpt); + s1=strdup(buf); + xbt_dynar_push(d,&s1); + } + for (cpt=2*(NB_ELEM/5); cpt< 4*(NB_ELEM/5); cpt++) { + sprintf(buf,"%d",cpt); + xbt_dynar_remove_at(d,2*(NB_ELEM/5),&s2); + xbt_test_assert2(!strcmp(buf,s2), + "Remove a bad value. Got %s, expected %s", + s2,buf); + free(s2); + } + xbt_dynar_free(&d); /* end_of_doxygen */ } @@ -1153,45 +1153,45 @@ XBT_TEST_UNIT("string",test_dynar_string,"Dyars of strings") { /*******************************************************************************/ #include "xbt/synchro.h" static void pusher_f(void *a) { - xbt_dynar_t d=(xbt_dynar_t)a; - int i; - for (i=0; i<500; i++) { - xbt_dynar_push(d,&i); - } + xbt_dynar_t d=(xbt_dynar_t)a; + int i; + for (i=0; i<500; i++) { + xbt_dynar_push(d,&i); + } } static void poper_f(void *a) { - xbt_dynar_t d=(xbt_dynar_t)a; - int i; - int data; - xbt_ex_t e; - - for (i=0; i<500; i++) { - TRY { - xbt_dynar_pop(d,&data); - } CATCH(e) { - if (e.category == bound_error) { - xbt_ex_free(e); - i--; - } else { - RETHROW; - } + xbt_dynar_t d=(xbt_dynar_t)a; + int i; + int data; + xbt_ex_t e; + + for (i=0; i<500; i++) { + TRY { + xbt_dynar_pop(d,&data); + } CATCH(e) { + if (e.category == bound_error) { + xbt_ex_free(e); + i--; + } else { + RETHROW; } - } + } + } } - + XBT_TEST_UNIT("synchronized int",test_dynar_sync_int,"Synchronized dynars of integers") { - /* Vars_decl [doxygen cruft] */ - xbt_dynar_t d; - xbt_thread_t pusher,poper; - - xbt_test_add0("==== Have a pusher and a popper on the dynar"); - d=xbt_dynar_new_sync(sizeof(int),NULL); - pusher = xbt_thread_create("pusher",pusher_f,d); - poper = xbt_thread_create("poper",poper_f,d); - xbt_thread_join(pusher); - xbt_thread_join(poper); - xbt_dynar_free(&d); + /* Vars_decl [doxygen cruft] */ + xbt_dynar_t d; + xbt_thread_t pusher,poper; + + xbt_test_add0("==== Have a pusher and a popper on the dynar"); + d=xbt_dynar_new_sync(sizeof(int),NULL); + pusher = xbt_thread_create("pusher",pusher_f,d); + poper = xbt_thread_create("poper",poper_f,d); + xbt_thread_join(pusher); + xbt_thread_join(poper); + xbt_dynar_free(&d); } #endif /* SIMGRID_TEST */ diff --git a/src/xbt/error.c b/src/xbt/error.c index 9e527bc463..9fe0e4e9ac 100644 --- a/src/xbt/error.c +++ b/src/xbt/error.c @@ -13,14 +13,14 @@ /** * \brief Usefull to do nice error repporting messages. * - * \param errcode + * \param errcode * \return the printable name of an error code * */ const char *xbt_error_name(xbt_error_t errcode) { - switch (errcode) { - + switch (errcode) { + case no_error: return "success"; case old_mismatch_error: return "mismatch"; case old_system_error: return "system"; @@ -30,15 +30,15 @@ const char *xbt_error_name(xbt_error_t errcode) { case old_unknown_error: return "unclassified"; default: return "SEVERE ERROR in error repporting module"; - } + } } XBT_LOG_EXTERNAL_CATEGORY(xbt); XBT_LOG_DEFAULT_CATEGORY(xbt); - + /** - * @brief Kill the program with an error message - * \param msg + * @brief Kill the program with an error message + * \param msg * * Things are so messed up that the only thing to do now, is to stop the program. * @@ -47,11 +47,11 @@ XBT_LOG_DEFAULT_CATEGORY(xbt); * If you want to pass arguments to the format, you can always write xbt_assert1(0,"fmt",args) */ void xbt_die (const char *msg) { - CRITICAL1("%s",msg); - xbt_abort(); + CRITICAL1("%s",msg); + xbt_abort(); } /** @brief Kill the program in silence */ void xbt_abort(void) { - abort(); + abort(); } diff --git a/src/xbt/ex.c b/src/xbt/ex.c index c93ea855b2..7c0714fcf8 100644 --- a/src/xbt/ex.c +++ b/src/xbt/ex.c @@ -25,20 +25,20 @@ #include "xbt/ex_interface.h" #undef HAVE_BACKTRACE -#if defined(HAVE_EXECINFO_H) && defined(HAVE_POPEN) && defined(ADDR2LINE) +#if defined(HAVE_EXECINFO_H) && defined(HAVE_POPEN) && defined(ADDR2LINE) # define HAVE_BACKTRACE 1 /* Hello linux box */ #endif #if defined(WIN32) && defined(_M_IX86) && !defined(__GNUC__) # define HAVE_BACKTRACE 1 /* Hello x86 windows box */ -#endif - +#endif + XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_ex,xbt,"Exception mecanism"); /* default __ex_ctx callback function */ ex_ctx_t *__xbt_ex_ctx_default(void) { - /* Don't scream: this is a default which is never used (so, yes, + /* Don't scream: this is a default which is never used (so, yes, there is one setjump container by running entity). This default gets overriden in xbt/xbt_os_thread.c so that it works in @@ -47,10 +47,10 @@ ex_ctx_t *__xbt_ex_ctx_default(void) { It also gets overriden in xbt/context.c when using ucontextes (as well as in Java for now, but after the java overhaul, it will get cleaned out) - */ - static ex_ctx_t ctx = XBT_CTX_INITIALIZER; + */ + static ex_ctx_t ctx = XBT_CTX_INITIALIZER; - return &ctx; + return &ctx; } /* Change raw libc symbols to file names and line numbers */ @@ -58,24 +58,24 @@ void xbt_ex_setup_backtrace(xbt_ex_t *e); void xbt_backtrace_display(xbt_ex_t *e) { xbt_ex_setup_backtrace(e); - + #ifdef HAVE_BACKTRACE if (e->used == 0) { - fprintf(stderr,"(backtrace not set)\n"); - } else { - int i; - - fprintf(stderr,"Backtrace (displayed in thread %p):\n", - (void*)xbt_thread_self()); - for (i=1; iused; i++) /* no need to display "xbt_display_backtrace" */ - fprintf(stderr,"---> %s\n",e->bt_strings[i] +4); + fprintf(stderr,"(backtrace not set)\n"); + } else { + int i; + + fprintf(stderr,"Backtrace (displayed in thread %p):\n", + (void*)xbt_thread_self()); + for (i=1; iused; i++) /* no need to display "xbt_display_backtrace" */ + fprintf(stderr,"---> %s\n",e->bt_strings[i] +4); } - + /* don't fool xbt_ex_free with uninitialized msg field */ e->msg=NULL; e->remote=0; xbt_ex_free(*e); -#else +#else ERROR0("No backtrace on this arch"); #endif @@ -104,12 +104,12 @@ void xbt_ex_display(xbt_ex_t *e) { thrower = bprintf(" on host %s(%d)",e->host,e->pid); fprintf(stderr, - "** SimGrid: UNCAUGHT EXCEPTION received on %s(%d): category: %s; value: %d\n" - "** %s\n" - "** Thrown by %s()%s\n", - gras_os_myname(),(*xbt_getpid)(), - xbt_ex_catname(e->category), e->value, e->msg, - e->procname,thrower?thrower:" in this process"); + "** SimGrid: UNCAUGHT EXCEPTION received on %s(%d): category: %s; value: %d\n" + "** %s\n" + "** Thrown by %s()%s\n", + gras_os_myname(),(*xbt_getpid)(), + xbt_ex_catname(e->category), e->value, e->msg, + e->procname,thrower?thrower:" in this process"); CRITICAL1("%s",e->msg); if (thrower) @@ -122,15 +122,15 @@ void xbt_ex_display(xbt_ex_t *e) { /* We have everything to build neat backtraces */ { int i; - + fprintf(stderr,"\n"); for (i=0; iused; i++) fprintf(stderr,"%s\n",e->bt_strings[i]); - + } #else - fprintf(stderr," at %s:%d:%s (no backtrace available on that arch)\n", - e->file,e->line,e->func); + fprintf(stderr," at %s:%d:%s (no backtrace available on that arch)\n", + e->file,e->line,e->func); #endif xbt_ex_free(*e); } @@ -159,10 +159,10 @@ void xbt_ex_free(xbt_ex_t e) { free(e.host); } - if (e.bt_strings) { - for (i=0; ifirst = cp1; cp2 = mallocex(TOOBIG); @@ -341,7 +341,7 @@ static void bad_example(void) { } #endif typedef struct {char *first;} global_context_t; - + static void good_example(void) { global_context_t *global_context=malloc(sizeof(global_context_t)); xbt_ex_t ex; @@ -362,9 +362,9 @@ static void good_example(void) { } CLEANUP { /*04*/ printf("cp3=%s", cp3 == NULL /*02*/ ? "" : cp3); if (cp3 != NULL) - free(cp3); + free(cp3); if (cp2 != NULL) - free(cp2); + free(cp2); /*05 cp1 was given away */ } CATCH(ex) { /*05 global context untouched */ diff --git a/src/xbt/fifo.c b/src/xbt/fifo.c index 84a3ade3bb..8e5ad69436 100644 --- a/src/xbt/fifo.c +++ b/src/xbt/fifo.c @@ -29,9 +29,9 @@ xbt_fifo_t xbt_fifo_new(void) if (item_mallocator == NULL) { item_mallocator = xbt_mallocator_new(256, - fifo_item_mallocator_new_f, - fifo_item_mallocator_free_f, - fifo_item_mallocator_reset_f); + fifo_item_mallocator_new_f, + fifo_item_mallocator_free_f, + fifo_item_mallocator_reset_f); } return fifo; } @@ -46,7 +46,7 @@ void xbt_fifo_free(xbt_fifo_t l) xbt_fifo_item_t b, tmp; for (b = xbt_fifo_get_first_item(l); b; - tmp = b, b = b->next, xbt_fifo_free_item(tmp)); + tmp = b, b = b->next, xbt_fifo_free_item(tmp)); xbt_free(l); return; } @@ -73,7 +73,7 @@ xbt_fifo_item_t xbt_fifo_push(xbt_fifo_t l, void *t) * \param l list * \returns the object stored at the tail of the list. * - * Removes and returns the object stored at the tail of the list. + * Removes and returns the object stored at the tail of the list. * Returns NULL if the list is empty. */ void *xbt_fifo_pop(xbt_fifo_t l) @@ -110,7 +110,7 @@ xbt_fifo_item_t xbt_fifo_unshift(xbt_fifo_t l, void *t) * \param l list * \returns the object stored at the head of the list. * - * Removes and returns the object stored at the head of the list. + * Removes and returns the object stored at the head of the list. * Returns NULL if the list is empty. */ void *xbt_fifo_shift(xbt_fifo_t l) @@ -120,7 +120,7 @@ void *xbt_fifo_shift(xbt_fifo_t l) if(l==NULL) return NULL; if(!(item = xbt_fifo_shift_item(l))) return NULL; - + content = item->content; xbt_fifo_free_item(item); return content; @@ -160,7 +160,7 @@ xbt_fifo_item_t xbt_fifo_pop_item(xbt_fifo_t l) return NULL; item = l->tail; - + l->tail = item->prev; if (l->tail == NULL) l->head = NULL; @@ -224,10 +224,10 @@ xbt_fifo_item_t xbt_fifo_shift_item(xbt_fifo_t l) } /** - * \param l + * \param l * \param t an objet * - * removes the first occurence of \a t from \a l. + * removes the first occurence of \a t from \a l. * \warning it will not remove duplicates * \return 1 if an item was removed and 0 otherwise. */ @@ -251,10 +251,10 @@ int xbt_fifo_remove(xbt_fifo_t l, void *t) /** - * \param l + * \param l * \param t an objet * - * removes all occurences of \a t from \a l. + * removes all occurences of \a t from \a l. * \return 1 if an item was removed and 0 otherwise. */ int xbt_fifo_remove_all(xbt_fifo_t l, void *t) @@ -278,8 +278,8 @@ int xbt_fifo_remove_all(xbt_fifo_t l, void *t) * \param l a list * \param current a bucket * - * removes a bucket \a current from the list \a l. This function implicitely - * assumes (and doesn't check!) that this item belongs to this list... + * removes a bucket \a current from the list \a l. This function implicitely + * assumes (and doesn't check!) that this item belongs to this list... */ void xbt_fifo_remove_item(xbt_fifo_t l, xbt_fifo_item_t current) { diff --git a/src/xbt/graph.c b/src/xbt/graph.c index 464dad4af1..53341c83a6 100644 --- a/src/xbt/graph.c +++ b/src/xbt/graph.c @@ -60,7 +60,7 @@ xbt_node_t xbt_graph_new_node(xbt_graph_t g, void *data) /** @brief add an edge to the given graph */ xbt_edge_t xbt_graph_new_edge(xbt_graph_t g, - xbt_node_t src, xbt_node_t dst, void *data) + xbt_node_t src, xbt_node_t dst, void *data) { xbt_edge_t edge = NULL; @@ -124,12 +124,12 @@ void xbt_graph_edge_set_data(xbt_edge_t edge, void *data) * @param edge_free_function: function to use to free data associated to each edge * @param graph_free_function: function to use to free data associated to g * - * Free the graph structure. + * Free the graph structure. */ void xbt_graph_free_graph(xbt_graph_t g, - void_f_pvoid_t node_free_function, - void_f_pvoid_t edge_free_function, - void_f_pvoid_t graph_free_function) + void_f_pvoid_t node_free_function, + void_f_pvoid_t edge_free_function, + void_f_pvoid_t graph_free_function) { unsigned int cursor = 0; xbt_node_t node = NULL; @@ -149,14 +149,14 @@ void xbt_graph_free_graph(xbt_graph_t g, } xbt_dynar_foreach(g->nodes, cursor, node) - free(node); + free(node); xbt_dynar_free(&(g->nodes)); xbt_dynar_foreach(g->edges, cursor, edge) - free(edge); + free(edge); xbt_dynar_free(&(g->edges)); - if(graph_free_function) - (*graph_free_function)(g->data); + if(graph_free_function) + (*graph_free_function)(g->data); free(g); return; @@ -165,8 +165,8 @@ void xbt_graph_free_graph(xbt_graph_t g, /** @brief remove the given node from the given graph */ void xbt_graph_free_node(xbt_graph_t g, xbt_node_t n, - void_f_pvoid_t node_free_function, - void_f_pvoid_t edge_free_function) + void_f_pvoid_t node_free_function, + void_f_pvoid_t edge_free_function) { unsigned long nbr; unsigned long i; @@ -190,8 +190,8 @@ void xbt_graph_free_node(xbt_graph_t g, xbt_node_t n, cursor = 0; xbt_dynar_foreach(g->nodes, cursor, node) - if (node == n) - xbt_dynar_cursor_rm(g->nodes, &cursor); + if (node == n) + xbt_dynar_cursor_rm(g->nodes, &cursor); xbt_dynar_free(&(n->in)); xbt_dynar_free(&(n->out)); @@ -203,7 +203,7 @@ void xbt_graph_free_node(xbt_graph_t g, xbt_node_t n, /** @brief remove the given edge from the given graph */ void xbt_graph_free_edge(xbt_graph_t g, xbt_edge_t e, - void_f_pvoid_t free_function) + void_f_pvoid_t free_function) { int idx; unsigned int cursor = 0; @@ -215,11 +215,11 @@ void xbt_graph_free_edge(xbt_graph_t g, xbt_edge_t e, xbt_dynar_foreach(g->edges, cursor, edge) { if (edge == e) { if (g->directed) { - idx = __xbt_find_in_dynar(edge->dst->in, edge); - xbt_dynar_remove_at(edge->dst->in, idx, NULL); + idx = __xbt_find_in_dynar(edge->dst->in, edge); + xbt_dynar_remove_at(edge->dst->in, idx, NULL); } else { /* only the out field is used */ - idx = __xbt_find_in_dynar(edge->dst->out, edge); - xbt_dynar_remove_at(edge->dst->out, idx, NULL); + idx = __xbt_find_in_dynar(edge->dst->out, edge); + xbt_dynar_remove_at(edge->dst->out, idx, NULL); } idx = __xbt_find_in_dynar(edge->src->out, edge); @@ -285,7 +285,7 @@ double xbt_graph_edge_get_length(xbt_edge_t e) /** @brief construct the adjacency matrix corresponding to the given graph - * + * * The weights are the distances between nodes */ double *xbt_graph_get_length_matrix(xbt_graph_t g) @@ -313,9 +313,9 @@ double *xbt_graph_get_length_matrix(xbt_graph_t g) xbt_dynar_foreach(node->out, in_cursor, edge) { if (edge->dst == node) - idx = __xbt_find_in_dynar(g->nodes, edge->src); + idx = __xbt_find_in_dynar(g->nodes, edge->src); else /*case of undirected graphs */ - idx = __xbt_find_in_dynar(g->nodes, edge->dst); + idx = __xbt_find_in_dynar(g->nodes, edge->dst); D(cursor, idx) = edge->length; } } @@ -326,9 +326,9 @@ double *xbt_graph_get_length_matrix(xbt_graph_t g) } /** @brief Floyd-Warshall algorithm for shortest path finding - * - * From wikipedia: - * + * + * From wikipedia: + * * The Floyd–Warshall algorithm takes as input an adjacency matrix * representation of a weighted, directed graph (V, E). The weight of a * path between two vertices is the sum of the weights of the edges along @@ -338,7 +338,7 @@ double *xbt_graph_get_length_matrix(xbt_graph_t g) * the two vertices. The running time complexity is Θ(|V|3). */ void xbt_floyd_algorithm(xbt_graph_t g, double *adj, double *d, - xbt_node_t * p) + xbt_node_t * p) { unsigned long i, j, k; unsigned long n; @@ -355,7 +355,7 @@ void xbt_floyd_algorithm(xbt_graph_t g, double *adj, double *d, for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { if (D(i, j) != -1) { - P(i, j) = *((xbt_node_t *) xbt_dynar_get_ptr(g->nodes, i)); + P(i, j) = *((xbt_node_t *) xbt_dynar_get_ptr(g->nodes, i)); } } } @@ -363,12 +363,12 @@ void xbt_floyd_algorithm(xbt_graph_t g, double *adj, double *d, for (k = 0; k < n; k++) { for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { - if ((D(i, k) != -1) && (D(k, j) != -1)) { - if ((D(i, j) == -1) || (D(i, j) > D(i, k) + D(k, j))) { - D(i, j) = D(i, k) + D(k, j); - P(i, j) = P(k, j); - } - } + if ((D(i, k) != -1) && (D(k, j) != -1)) { + if ((D(i, j) == -1) || (D(i, j) > D(i, k) + D(k, j))) { + D(i, j) = D(i, k) + D(k, j); + P(i, j) = P(k, j); + } + } } } } @@ -406,11 +406,11 @@ xbt_node_t *xbt_graph_shortest_paths(xbt_graph_t g) k = j; while ((P(i, k)) && (__xbt_find_in_dynar(g->nodes, P(i, k)) != i)) { - k = __xbt_find_in_dynar(g->nodes, P(i, k)); + k = __xbt_find_in_dynar(g->nodes, P(i, k)); } if (P(i, j)) { - R(i, j) = *((xbt_node_t *) xbt_dynar_get_ptr(g->nodes, k)); + R(i, j) = *((xbt_node_t *) xbt_dynar_get_ptr(g->nodes, k)); } } } @@ -436,7 +436,7 @@ xbt_edge_t *xbt_graph_spanning_tree_prim(xbt_graph_t g) unsigned int cursor; xbt_assert0(!(g->directed), - "Spanning trees do not make sense on directed graphs"); + "Spanning trees do not make sense on directed graphs"); xbt_dynar_foreach(g->nodes, cursor, node) { node->xbtdata = NULL; @@ -446,7 +446,7 @@ xbt_edge_t *xbt_graph_spanning_tree_prim(xbt_graph_t g) node->xbtdata = (void *) 1; edge_list = node->out; xbt_dynar_foreach(edge_list, cursor, e) - xbt_heap_push(heap, e, -(e->length)); + xbt_heap_push(heap, e, -(e->length)); while ((edge = xbt_heap_pop(heap))) { if ((edge->src->xbtdata) && (edge->dst->xbtdata)) @@ -456,13 +456,13 @@ xbt_edge_t *xbt_graph_spanning_tree_prim(xbt_graph_t g) edge->src->xbtdata = (void *) 1; edge_list = edge->src->out; xbt_dynar_foreach(edge_list, cursor, e) { - xbt_heap_push(heap, e, -(e->length)); + xbt_heap_push(heap, e, -(e->length)); } } else { edge->dst->xbtdata = (void *) 1; edge_list = edge->dst->out; xbt_dynar_foreach(edge_list, cursor, e) { - xbt_heap_push(heap, e, -(e->length)); + xbt_heap_push(heap, e, -(e->length)); } } if (tree_size == tree_size_max) @@ -474,10 +474,10 @@ xbt_edge_t *xbt_graph_spanning_tree_prim(xbt_graph_t g) return tree; } -/** @brief Topological sort on the given graph +/** @brief Topological sort on the given graph * * From wikipedia: - * + * * In graph theory, a topological sort of a directed acyclic graph (DAG) is * a linear ordering of its nodes which is compatible with the partial * order R induced on the nodes where x comes before y (xRy) if there's a @@ -500,10 +500,10 @@ xbt_node_t *xbt_graph_topo_sort(xbt_graph_t g) sorted = xbt_malloc(n * sizeof(xbt_node_t)); xbt_dynar_foreach(g->nodes, cursor, node) - node->xbtdata = xbt_new0(int, 1); + node->xbtdata = xbt_new0(int, 1); xbt_dynar_foreach(g->nodes, cursor, node) - xbt_graph_depth_visit(g, node, sorted, &idx); + xbt_graph_depth_visit(g, node, sorted, &idx); xbt_dynar_foreach(g->nodes, cursor, node) { free(node->xbtdata); @@ -515,7 +515,7 @@ xbt_node_t *xbt_graph_topo_sort(xbt_graph_t g) /** @brief First-depth graph traversal */ void xbt_graph_depth_visit(xbt_graph_t g, xbt_node_t n, - xbt_node_t * sorted, int *idx) + xbt_node_t * sorted, int *idx) { unsigned int cursor; xbt_edge_t edge; @@ -541,9 +541,9 @@ static xbt_graph_t parsed_graph = NULL; static xbt_dict_t parsed_nodes = NULL; static void *(*__parse_node_label_and_data) (xbt_node_t, const char *, - const char *) = NULL; + const char *) = NULL; static void *(*__parse_edge_label_and_data) (xbt_edge_t, const char *, - const char *) = NULL; + const char *) = NULL; static void __parse_graph_begin(void) { @@ -569,11 +569,11 @@ static void __parse_node(void) DEBUG1("", A_graphxml_node_name); if (__parse_node_label_and_data) node->data = __parse_node_label_and_data(node, A_graphxml_node_label, - A_graphxml_node_data); + A_graphxml_node_data); xbt_graph_parse_get_double(&(node->position_x), - A_graphxml_node_position_x); + A_graphxml_node_position_x); xbt_graph_parse_get_double(&(node->position_y), - A_graphxml_node_position_y); + A_graphxml_node_position_y); xbt_dict_set(parsed_nodes, A_graphxml_node_name, (void *) node, NULL); } @@ -581,31 +581,31 @@ static void __parse_node(void) static void __parse_edge(void) { xbt_edge_t edge = xbt_graph_new_edge(parsed_graph, - xbt_dict_get(parsed_nodes, - A_graphxml_edge_source), - xbt_dict_get(parsed_nodes, - A_graphxml_edge_target), - NULL); + xbt_dict_get(parsed_nodes, + A_graphxml_edge_source), + xbt_dict_get(parsed_nodes, + A_graphxml_edge_target), + NULL); if (__parse_edge_label_and_data) edge->data = __parse_edge_label_and_data(edge, A_graphxml_edge_label, - A_graphxml_edge_data); + A_graphxml_edge_data); xbt_graph_parse_get_double(&(edge->length), A_graphxml_edge_length); DEBUG3("", - (char *) (edge->src)->data, - (char *) (edge->dst)->data, xbt_graph_edge_get_length(edge)); + (char *) (edge->src)->data, + (char *) (edge->dst)->data, xbt_graph_edge_get_length(edge)); } /** @brief Import a graph from a file following the GraphXML format */ xbt_graph_t xbt_graph_read(const char *filename, - void *(*node_label_and_data) (xbt_node_t, - const char *, - const char *), - void *(*edge_label_and_data) (xbt_edge_t, - const char *, - const char *)) + void *(*node_label_and_data) (xbt_node_t, + const char *, + const char *), + void *(*edge_label_and_data) (xbt_edge_t, + const char *, + const char *)) { xbt_graph_t graph = NULL; @@ -632,8 +632,8 @@ xbt_graph_t xbt_graph_read(const char *filename, /** @brief Export the given graph in the GraphViz formatting for visualization */ void xbt_graph_export_graphviz(xbt_graph_t g, const char *filename, - const char *(node_name) (xbt_node_t), - const char *(edge_name) (xbt_edge_t)) + const char *(node_name) (xbt_node_t), + const char *(edge_name) (xbt_edge_t)) { unsigned int cursor = 0; xbt_node_t node = NULL; @@ -653,7 +653,7 @@ void xbt_graph_export_graphviz(xbt_graph_t g, const char *filename, fprintf(file, " node [shape=box, style=filled]\n"); fprintf(file, - " node [width=.3, height=.3, style=filled, color=skyblue]\n\n"); + " node [width=.3, height=.3, style=filled, color=skyblue]\n\n"); xbt_dynar_foreach(g->nodes, cursor, node) { fprintf(file, " \"%p\" ", node); @@ -676,10 +676,10 @@ void xbt_graph_export_graphviz(xbt_graph_t g, const char *filename, /** @brief Export the given graph in the GraphXML format */ void xbt_graph_export_graphxml(xbt_graph_t g, const char *filename, - const char *(node_name) (xbt_node_t), - const char *(edge_name) (xbt_edge_t), - const char *(node_data_print) (void *), - const char *(edge_data_print) (void *)) + const char *(node_name) (xbt_node_t), + const char *(edge_name) (xbt_edge_t), + const char *(node_data_print) (void *), + const char *(edge_data_print) (void *)) { unsigned int cursor = 0; xbt_node_t node = NULL; @@ -706,7 +706,7 @@ void xbt_graph_export_graphxml(xbt_graph_t g, const char *filename, } xbt_dynar_foreach(g->edges, cursor, edge) { fprintf(file, " src, edge->dst); + edge->src, edge->dst); if ((edge_name) && ((name = edge_name(edge)))) fprintf(file, "label=\"%s\" ", name); if (edge->length >= 0.0) diff --git a/src/xbt/graphxml_parse.c b/src/xbt/graphxml_parse.c index b03c09757a..5768ea0268 100644 --- a/src/xbt/graphxml_parse.c +++ b/src/xbt/graphxml_parse.c @@ -85,9 +85,9 @@ void xbt_graph_parse_open(const char *file) { WARN0("I hope you know what you're doing... you just gave me a NULL pointer!"); return; } - if(!xbt_graph_input_buffer_stack) + if(!xbt_graph_input_buffer_stack) xbt_graph_input_buffer_stack = xbt_dynar_new(sizeof(YY_BUFFER_STATE),NULL); - if(!xbt_graph_file_to_parse_stack) + if(!xbt_graph_file_to_parse_stack) xbt_graph_file_to_parse_stack = xbt_dynar_new(sizeof(FILE*),NULL); xbt_graph_file_to_parse = fopen(file,"r"); /* FIXME should use something like surf_fopen */ @@ -98,9 +98,9 @@ void xbt_graph_parse_open(const char *file) { } void xbt_graph_parse_close(void) { - if(xbt_graph_input_buffer_stack) + if(xbt_graph_input_buffer_stack) xbt_dynar_free(&xbt_graph_input_buffer_stack); - if(xbt_graph_file_to_parse_stack) + if(xbt_graph_file_to_parse_stack) xbt_dynar_free(&xbt_graph_file_to_parse_stack); if(xbt_graph_file_to_parse) { @@ -118,11 +118,11 @@ static int _xbt_graph_parse(void) int_f_void_t xbt_graph_parse = _xbt_graph_parse; void xbt_graph_parse_get_double(double *value,const char *string) -{ +{ int ret = 0; ret = sscanf(string, "%lg", value); xbt_assert2((ret==1), "Parse error line %d : %s not a number", xbt_graph_parse_lineno, - string); + string); } diff --git a/src/xbt/heap.c b/src/xbt/heap.c index 243e9c3212..8423b0cc54 100644 --- a/src/xbt/heap.c +++ b/src/xbt/heap.c @@ -14,7 +14,7 @@ #include -/** @addtogroup XBT_heap +/** @addtogroup XBT_heap * \brief This section describes the API to generic heap with O(log(n)) access. */ @@ -71,21 +71,21 @@ int xbt_heap_size(xbt_heap_t H) */ void xbt_heap_push(xbt_heap_t H, void *content, double key) { - int count = ++(H->count); - - int size = H->size; - xbt_heapItem_t item; - - if (count > size) { - H->size = 2 * size + 1; - H->items =(void *) realloc(H->items,(H->size) * sizeof(struct xbt_heapItem)); - } - - item = &(H->items[count - 1]); - item->key = key; - item->content = content; - xbt_heap_increaseKey(H, count - 1); - return; + int count = ++(H->count); + + int size = H->size; + xbt_heapItem_t item; + + if (count > size) { + H->size = 2 * size + 1; + H->items =(void *) realloc(H->items,(H->size) * sizeof(struct xbt_heapItem)); + } + + item = &(H->items[count - 1]); + item->key = key; + item->content = content; + xbt_heap_increaseKey(H, count - 1); + return; } /** @@ -112,8 +112,8 @@ void *xbt_heap_pop(xbt_heap_t H) if (H->count < H->size / 4 && H->size > 16) { H->size = H->size / 2 + 1; H->items = - (void *) realloc(H->items, - (H->size) * sizeof(struct xbt_heapItem)); + (void *) realloc(H->items, + (H->size) * sizeof(struct xbt_heapItem)); } return max; } @@ -145,7 +145,7 @@ void *xbt_heap_maxcontent(xbt_heap_t H) /* <<<< private >>>> * \param H the heap we're working on - * + * * Restores the heap property once an element has been deleted. */ static void xbt_heap_maxHeapify(xbt_heap_t H) @@ -173,7 +173,7 @@ static void xbt_heap_maxHeapify(xbt_heap_t H) /* <<<< private >>>> * \param H the heap we're working on * \param i an item position in the heap - * + * * Moves up an item at position i to its correct position. Works only * when called from xbt_heap_push. Do not use otherwise. */ diff --git a/src/xbt/log.c b/src/xbt/log.c index 54a1691f82..adc1fdf198 100644 --- a/src/xbt/log.c +++ b/src/xbt/log.c @@ -28,11 +28,11 @@ XBT_PUBLIC_DATA(int) (*xbt_pid)(); /** \addtogroup XBT_log * - * This section describes the API to the log functions used + * This section describes the API to the log functions used * everywhere in this project. \section XBT_log_toc Table of contents - + - \ref log_overview - \ref log_cat - \ref log_pri @@ -56,26 +56,26 @@ XBT_PUBLIC_DATA(int) (*xbt_pid)(); - \ref log_in_perf - \ref log_in_app - \ref XBT_log_cats - + \section log_overview 1. Introduction This module is in charge of handling the log messages of every SimGrid program. The main design goal are: - - configurability: the user can choose at runtime what messages to show and + - configurability: the user can choose at runtime what messages to show and what to hide, as well as how messages get displayed. - ease of use: both to the programmer (using preprocessor macros black magic) and to the user (with command line options) - performances: logging shouldn't slow down the program when turned off, for example - - deal with distributed settings: SimGrid programs are [often] distributed ones, + - deal with distributed settings: SimGrid programs are [often] distributed ones, and the logging mecanism allows to syndicate each and every log source into the same place. At least, its design would allow to, once we write the last missing pieces - + There is three main concepts in SimGrid's logging mecanism: category, priority and appender. These three concepts work together to enable developers to log messages according to message type and priority, and to control at runtime how these messages are formatted and where they are -reported. +reported. \subsection log_cat 1.1 Category hierarchy @@ -83,8 +83,8 @@ The first and foremost advantage of any logging API over plain printf() resides in its ability to disable certain log statements while allowing others to print unhindered. This capability assumes that the logging space, that is, the space of all possible logging statements, is categorized -according to some developer-chosen criteria. - +according to some developer-chosen criteria. + This observation led to choosing category as the central concept of the system. In a certain sense, they can be considered as logging topics or channels. @@ -94,7 +94,7 @@ channels. The user can naturally declare interest into this or that logging category, but he also can specify the desired level of details for each of them. This is controled by the priority concept (which should maybe be renamed to -severity). +severity). Empirically, the user can specify that he wants to see every debuging message of GRAS while only being interested into the messages at level "error" or @@ -114,10 +114,10 @@ One day, for sure ;) The message layouts are the elements in charge of choosing how each message will look like. Their result is a string which is then passed to the appender -attached to the category to be displayed. +attached to the category to be displayed. For now, there is two layouts: The simple one, which is good for most cases, -and another one allowing users to specify the format they want. +and another one allowing users to specify the format they want. \ref log_use_conf provides more info on this. \subsection log_hist 1.5 History of this module @@ -135,8 +135,8 @@ is not object oriented. Every category is declared by providing a name and an optional parent. If no parent is explicitly named, the root category, LOG_ROOT_CAT is -the category's parent. - +the category's parent. + A category is created by a macro call at the top level of a file. A category can be created with any one of the following macros: @@ -149,12 +149,12 @@ category can be created with any one of the following macros: - \ref XBT_LOG_NEW_DEFAULT_SUBCATEGORY(MyCat, ParentCat,desc); Like XBT_LOG_NEW_SUBCATEGORY, but the new category is the default one in this file - + The parent cat can be defined in the same file or in another file (in which case you want to use the \ref XBT_LOG_EXTERNAL_CATEGORY macro to make it visible in the current file), but each category may have only one definition. - + Typically, there will be a Category for each module and sub-module, so you can independently control logging for each module. @@ -167,7 +167,7 @@ it should be complete and accurate. A category may be assigned a threshold priorty. The set of priorites are defined by the \ref e_xbt_log_priority_t enum. All logging request under this priority will be discarded. - + If a given category is not assigned a threshold priority, then it inherits one from its closest ancestor with an assigned threshold. To ensure that all categories can eventually inherit a threshold, the root category always has @@ -182,7 +182,7 @@ format. This is usualy a good idea. Because some C compilers do not support vararg macros, there is a version of the macro for any number of arguments from 0 to 6. The macro name ends with the total number of arguments. - + Here is an example of the most basic type of macro. This is a logging request with priority warning. @@ -192,8 +192,8 @@ request with priority warning. A logging request is said to be enabled if its priority is higher than or equal to the threshold priority of its category. Otherwise, the request is said to be disabled. A category without an assigned priority will inherit -one from the hierarchy. - +one from the hierarchy. + It is possible to use any non-negative integer as a priority. If, as in the example, one of the standard priorites is used, then there is a convenience macro that is typically used instead. For example, the above example is @@ -207,12 +207,12 @@ It is sometimes useful to check whether a perticular category is enabled at a perticular priority. One example is when you want to do some extra computation to prepare a nice debugging message. There is no use of doing so if the message won't be used afterward because -debugging is turned off. - +debugging is turned off. + Doing so is extremely easy, thanks to the XBT_LOG_ISENABLED(category, priority). \section log_API_subcat 2.4 Using a default category (the easy interface) - + If \ref XBT_LOG_NEW_DEFAULT_SUBCATEGORY(MyCat, Parent) or \ref XBT_LOG_NEW_DEFAULT_CATEGORY(MyCat) is used to create the category, then the even shorter form can be used: @@ -236,7 +236,7 @@ This is because we want SimGrid itself to keep compilable on ancient compiler not supporting variable number of arguments to macros. But we should provide a macro simpler to use for the users not interested in SP3 machines (FIXME). - + Under GCC, these macro check there arguments the same way than printf does. So, if you compile with -Wall, the folliwing code will issue a warning: DEBUG2("Found %s (id %f)", some_string, a_double) @@ -245,7 +245,7 @@ If you want to specify the category to log onto (for example because you have more than one category per file, add a C before the name of the log producing macro (ie, use #CDEBUG10, #CVERB10, #CINFO10, #CWARN10, #CERROR10 and #CCRITICAL10 and friends), and pass the category name as first argument. - + The TRACE priority is not used the same way than the other. You should use the #XBT_IN, XBT_IN (up to #XBT_IN5), #XBT_OUT and #XBT_HERE macros instead. @@ -276,11 +276,11 @@ int main() { INFO1("Located nearest gas station."); / * This request is disabled, because DEBUG < INFO. * / - DEBUG1("Exiting gas station search"); + DEBUG1("Exiting gas station search"); } \endverbatim -Another example can be found in the relevant part of the GRAS tutorial: +Another example can be found in the relevant part of the GRAS tutorial: \ref GRAS_tut_tour_logs. \section log_user 3. User interface @@ -292,13 +292,13 @@ program initialization by invoking the xbt_log_control_set() method manually. A more conventionnal way is to use the --log command line argument. xbt_init() (called by MSG_init(), gras_init() and friends) checks and deals properly with such arguments. - + The following command line arguments exist, but are deprecated and may disapear in the future: --xbt-log, --gras-log, --msg-log and --surf-log. - + \subsection log_use_conf_thres 3.1.1 Thresold configuration - + The most common setting is to control which logging event will get displayed by setting a threshold to each category through the thres keyword. @@ -310,15 +310,15 @@ completely off. \subsection log_use_conf_multi 3.1.2 Passing several settings -You can provide several of those arguments to change the setting of several +You can provide several of those arguments to change the setting of several categories, they will be applied from left to right. So, \verbatim --log="root.thres:debug root.thres:critical"\endverbatim should disable almost any logging. - + Note that the quotes on above line are mandatory because there is a space in the argument, so we are protecting ourselves from the shell, not from SimGrid. We could also reach the same effect with this: -\verbatim --log=root.thres:debug --log=root.thres:critical\endverbatim +\verbatim --log=root.thres:debug --log=root.thres:critical\endverbatim \subsection log_use_conf_fmt 3.1.3 Format configuration @@ -347,13 +347,13 @@ Here are the existing format directives: - %%F: file name where the log event was raised (LOG4J compliant) - %%l: location where the log event was raised (LOG4J compliant, like '%%F:%%L' -- this is a l as in 'l'etter) - %%L: line number where the log event was raised (LOG4J compliant) - - %%M: function name (LOG4J compliant -- called method name here of course). + - %%M: function name (LOG4J compliant -- called method name here of course). Defined only when using gcc because there is no __FUNCTION__ elsewhere. - - %%b: full backtrace (Called %%throwable in LOG4J). - Defined only when using the GNU libc because backtrace() is not defined + - %%b: full backtrace (Called %%throwable in LOG4J). + Defined only when using the GNU libc because backtrace() is not defined elsewhere. - - %%B: short backtrace (only the first line of the %%b). + - %%B: short backtrace (only the first line of the %%b). Called %%throwable{short} in LOG4J; defined where %%b is. - %%d: date (UNIX-like epoch) @@ -410,8 +410,8 @@ requests are statically disabled and cost nothing. Released executables might be compiled with (note that it will prevent users to debug their problems) \verbatim-DXBT_LOG_STATIC_THRESHOLD=gras_log_priority_infinite\endverbatim -Compiling with the \verbatim-DNLOG\endverbatim option disables all logging -requests at compilation time while the \verbatim-DNDEBUG\endverbatim disables +Compiling with the \verbatim-DNLOG\endverbatim option disables all logging +requests at compilation time while the \verbatim-DNDEBUG\endverbatim disables the requests of priority below INFO. \todo Logging performance *may* be improved further by improving the message @@ -429,9 +429,9 @@ category performs the following actions: - if the category has an appender, the message is passed to the appender's doAppend() function, - if additivity is true for the category (which is the case by - default, and can be controlled by xbt_log_additivity_set()), the - message is passed to the category's parent. - + default, and can be controlled by xbt_log_additivity_set()), the + message is passed to the category's parent. + By default, only the root category have an appender, and any other category has its additivity set to true. This causes all messages to be logged by the root category's appender. @@ -443,7 +443,7 @@ This is on our TODO list for quite a while now, but your help would be welcome here, too. -*//*'*/ + *//*'*/ xbt_log_appender_t xbt_log_default_appender = NULL; /* set in log_init */ @@ -469,25 +469,25 @@ static void _free_setting(void *s) { } } static void _xbt_log_cat_apply_set(xbt_log_category_t category, - xbt_log_setting_t setting); + xbt_log_setting_t setting); const char *xbt_log_priority_names[8] = { - "NONE", - "TRACE", - "DEBUG", - "VERBOSE", - "INFO", - "WARNING", - "ERROR", - "CRITICAL" + "NONE", + "TRACE", + "DEBUG", + "VERBOSE", + "INFO", + "WARNING", + "ERROR", + "CRITICAL" }; s_xbt_log_category_t _XBT_LOGV(XBT_LOG_ROOT_CAT) = { - NULL /*parent*/, NULL /* firstChild */, NULL /* nextSibling */, - "root", xbt_log_priority_uninitialized /* threshold */, - 0 /* isThreshInherited */, - NULL /* appender */, NULL /* layout */, - 0 /* additivity */ + NULL /*parent*/, NULL /* firstChild */, NULL /* nextSibling */, + "root", xbt_log_priority_uninitialized /* threshold */, + 0 /* isThreshInherited */, + NULL /* appender */, NULL /* layout */, + 0 /* additivity */ }; XBT_LOG_NEW_CATEGORY(xbt,"All XBT categories (simgrid toolbox)"); @@ -498,51 +498,51 @@ XBT_LOG_NEW_CATEGORY(simix,"All SIMIX categories"); XBT_LOG_NEW_DEFAULT_SUBCATEGORY(log,xbt,"Loggings from the logging mechanism itself"); /** @brief Get all logging settings from the command line - * + * * xbt_log_control_set() is called on each string we got from cmd line */ void xbt_log_init(int *argc,char **argv) { - int i,j; - char *opt; - - /* create the default appender and install it in the root category, + int i,j; + char *opt; + + /* create the default appender and install it in the root category, which were already created (damnit. Too slow little beetle)*/ - xbt_log_default_appender = xbt_log_appender_file_new(NULL); - xbt_log_default_layout = xbt_log_layout_simple_new(NULL); - _XBT_LOGV(XBT_LOG_ROOT_CAT).appender = xbt_log_default_appender; - _XBT_LOGV(XBT_LOG_ROOT_CAT).layout = xbt_log_default_layout; - _log_usable = 1; - -// _XBT_LOGV(log).threshold = xbt_log_priority_debug; /* uncomment to set the LOG category to debug directly */ - - /* Set logs and init log submodule */ - for (i=1; i<*argc; i++){ - if (!strncmp(argv[i],"--log=",strlen("--log=")) || - !strncmp(argv[i],"--gras-log=",strlen("--gras-log=")) || - !strncmp(argv[i],"--surf-log=",strlen("--surf-log=")) || - !strncmp(argv[i],"--msg-log=",strlen("--msg-log=")) || - !strncmp(argv[i],"--simix-log=",strlen("--simix-log=")) || - !strncmp(argv[i],"--xbt-log=",strlen("--xbt-log="))){ - - if (strncmp(argv[i],"--log=",strlen("--log="))) - WARN2("Option %.*s is deprecated and will disapear in the future. Use --log instead.", - (int)(strchr(argv[i],'=')-argv[i]),argv[i]); - - opt=strchr(argv[i],'='); - opt++; - xbt_log_control_set(opt); - DEBUG1("Did apply '%s' as log setting",opt); - /*remove this from argv*/ - - for (j=i+1; j<*argc; j++){ - argv[j-1] = argv[j]; - } - - argv[j-1] = NULL; - (*argc)--; - i--; /* compensate effect of next loop incrementation */ - } - } + xbt_log_default_appender = xbt_log_appender_file_new(NULL); + xbt_log_default_layout = xbt_log_layout_simple_new(NULL); + _XBT_LOGV(XBT_LOG_ROOT_CAT).appender = xbt_log_default_appender; + _XBT_LOGV(XBT_LOG_ROOT_CAT).layout = xbt_log_default_layout; + _log_usable = 1; + + // _XBT_LOGV(log).threshold = xbt_log_priority_debug; /* uncomment to set the LOG category to debug directly */ + + /* Set logs and init log submodule */ + for (i=1; i<*argc; i++){ + if (!strncmp(argv[i],"--log=",strlen("--log=")) || + !strncmp(argv[i],"--gras-log=",strlen("--gras-log=")) || + !strncmp(argv[i],"--surf-log=",strlen("--surf-log=")) || + !strncmp(argv[i],"--msg-log=",strlen("--msg-log=")) || + !strncmp(argv[i],"--simix-log=",strlen("--simix-log=")) || + !strncmp(argv[i],"--xbt-log=",strlen("--xbt-log="))){ + + if (strncmp(argv[i],"--log=",strlen("--log="))) + WARN2("Option %.*s is deprecated and will disapear in the future. Use --log instead.", + (int)(strchr(argv[i],'=')-argv[i]),argv[i]); + + opt=strchr(argv[i],'='); + opt++; + xbt_log_control_set(opt); + DEBUG1("Did apply '%s' as log setting",opt); + /*remove this from argv*/ + + for (j=i+1; j<*argc; j++){ + argv[j-1] = argv[j]; + } + + argv[j-1] = NULL; + (*argc)--; + i--; /* compensate effect of next loop incrementation */ + } + } } static void log_cat_exit(xbt_log_category_t cat) { @@ -557,9 +557,9 @@ static void log_cat_exit(xbt_log_category_t cat) { if (cat->layout->free_) cat->layout->free_(cat->layout); free(cat->layout); - } + } - for(child=cat->firstChild ; child != NULL; child = child->nextSibling) + for(child=cat->firstChild ; child != NULL; child = child->nextSibling) log_cat_exit(child); } @@ -571,17 +571,17 @@ void xbt_log_exit(void) { } void _xbt_log_event_log( xbt_log_event_t ev, const char *fmt, ...) { - + xbt_log_category_t cat = ev->cat; if (!_log_usable) { - /* Make sure that the layouts have been malloced */ - xbt_log_default_appender = xbt_log_appender_file_new(NULL); - xbt_log_default_layout = xbt_log_layout_simple_new(NULL); - _XBT_LOGV(XBT_LOG_ROOT_CAT).appender = xbt_log_default_appender; - _XBT_LOGV(XBT_LOG_ROOT_CAT).layout = xbt_log_default_layout; - _log_usable = 1; + /* Make sure that the layouts have been malloced */ + xbt_log_default_appender = xbt_log_appender_file_new(NULL); + xbt_log_default_layout = xbt_log_layout_simple_new(NULL); + _XBT_LOGV(XBT_LOG_ROOT_CAT).appender = xbt_log_default_appender; + _XBT_LOGV(XBT_LOG_ROOT_CAT).layout = xbt_log_default_layout; + _log_usable = 1; } - + va_start(ev->ap, fmt); va_start(ev->ap_copy, fmt); while(1) { @@ -594,80 +594,80 @@ void _xbt_log_event_log( xbt_log_event_t ev, const char *fmt, ...) { break; cat = cat->parent; - } + } va_end(ev->ap); va_end(ev->ap_copy); - - #ifdef WIN32 + +#ifdef WIN32 free(ev->buffer); - #endif +#endif } static void _xbt_log_cat_apply_set(xbt_log_category_t category, - xbt_log_setting_t setting) { + xbt_log_setting_t setting) { s_xbt_log_event_t _log_ev; if (setting->thresh != xbt_log_priority_uninitialized) { xbt_log_threshold_set(category, setting->thresh); - + if (category->threshold <= xbt_log_priority_debug) { _log_ev.cat = category; _log_ev.priority = xbt_log_priority_debug; _log_ev.fileName = __FILE__ ; _log_ev.functionName = _XBT_FUNCTION ; _log_ev.lineNum = __LINE__ ; - + _xbt_log_event_log(&_log_ev, - "Apply settings for category '%s': set threshold to %s (=%d)", - category->name, - xbt_log_priority_names[category->threshold], - category->threshold); + "Apply settings for category '%s': set threshold to %s (=%d)", + category->name, + xbt_log_priority_names[category->threshold], + category->threshold); } } if (setting->fmt) { xbt_log_layout_set(category,xbt_log_layout_format_new(setting->fmt)); - + if (category->threshold <= xbt_log_priority_debug) { _log_ev.cat = category; _log_ev.priority = xbt_log_priority_debug; _log_ev.fileName = __FILE__ ; _log_ev.functionName = _XBT_FUNCTION ; _log_ev.lineNum = __LINE__ ; - + _xbt_log_event_log(&_log_ev, - "Apply settings for category '%s': set format to %s", - category->name, - setting->fmt); + "Apply settings for category '%s': set format to %s", + category->name, + setting->fmt); } } if (setting->additivity != -1) { xbt_log_additivity_set(category,setting->additivity); - + if (category->threshold <= xbt_log_priority_debug) { _log_ev.cat = category; _log_ev.priority = xbt_log_priority_debug; _log_ev.fileName = __FILE__ ; _log_ev.functionName = _XBT_FUNCTION ; _log_ev.lineNum = __LINE__ ; - + _xbt_log_event_log(&_log_ev, - "Apply settings for category '%s': set additivity to %s", - category->name, - (setting->additivity?"on":"off")); + "Apply settings for category '%s': set additivity to %s", + category->name, + (setting->additivity?"on":"off")); } } } /* * This gets called the first time a category is referenced and performs the - * initialization. + * initialization. * Also resets threshold to inherited! */ int _xbt_log_cat_init(xbt_log_category_t category, - e_xbt_log_priority_t priority) { + e_xbt_log_priority_t priority) { unsigned int cursor; xbt_log_setting_t setting=NULL; int found = 0; @@ -675,17 +675,17 @@ int _xbt_log_cat_init(xbt_log_category_t category, if (_XBT_LOGV(log).threshold <= xbt_log_priority_debug && _XBT_LOGV(log).threshold != xbt_log_priority_uninitialized) { - _log_ev.cat = &_XBT_LOGV(log); - _log_ev.priority = xbt_log_priority_debug; - _log_ev.fileName = __FILE__ ; - _log_ev.functionName = _XBT_FUNCTION ; - _log_ev.lineNum = __LINE__ ; - _xbt_log_event_log(&_log_ev, "Initializing category '%s' (firstChild=%s, nextSibling=%s)", - category->name, - (category->firstChild ?category->firstChild->name :"none"), - (category->nextSibling?category->nextSibling->name:"none")); + _log_ev.cat = &_XBT_LOGV(log); + _log_ev.priority = xbt_log_priority_debug; + _log_ev.fileName = __FILE__ ; + _log_ev.functionName = _XBT_FUNCTION ; + _log_ev.lineNum = __LINE__ ; + _xbt_log_event_log(&_log_ev, "Initializing category '%s' (firstChild=%s, nextSibling=%s)", + category->name, + (category->firstChild ?category->firstChild->name :"none"), + (category->nextSibling?category->nextSibling->name:"none")); } - + if(category == &_XBT_LOGV(XBT_LOG_ROOT_CAT)){ category->threshold = xbt_log_priority_info;/* xbt_log_priority_debug*/; category->appender = xbt_log_default_appender; @@ -694,154 +694,154 @@ int _xbt_log_cat_init(xbt_log_category_t category, if (!category->parent) category->parent = &_XBT_LOGV(XBT_LOG_ROOT_CAT); - + if (_XBT_LOGV(log).threshold <= xbt_log_priority_debug - && _XBT_LOGV(log).threshold != xbt_log_priority_uninitialized) { - _log_ev.lineNum = __LINE__ ; - _xbt_log_event_log(&_log_ev, "Set %s (%s) as father of %s ", category->parent->name, - (category->parent->threshold == xbt_log_priority_uninitialized ? "uninited":xbt_log_priority_names[category->parent->threshold]), - category->name); - } + && _XBT_LOGV(log).threshold != xbt_log_priority_uninitialized) { + _log_ev.lineNum = __LINE__ ; + _xbt_log_event_log(&_log_ev, "Set %s (%s) as father of %s ", category->parent->name, + (category->parent->threshold == xbt_log_priority_uninitialized ? "uninited":xbt_log_priority_names[category->parent->threshold]), + category->name); + } xbt_log_parent_set(category, category->parent); - + if (_XBT_LOGV(log).threshold < xbt_log_priority_info - && _XBT_LOGV(log).threshold != xbt_log_priority_uninitialized) { - char *buf,*res=NULL; - xbt_log_category_t cpp = category->parent->firstChild; - while (cpp) { - if (res) { - buf = bprintf("%s %s",res,cpp->name); - free(res); - res = buf; - } else { - res = xbt_strdup(cpp->name); - } - cpp = cpp->nextSibling; - } - - _log_ev.lineNum = __LINE__ ; - _xbt_log_event_log(&_log_ev, - "Childs of %s: %s; nextSibling: %s", category->parent->name,res, - (category->parent->nextSibling?category->parent->nextSibling->name:"none")); - - free(res); + && _XBT_LOGV(log).threshold != xbt_log_priority_uninitialized) { + char *buf,*res=NULL; + xbt_log_category_t cpp = category->parent->firstChild; + while (cpp) { + if (res) { + buf = bprintf("%s %s",res,cpp->name); + free(res); + res = buf; + } else { + res = xbt_strdup(cpp->name); + } + cpp = cpp->nextSibling; + } + + _log_ev.lineNum = __LINE__ ; + _xbt_log_event_log(&_log_ev, + "Childs of %s: %s; nextSibling: %s", category->parent->name,res, + (category->parent->nextSibling?category->parent->nextSibling->name:"none")); + + free(res); } - + } - /* Apply the control */ + /* Apply the control */ if (!xbt_log_settings) return priority >= category->threshold; - + xbt_assert0(category,"NULL category"); xbt_assert(category->name); - + xbt_dynar_foreach(xbt_log_settings,cursor,setting) { xbt_assert0(setting,"Damnit, NULL cat in the list"); xbt_assert1(setting->catname,"NULL setting(=%p)->catname",(void*)setting); - + if (!strcmp(setting->catname,category->name)) { - + found = 1; - + _xbt_log_cat_apply_set(category,setting); xbt_dynar_cursor_rm(xbt_log_settings,&cursor); } } - + if (!found && category->threshold <= xbt_log_priority_verbose) { - + _log_ev.cat = &_XBT_LOGV(log); _log_ev.priority = xbt_log_priority_verbose; _log_ev.fileName = __FILE__ ; _log_ev.functionName = _XBT_FUNCTION ; _log_ev.lineNum = __LINE__ ; - + _xbt_log_event_log(&_log_ev, - "Category '%s': inherited threshold = %s (=%d)", - category->name, - xbt_log_priority_names[category->threshold], category->threshold); + "Category '%s': inherited threshold = %s (=%d)", + category->name, + xbt_log_priority_names[category->threshold], category->threshold); } - + return priority >= category->threshold; } void xbt_log_parent_set(xbt_log_category_t cat,xbt_log_category_t parent) { - - xbt_assert0(cat,"NULL category to be given a parent"); - xbt_assert1(parent,"The parent category of %s is NULL",cat->name); - - /* - * if the threshold is initialized - * unlink from current parent - */ - if(cat->threshold != xbt_log_priority_uninitialized){ - - xbt_log_category_t* cpp = &parent->firstChild; - - while(*cpp != cat && *cpp != NULL) { - cpp = &(*cpp)->nextSibling; - } - - xbt_assert(*cpp == cat); - *cpp = cat->nextSibling; - } - - cat->parent = parent; - cat->nextSibling = parent->firstChild; - - parent->firstChild = cat; - - if (parent->threshold == xbt_log_priority_uninitialized){ - - _xbt_log_cat_init(parent, - xbt_log_priority_uninitialized/* ignored*/); - } - - cat->threshold = parent->threshold; - - cat->isThreshInherited = 1; - + + xbt_assert0(cat,"NULL category to be given a parent"); + xbt_assert1(parent,"The parent category of %s is NULL",cat->name); + + /* + * if the threshold is initialized + * unlink from current parent + */ + if(cat->threshold != xbt_log_priority_uninitialized){ + + xbt_log_category_t* cpp = &parent->firstChild; + + while(*cpp != cat && *cpp != NULL) { + cpp = &(*cpp)->nextSibling; + } + + xbt_assert(*cpp == cat); + *cpp = cat->nextSibling; + } + + cat->parent = parent; + cat->nextSibling = parent->firstChild; + + parent->firstChild = cat; + + if (parent->threshold == xbt_log_priority_uninitialized){ + + _xbt_log_cat_init(parent, + xbt_log_priority_uninitialized/* ignored*/); + } + + cat->threshold = parent->threshold; + + cat->isThreshInherited = 1; + } static void _set_inherited_thresholds(xbt_log_category_t cat) { - + xbt_log_category_t child = cat->firstChild; - + for( ; child != NULL; child = child->nextSibling) { if (child->isThreshInherited) { if (cat != &_XBT_LOGV(log)) - VERB3("Set category threshold of %s to %s (=%d)", - child->name,xbt_log_priority_names[cat->threshold],cat->threshold); + VERB3("Set category threshold of %s to %s (=%d)", + child->name,xbt_log_priority_names[cat->threshold],cat->threshold); child->threshold = cat->threshold; _set_inherited_thresholds(child); } } - - + + } void xbt_log_threshold_set(xbt_log_category_t cat, - e_xbt_log_priority_t threshold) { + e_xbt_log_priority_t threshold) { cat->threshold = threshold; cat->isThreshInherited = 0; - + _set_inherited_thresholds(cat); - + } static xbt_log_setting_t _xbt_log_parse_setting(const char* control_string) { xbt_log_setting_t set = xbt_new(s_xbt_log_setting_t,1); const char *name, *dot, *eq; - + set->catname=NULL; set->thresh = xbt_log_priority_uninitialized; set->fmt = NULL; set->additivity = -1; - if (!*control_string) + if (!*control_string) return set; DEBUG1("Parse log setting '%s'",control_string); @@ -854,50 +854,50 @@ static xbt_log_setting_t _xbt_log_parse_setting(const char* control_string) { control_string += strcspn(control_string, " "); xbt_assert1(*dot == '.' && (*eq == '=' || *eq == ':'), - "Invalid control string '%s'",control_string); + "Invalid control string '%s'",control_string); if (!strncmp(dot + 1, "thresh", (size_t)(eq - dot - 1))) { int i; char *neweq=xbt_strdup(eq+1); char *p=neweq-1; - + while (*(++p) != '\0') { if (*p >= 'a' && *p <= 'z') { - *p-='a'-'A'; + *p-='a'-'A'; } } - + DEBUG1("New priority name = %s",neweq); for (i=0; ithresh= (e_xbt_log_priority_t) i; } else { THROW1(arg_error,0, - "Unknown priority name: %s (must be one of: trace,debug,verbose,info,warning,error,critical)",eq+1); + "Unknown priority name: %s (must be one of: trace,debug,verbose,info,warning,error,critical)",eq+1); } free(neweq); } else if ( !strncmp(dot + 1, "add", (size_t)(eq - dot - 1)) || - !strncmp(dot + 1, "additivity", (size_t)(eq - dot - 1)) ) { + !strncmp(dot + 1, "additivity", (size_t)(eq - dot - 1)) ) { char *neweq=xbt_strdup(eq+1); char *p=neweq-1; - + while (*(++p) != '\0') { if (*p >= 'a' && *p <= 'z') { - *p-='a'-'A'; + *p-='a'-'A'; } } if ( !strcmp(neweq,"ON") || - !strcmp(neweq,"YES") || - !strcmp(neweq,"1") ) { - set->additivity = 1; + !strcmp(neweq,"YES") || + !strcmp(neweq,"1") ) { + set->additivity = 1; } else { - set->additivity = 0; + set->additivity = 0; } free(neweq); } else if (!strncmp(dot + 1, "fmt", (size_t)(eq - dot - 1))) { @@ -908,53 +908,53 @@ static xbt_log_setting_t _xbt_log_parse_setting(const char* control_string) { THROW1(arg_error,0,"Unknown setting of the log category: '%s'",buff); } set->catname=(char*)xbt_malloc(dot - name+1); - + memcpy(set->catname,name,dot-name); set->catname[dot-name]='\0'; /* Just in case */ DEBUG1("This is for cat '%s'", set->catname); - + return set; } static xbt_log_category_t _xbt_log_cat_searchsub(xbt_log_category_t cat,char *name) { xbt_log_category_t child,res; - + DEBUG4("Search '%s' into '%s' (firstChild='%s'; nextSibling='%s')",name,cat->name, - (cat->firstChild ? cat->firstChild->name :"none"), - (cat->nextSibling ? cat->nextSibling->name:"none")); - if (!strcmp(cat->name,name)) + (cat->firstChild ? cat->firstChild->name :"none"), + (cat->nextSibling ? cat->nextSibling->name:"none")); + if (!strcmp(cat->name,name)) return cat; for (child=cat->firstChild ; child != NULL; child = child->nextSibling) { - DEBUG1("Dig into %s",child->name); - res = _xbt_log_cat_searchsub(child,name); - if (res) - return res; + DEBUG1("Dig into %s",child->name); + res = _xbt_log_cat_searchsub(child,name); + if (res) + return res; } return NULL; } /** - * \ingroup XBT_log + * \ingroup XBT_log * \param control_string What to parse * * Typically passed a command-line argument. The string has the syntax: * * ( [category] "." [keyword] ":" value (" ")... )... * - * where [category] is one the category names (see \ref XBT_log_cats for - * a complete list of the ones defined in the SimGrid library) + * where [category] is one the category names (see \ref XBT_log_cats for + * a complete list of the ones defined in the SimGrid library) * and keyword is one of the following: * * - thres: category's threshold priority. Possible values: * TRACE,DEBUG,VERBOSE,INFO,WARNING,ERROR,CRITICAL - * - add or additivity: whether the logging actions must be passed to - * the parent category. + * - add or additivity: whether the logging actions must be passed to + * the parent category. * Possible values: 0, 1, no, yes, on, off. * Default value: yes. * - fmt: the format to use. See \ref log_lay for more information. - * + * */ void xbt_log_control_set(const char* control_string) { xbt_log_setting_t set; @@ -971,21 +971,21 @@ void xbt_log_control_set(const char* control_string) { /* some initialization if this is the first time that this get called */ if (xbt_log_settings == NULL) xbt_log_settings = xbt_dynar_new(sizeof(xbt_log_setting_t), - _free_setting); + _free_setting); /* split the string, and remove empty entries */ set_strings=xbt_str_split_quoted(control_string); if (xbt_dynar_length(set_strings) == 0) { /* vicious user! */ xbt_dynar_free(&set_strings); - return; + return; } /* Parse each entry and either use it right now (if the category was already created), or store it for further use */ xbt_dynar_foreach(set_strings,cpt,str) { xbt_log_category_t cat=NULL; - + set = _xbt_log_parse_setting(str); cat = _xbt_log_cat_searchsub(&_XBT_LOGV(XBT_LOG_ROOT_CAT),set->catname); @@ -1001,7 +1001,7 @@ void xbt_log_control_set(const char* control_string) { } } xbt_dynar_free(&set_strings); -} +} void xbt_log_appender_set(xbt_log_category_t cat, xbt_log_appender_t app) { if (cat->appender) { @@ -1014,11 +1014,11 @@ void xbt_log_appender_set(xbt_log_category_t cat, xbt_log_appender_t app) { void xbt_log_layout_set(xbt_log_category_t cat, xbt_log_layout_t lay) { if (!cat->appender) { VERB1("No appender to category %s. Setting the file appender as default", - cat->name); + cat->name); xbt_log_appender_set(cat,xbt_log_appender_file_new(NULL)); } if (cat->layout && cat != &_XBT_LOGV(root)) { - /* better leak the default layout than check every categories to + /* better leak the default layout than check every categories to change it */ if (cat->layout->free_) { cat->layout->free_(cat->layout); diff --git a/src/xbt/log_private.h b/src/xbt/log_private.h index 38533a1eef..17341d396f 100644 --- a/src/xbt/log_private.h +++ b/src/xbt/log_private.h @@ -11,29 +11,29 @@ #include "xbt/log.h" struct xbt_log_appender_s { void (*do_append) (xbt_log_appender_t this_appender, - char *event); + char *event); void (*free_) (xbt_log_appender_t this_); void *data; }; struct xbt_log_layout_s { void (*do_layout)(xbt_log_layout_t l, - xbt_log_event_t event, const char *fmt, - xbt_log_appender_t appender); + xbt_log_event_t event, const char *fmt, + xbt_log_appender_t appender); void (*free_) (xbt_log_layout_t l); void *data; } ; /** - * \ingroup XBT_log_implem + * \ingroup XBT_log_implem * \param cat the category (not only its name, but the variable) * \param parent the parent cat * * Programatically alter a category's parent (don't use). */ XBT_PUBLIC(void) xbt_log_parent_set(xbt_log_category_t cat, - xbt_log_category_t parent); + xbt_log_category_t parent); #endif /* LOG_PRIVATE_H */ diff --git a/src/xbt/mallocator.c b/src/xbt/mallocator.c index e274ce57e3..62c34ee884 100644 --- a/src/xbt/mallocator.c +++ b/src/xbt/mallocator.c @@ -22,7 +22,7 @@ XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_mallocator,xbt,"Mallocators"); * in \a xbt_mallocator_release() when the stack is full, and when * the mallocator is freed. * \param reset_f function to reinitialise an object of your datatype, called - * when you extract an object from the mallocator + * when you extract an object from the mallocator * * Create and initialize a new mallocator for a given datatype. * @@ -30,9 +30,9 @@ XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_mallocator,xbt,"Mallocators"); * \see xbt_mallocator_free() */ xbt_mallocator_t xbt_mallocator_new(int size, - pvoid_f_void_t new_f, - void_f_pvoid_t free_f, - void_f_pvoid_t reset_f) { + pvoid_f_void_t new_f, + void_f_pvoid_t free_f, + void_f_pvoid_t reset_f) { xbt_mallocator_t m; @@ -43,7 +43,7 @@ xbt_mallocator_t xbt_mallocator_new(int size, m = xbt_new0(s_xbt_mallocator_t, 1); VERB1("Create mallocator %p",m); if (XBT_LOG_ISENABLED(xbt_mallocator,xbt_log_priority_verbose)) - xbt_backtrace_display_current(); + xbt_backtrace_display_current(); m->objects = xbt_new0(void*, size); m->max_size = size; @@ -84,10 +84,10 @@ void xbt_mallocator_free(xbt_mallocator_t m) { * This function is designed to be used instead of malloc(). * If the mallocator is not empty, an object is * extracted from the mallocator and no malloc is done. - * + * * If the mallocator is empty, a new object is created, * by calling the function new_f(). - * + * * In both cases, the function reset_f() is called on the object. * * \see xbt_mallocator_release() diff --git a/src/xbt/set.c b/src/xbt/set.c index 25c8364723..dc96161659 100644 --- a/src/xbt/set.c +++ b/src/xbt/set.c @@ -17,7 +17,7 @@ #include "xbt/set.h" XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_set,xbt, - "set: data container consisting in dict+dynar"); + "set: data container consisting in dict+dynar"); /*####[ Type definition ]####################################################*/ typedef struct xbt_set_ { @@ -66,35 +66,35 @@ static int _xbt_set_get_id(xbt_set_t set) { return id; } -/** @brief Add an element to a set. +/** @brief Add an element to a set. * * \param set set to populate - * \param elm element to add. - * \param free_func How to add the data + * \param elm element to add. + * \param free_func How to add the data * * elm->name must be set; * if elm->name_len <= 0, it is recomputed. If >0, it's used as is; * elm->ID is attributed automatically. */ void xbt_set_add (xbt_set_t set, - xbt_set_elm_t elm, - void_f_pvoid_t free_func) { + xbt_set_elm_t elm, + void_f_pvoid_t free_func) { int found = 1; xbt_set_elm_t found_in_dict = NULL; xbt_ex_t e; VERB1("add %s to the set",elm->name); - + if (elm->name_len <= 0) { elm->name_len = strlen(elm->name); } TRY { - found_in_dict = xbt_dict_get_ext (set->dict, - elm->name, elm->name_len); + found_in_dict = xbt_dict_get_ext (set->dict, + elm->name, elm->name_len); } CATCH(e) { - if (e.category != not_found_error) + if (e.category != not_found_error) RETHROW; found = 0; elm->ID = _xbt_set_get_id(set); @@ -103,11 +103,11 @@ void xbt_set_add (xbt_set_t set, DEBUG2("Insertion of key '%s' (id %d)", elm->name, elm->ID); xbt_ex_free(e); } - + if (found) { if (elm == found_in_dict) { DEBUG2("Ignoring request to insert the same element twice (key %s ; id %d)", - elm->name, elm->ID); + elm->name, elm->ID); return; } else { elm->ID=found_in_dict->ID; @@ -119,7 +119,7 @@ void xbt_set_add (xbt_set_t set, } } -/** @brief Remove an element from a set. +/** @brief Remove an element from a set. * * \param set a set * \param elm element to remove @@ -132,7 +132,7 @@ void xbt_set_remove (xbt_set_t set, xbt_set_elm_t elm) { xbt_dynar_set(set->dynar, id, &elm); } -/** @brief Remove an element from a set providing its name. +/** @brief Remove an element from a set providing its name. * * \param set a set * \param key name of the element to remove @@ -143,7 +143,7 @@ void xbt_set_remove_by_name (xbt_set_t set, const char *key) { } /** @brief Remove an element from a set providing its name - * and the length of the name. + * and the length of the name. * * \param set a set * \param key name of the element to remove @@ -154,7 +154,7 @@ void xbt_set_remove_by_name_ext (xbt_set_t set, const char *key, int key_len) { xbt_set_remove(set, elm); } -/** @brief Remove an element from a set providing its id. +/** @brief Remove an element from a set providing its id. * * \param set a set * \param id id of the element to remove @@ -165,13 +165,13 @@ void xbt_set_remove_by_id (xbt_set_t set, int id) { } /** @brief Retrieve data by providing its name. - * + * * \param set * \param name Name of the searched cell * \returns the data you're looking for */ xbt_set_elm_t xbt_set_get_by_name (xbt_set_t set, - const char *name) { + const char *name) { DEBUG1("Lookup key %s",name); return xbt_dict_get(set->dict, name); } @@ -187,8 +187,8 @@ xbt_set_elm_t xbt_set_get_by_name (xbt_set_t set, * as name, you weirdo. */ xbt_set_elm_t xbt_set_get_by_name_ext(xbt_set_t set, - const char *name, - int name_len) { + const char *name, + int name_len) { return xbt_dict_get_ext (set->dict, name, name_len); } @@ -203,26 +203,26 @@ xbt_set_elm_t xbt_set_get_by_name_ext(xbt_set_t set, */ xbt_set_elm_t xbt_set_get_by_id (xbt_set_t set, int id) { xbt_set_elm_t res; - + /* Don't bother checking the bounds, the dynar does so */ res = xbt_dynar_get_as(set->dynar,id, xbt_set_elm_t); if (res == NULL) { THROW1(not_found_error, 0, "Invalid id: %d", id); } - DEBUG3("Lookup type of id %d (of %lu): %s", - id, xbt_dynar_length(set->dynar), res->name); - + DEBUG3("Lookup type of id %d (of %lu): %s", + id, xbt_dynar_length(set->dynar), res->name); + return res; } -/** +/** * \brief Returns the number of elements in the set * \param set a set * \return the number of elements in the set */ unsigned long xbt_set_length (const xbt_set_t set) { - return xbt_dynar_length(set->dynar); + return xbt_dynar_length(set->dynar); } /*** @@ -235,7 +235,7 @@ typedef struct xbt_set_cursor_ { /** @brief Create the cursor if it does not exists, rewind it in any case. */ void xbt_set_cursor_first (xbt_set_t set, - xbt_set_cursor_t *cursor) { + xbt_set_cursor_t *cursor) { xbt_dynar_t dynar; if (set != NULL) { @@ -243,7 +243,7 @@ void xbt_set_cursor_first (xbt_set_t set, DEBUG0("Create the cursor on first use"); *cursor = xbt_new(s_xbt_set_cursor_t,1); xbt_assert0(*cursor, - "Malloc error during the creation of the cursor"); + "Malloc error during the creation of the cursor"); } (*cursor)->set = set; @@ -266,15 +266,15 @@ void xbt_set_cursor_step (xbt_set_cursor_t cursor) { cursor->val++; } while (cursor->val < xbt_dynar_length(dynar) && - xbt_dynar_get_ptr(dynar, cursor->val) == NULL); + xbt_dynar_get_ptr(dynar, cursor->val) == NULL); } /** @brief Get current data - * + * * \return true if it's ok, false if there is no more data */ int xbt_set_cursor_get_or_free (xbt_set_cursor_t *curs, - xbt_set_elm_t *elm) { + xbt_set_elm_t *elm) { xbt_set_cursor_t cursor; if (!curs || !(*curs)) @@ -285,7 +285,7 @@ int xbt_set_cursor_get_or_free (xbt_set_cursor_t *curs, if (cursor->val >= xbt_dynar_length(cursor->set->dynar)) { free(cursor); *curs=NULL; - return FALSE; + return FALSE; } xbt_dynar_get_cpy(cursor->set->dynar, cursor->val, elm); @@ -320,8 +320,8 @@ static void my_elem_free(void *e) { } static void debuged_add(xbt_set_t set, - const char *name, - const char *data) { + const char *name, + const char *data) { my_elem_t elm; elm = xbt_new(s_my_elem_t,1); @@ -355,14 +355,14 @@ static void search_name(xbt_set_t head,const char*key) { xbt_test_add1("Search by name %s",key); elm = (my_elem_t)xbt_set_get_by_name(head,key); xbt_test_log2(" Found %s (under ID %d)\n", - elm? elm->data:"(null)", - elm? elm->ID:-1); + elm? elm->data:"(null)", + elm? elm->ID:-1); if (strcmp(key,elm->name)) THROW2(mismatch_error,0,"The key (%s) is not the one expected (%s)", - key,elm->name); + key,elm->name); if (strcmp(elm->name,elm->data)) THROW2(mismatch_error,0,"The name (%s) != data (%s)", - key,elm->name); + key,elm->name); fflush(stdout); } @@ -372,30 +372,30 @@ static void search_id(xbt_set_t head,int id,const char*key) { xbt_test_add1("Search by id %d",id); elm = (my_elem_t) xbt_set_get_by_id(head,id); xbt_test_log2("Found %s (data %s)", - elm? elm->name:"(null)", - elm? elm->data:"(null)"); + elm? elm->name:"(null)", + elm? elm->data:"(null)"); if (id != elm->ID) THROW2(mismatch_error,0,"The found ID (%d) is not the one expected (%d)", - elm->ID,id); + elm->ID,id); if (strcmp(key,elm->name)) THROW2(mismatch_error,0,"The key (%s) is not the one expected (%s)", - elm->name,key); + elm->name,key); if (strcmp(elm->name,elm->data)) THROW2(mismatch_error,0,"The name (%s) != data (%s)", - elm->name,elm->data); + elm->name,elm->data); } static void traverse(xbt_set_t set) { xbt_set_cursor_t cursor=NULL; my_elem_t elm=NULL; - + xbt_set_foreach(set,cursor,elm) { xbt_test_assert0(elm,"Dude ! Got a null elm during traversal!"); xbt_test_log3("Id(%d): %s->%s\n",elm->ID,elm->name,elm->data); xbt_test_assert2(!strcmp(elm->name,elm->data), - "Key(%s) != value(%s). Abording", - elm->name,elm->data); + "Key(%s) != value(%s). Abording", + elm->name,elm->data); } } @@ -407,9 +407,9 @@ static void search_not_found(xbt_set_t set, const char *data) { xbt_set_get_by_name(set,data); THROW1(unknown_error,0,"Found something which shouldn't be there (%s)",data); } CATCH(e) { - if (e.category != not_found_error) + if (e.category != not_found_error) xbt_test_exception(e); - xbt_ex_free(e); + xbt_ex_free(e); } } @@ -421,7 +421,7 @@ XBT_TEST_UNIT("basic",test_set_basic,"Basic usage") { xbt_test_add0("Traverse the empty set"); traverse(set); - + xbt_test_add0("Free a data set"); fill(&set); xbt_set_free(&set); diff --git a/src/xbt/snprintf.c b/src/xbt/snprintf.c index e534d0b279..b80f8d23c7 100644 --- a/src/xbt/snprintf.c +++ b/src/xbt/snprintf.c @@ -366,17 +366,17 @@ #define fast_memcpy(d,s,n) \ { register size_t nn = (size_t)(n); \ - if (nn >= breakeven_point) memcpy((d), (s), nn); \ - else if (nn > 0) { /* proc call overhead is worth only for large strings*/\ - register char *dd; register const char *ss; \ - for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } } + if (nn >= breakeven_point) memcpy((d), (s), nn); \ + else if (nn > 0) { /* proc call overhead is worth only for large strings*/\ + register char *dd; register const char *ss; \ + for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } } #define fast_memset(d,c,n) \ { register size_t nn = (size_t)(n); \ - if (nn >= breakeven_point) memset((d), (int)(c), nn); \ - else if (nn > 0) { /* proc call overhead is worth only for large strings*/\ - register char *dd; register const int cc=(int)(c); \ - for (dd=(d); nn>0; nn--) *dd++ = cc; } } + if (nn >= breakeven_point) memset((d), (int)(c), nn); \ + else if (nn > 0) { /* proc call overhead is worth only for large strings*/\ + register char *dd; register const int cc=(int)(c); \ + for (dd=(d); nn>0; nn--) *dd++ = cc; } } /* prototypes */ @@ -384,7 +384,7 @@ #if defined(NEED_ASPRINTF) int asprintf (char **ptr, const char *fmt, /*args*/ ...); #endif -#if defined(NEED_VASPRINTF) +#if defined(NEED_VASPRINTF) int vasprintf (char **ptr, const char *fmt, va_list ap); #endif @@ -423,14 +423,14 @@ int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap); /* declarations */ static char credits[] = "\n\ -@(#)snprintf.c, v2.2: Mark Martinec, \n\ -@(#)snprintf.c, v2.2: Copyright 1999, Mark Martinec. Frontier Artistic License applies.\n\ -@(#)snprintf.c, v2.2: http://www.ijs.si/software/snprintf/\n"; + @(#)snprintf.c, v2.2: Mark Martinec, \n\ + @(#)snprintf.c, v2.2: Copyright 1999, Mark Martinec. Frontier Artistic License applies.\n\ + @(#)snprintf.c, v2.2: http://www.ijs.si/software/snprintf/\n"; -static void __foo__(void) +static void __foo__(void) { - printf("%s",credits); - __foo__(); + printf("%s",credits); + __foo__(); } #if defined(NEED_ASPRINTF) @@ -464,9 +464,9 @@ int vasprintf(char **ptr, const char *fmt, va_list ap) { *ptr = NULL; { va_list ap2; - va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */ - str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/ - va_end(ap2); + va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */ + str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/ + va_end(ap2); } assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */ *ptr = (char *) malloc(str_m = (size_t)str_l + 1); @@ -513,9 +513,9 @@ int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap) { *ptr = NULL; { va_list ap2; - va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */ - str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/ - va_end(ap2); + va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */ + str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/ + va_end(ap2); } assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */ if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1; /* truncate */ @@ -554,451 +554,451 @@ int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) { #if defined(NEED_SNPRINTF_ONLY) int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) { #else -int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) { + int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) { #endif #if defined(NEED_SNPRINTF_ONLY) - va_list ap; + va_list ap; #endif - size_t str_l = 0; - const char *p = fmt; + size_t str_l = 0; + const char *p = fmt; -/* In contrast with POSIX, the ISO C99 now says - * that str can be NULL and str_m can be 0. - * This is more useful than the old: if (str_m < 1) return -1; */ + /* In contrast with POSIX, the ISO C99 now says + * that str can be NULL and str_m can be 0. + * This is more useful than the old: if (str_m < 1) return -1; */ #if defined(NEED_SNPRINTF_ONLY) - va_start(ap, fmt); + va_start(ap, fmt); #endif - if (!p) p = ""; - while (*p) { - if (*p != '%') { - /* if (str_l < str_m) str[str_l++] = *p++; -- this would be sufficient */ - /* but the following code achieves better performance for cases - * where format string is long and contains few conversions */ - const char *q = strchr(p+1,'%'); - size_t n = !q ? strlen(p) : (q-p); - if (str_l < str_m) { - size_t avail = str_m-str_l; - fast_memcpy(str+str_l, p, (n>avail?avail:n)); - } - p += n; str_l += n; - } else { - const char *starting_p; - size_t min_field_width = 0, precision = 0; - int zero_padding = 0, precision_specified = 0, justify_left = 0; - int alternate_form = 0, force_sign = 0; - int space_for_positive = 1; /* If both the ' ' and '+' flags appear, + if (!p) p = ""; + while (*p) { + if (*p != '%') { + /* if (str_l < str_m) str[str_l++] = *p++; -- this would be sufficient */ + /* but the following code achieves better performance for cases + * where format string is long and contains few conversions */ + const char *q = strchr(p+1,'%'); + size_t n = !q ? strlen(p) : (q-p); + if (str_l < str_m) { + size_t avail = str_m-str_l; + fast_memcpy(str+str_l, p, (n>avail?avail:n)); + } + p += n; str_l += n; + } else { + const char *starting_p; + size_t min_field_width = 0, precision = 0; + int zero_padding = 0, precision_specified = 0, justify_left = 0; + int alternate_form = 0, force_sign = 0; + int space_for_positive = 1; /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored. */ - char length_modifier = '\0'; /* allowed values: \0, h, l, L */ - char tmp[32];/* temporary buffer for simple numeric->string conversion */ + char length_modifier = '\0'; /* allowed values: \0, h, l, L */ + char tmp[32];/* temporary buffer for simple numeric->string conversion */ - const char *str_arg; /* string address in case of string argument */ - size_t str_arg_l; /* natural field width of arg without padding + const char *str_arg; /* string address in case of string argument */ + size_t str_arg_l; /* natural field width of arg without padding and sign */ - unsigned char uchar_arg; + unsigned char uchar_arg; /* unsigned char argument value - only defined for c conversion. N.B. standard explicitly states the char argument for the c conversion is unsigned */ - size_t number_of_zeros_to_pad = 0; + size_t number_of_zeros_to_pad = 0; /* number of zeros to be inserted for numeric conversions as required by the precision or minimal field width */ - size_t zero_padding_insertion_ind = 0; + size_t zero_padding_insertion_ind = 0; /* index into tmp where zero padding is to be inserted */ - char fmt_spec = '\0'; + char fmt_spec = '\0'; /* current conversion specifier character */ - str_arg = credits;/* just to make compiler happy (defined but not used)*/ - str_arg = NULL; - starting_p = p; p++; /* skip '%' */ - /* parse flags */ - while (*p == '0' || *p == '-' || *p == '+' || - *p == ' ' || *p == '#' || *p == '\'') { - switch (*p) { - case '0': zero_padding = 1; break; - case '-': justify_left = 1; break; - case '+': force_sign = 1; space_for_positive = 0; break; - case ' ': force_sign = 1; - /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */ + str_arg = credits;/* just to make compiler happy (defined but not used)*/ + str_arg = NULL; + starting_p = p; p++; /* skip '%' */ + /* parse flags */ + while (*p == '0' || *p == '-' || *p == '+' || + *p == ' ' || *p == '#' || *p == '\'') { + switch (*p) { + case '0': zero_padding = 1; break; + case '-': justify_left = 1; break; + case '+': force_sign = 1; space_for_positive = 0; break; + case ' ': force_sign = 1; + /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */ #ifdef PERL_COMPATIBLE - /* ... but in Perl the last of ' ' and '+' applies */ - space_for_positive = 1; + /* ... but in Perl the last of ' ' and '+' applies */ + space_for_positive = 1; #endif - break; - case '#': alternate_form = 1; break; - case '\'': break; + break; + case '#': alternate_form = 1; break; + case '\'': break; + } + p++; } - p++; - } - /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */ - - /* parse field width */ - if (*p == '*') { - int j; - p++; j = va_arg(ap, int); - if (j >= 0) min_field_width = j; - else { min_field_width = -j; justify_left = 1; } - } else if (isdigit((int)(*p))) { - /* size_t could be wider than unsigned int; - make sure we treat argument like common implementations do */ - unsigned int uj = *p++ - '0'; - while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0'); - min_field_width = uj; - } - /* parse precision */ - if (*p == '.') { - p++; precision_specified = 1; + /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */ + + /* parse field width */ if (*p == '*') { - int j = va_arg(ap, int); - p++; - if (j >= 0) precision = j; - else { - precision_specified = 0; precision = 0; - /* NOTE: - * Solaris 2.6 man page claims that in this case the precision - * should be set to 0. Digital Unix 4.0, HPUX 10 and BSD man page - * claim that this case should be treated as unspecified precision, - * which is what we do here. - */ - } + int j; + p++; j = va_arg(ap, int); + if (j >= 0) min_field_width = j; + else { min_field_width = -j; justify_left = 1; } } else if (isdigit((int)(*p))) { /* size_t could be wider than unsigned int; - make sure we treat argument like common implementations do */ + make sure we treat argument like common implementations do */ unsigned int uj = *p++ - '0'; while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0'); - precision = uj; + min_field_width = uj; } - } - /* parse 'h', 'l' and 'll' length modifiers */ - if (*p == 'h' || *p == 'l') { - length_modifier = *p; p++; - if (length_modifier == 'l' && *p == 'l') { /* double l = long long */ + /* parse precision */ + if (*p == '.') { + p++; precision_specified = 1; + if (*p == '*') { + int j = va_arg(ap, int); + p++; + if (j >= 0) precision = j; + else { + precision_specified = 0; precision = 0; + /* NOTE: + * Solaris 2.6 man page claims that in this case the precision + * should be set to 0. Digital Unix 4.0, HPUX 10 and BSD man page + * claim that this case should be treated as unspecified precision, + * which is what we do here. + */ + } + } else if (isdigit((int)(*p))) { + /* size_t could be wider than unsigned int; + make sure we treat argument like common implementations do */ + unsigned int uj = *p++ - '0'; + while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0'); + precision = uj; + } + } + /* parse 'h', 'l' and 'll' length modifiers */ + if (*p == 'h' || *p == 'l') { + length_modifier = *p; p++; + if (length_modifier == 'l' && *p == 'l') { /* double l = long long */ #ifdef SNPRINTF_LONGLONG_SUPPORT - length_modifier = '2'; /* double l encoded as '2' */ + length_modifier = '2'; /* double l encoded as '2' */ #else - length_modifier = 'l'; /* treat it as a single 'l' */ + length_modifier = 'l'; /* treat it as a single 'l' */ #endif - p++; + p++; + } } - } - fmt_spec = *p; - /* common synonyms: */ - switch (fmt_spec) { - case 'i': fmt_spec = 'd'; break; - case 'D': fmt_spec = 'd'; length_modifier = 'l'; break; - case 'U': fmt_spec = 'u'; length_modifier = 'l'; break; - case 'O': fmt_spec = 'o'; length_modifier = 'l'; break; - default: break; - } - /* get parameter value, do initial processing */ - switch (fmt_spec) { - case '%': /* % behaves similar to 's' regarding flags and field widths */ - case 'c': /* c behaves similar to 's' regarding flags and field widths */ - case 's': - length_modifier = '\0'; /* wint_t and wchar_t not supported */ - /* the result of zero padding flag with non-numeric conversion specifier*/ - /* is undefined. Solaris and HPUX 10 does zero padding in this case, */ - /* Digital Unix and Linux does not. */ -#if !defined(SOLARIS_COMPATIBLE) && !defined(HPUX_COMPATIBLE) - zero_padding = 0; /* turn zero padding off for string conversions */ -#endif - str_arg_l = 1; + fmt_spec = *p; + /* common synonyms: */ switch (fmt_spec) { - case '%': - str_arg = p; break; - case 'c': { - int j = va_arg(ap, int); - uchar_arg = (unsigned char) j; /* standard demands unsigned char */ - str_arg = (const char *) &uchar_arg; - break; - } - case 's': - str_arg = va_arg(ap, const char *); - if (!str_arg) str_arg_l = 0; - /* make sure not to address string beyond the specified precision !!! */ - else if (!precision_specified) str_arg_l = strlen(str_arg); - /* truncate string if necessary as requested by precision */ - else if (precision == 0) str_arg_l = 0; - else { - /* memchr on HP does not like n > 2^31 !!! */ - char *q = (char *) memchr(str_arg, '\0', - precision <= 0x7fffffff ? precision : 0x7fffffff); - str_arg_l = !q ? precision : (q-str_arg); - } - break; - default: break; + case 'i': fmt_spec = 'd'; break; + case 'D': fmt_spec = 'd'; length_modifier = 'l'; break; + case 'U': fmt_spec = 'u'; length_modifier = 'l'; break; + case 'O': fmt_spec = 'o'; length_modifier = 'l'; break; + default: break; } - break; - case 'd': case 'u': case 'o': case 'x': case 'X': case 'p': { - /* NOTE: the u, o, x, X and p conversion specifiers imply + /* get parameter value, do initial processing */ + switch (fmt_spec) { + case '%': /* % behaves similar to 's' regarding flags and field widths */ + case 'c': /* c behaves similar to 's' regarding flags and field widths */ + case 's': + length_modifier = '\0'; /* wint_t and wchar_t not supported */ + /* the result of zero padding flag with non-numeric conversion specifier*/ + /* is undefined. Solaris and HPUX 10 does zero padding in this case, */ + /* Digital Unix and Linux does not. */ +#if !defined(SOLARIS_COMPATIBLE) && !defined(HPUX_COMPATIBLE) + zero_padding = 0; /* turn zero padding off for string conversions */ +#endif + str_arg_l = 1; + switch (fmt_spec) { + case '%': + str_arg = p; break; + case 'c': { + int j = va_arg(ap, int); + uchar_arg = (unsigned char) j; /* standard demands unsigned char */ + str_arg = (const char *) &uchar_arg; + break; + } + case 's': + str_arg = va_arg(ap, const char *); + if (!str_arg) str_arg_l = 0; + /* make sure not to address string beyond the specified precision !!! */ + else if (!precision_specified) str_arg_l = strlen(str_arg); + /* truncate string if necessary as requested by precision */ + else if (precision == 0) str_arg_l = 0; + else { + /* memchr on HP does not like n > 2^31 !!! */ + char *q = (char *) memchr(str_arg, '\0', + precision <= 0x7fffffff ? precision : 0x7fffffff); + str_arg_l = !q ? precision : (q-str_arg); + } + break; + default: break; + } + break; + case 'd': case 'u': case 'o': case 'x': case 'X': case 'p': { + /* NOTE: the u, o, x, X and p conversion specifiers imply the value is unsigned; d implies a signed value */ - int arg_sign = 0; - /* 0 if numeric argument is zero (or if pointer is NULL for 'p'), + int arg_sign = 0; + /* 0 if numeric argument is zero (or if pointer is NULL for 'p'), +1 if greater than zero (or nonzero for unsigned arguments), -1 if negative (unsigned argument is never negative) */ - int int_arg = 0; unsigned int uint_arg = 0; - /* only defined for length modifier h, or for no length modifiers */ + int int_arg = 0; unsigned int uint_arg = 0; + /* only defined for length modifier h, or for no length modifiers */ - long int long_arg = 0; unsigned long int ulong_arg = 0; - /* only defined for length modifier l */ + long int long_arg = 0; unsigned long int ulong_arg = 0; + /* only defined for length modifier l */ - void *ptr_arg = NULL; - /* pointer argument value -only defined for p conversion */ + void *ptr_arg = NULL; + /* pointer argument value -only defined for p conversion */ #ifdef SNPRINTF_LONGLONG_SUPPORT - long long int long_long_arg = 0; - unsigned long long int ulong_long_arg = 0; - /* only defined for length modifier ll */ + long long int long_long_arg = 0; + unsigned long long int ulong_long_arg = 0; + /* only defined for length modifier ll */ #endif - if (fmt_spec == 'p') { - /* HPUX 10: An l, h, ll or L before any other conversion character - * (other than d, i, u, o, x, or X) is ignored. - * Digital Unix: - * not specified, but seems to behave as HPUX does. - * Solaris: If an h, l, or L appears before any other conversion - * specifier (other than d, i, u, o, x, or X), the behavior - * is undefined. (Actually %hp converts only 16-bits of address - * and %llp treats address as 64-bit data which is incompatible - * with (void *) argument on a 32-bit system). - */ + if (fmt_spec == 'p') { + /* HPUX 10: An l, h, ll or L before any other conversion character + * (other than d, i, u, o, x, or X) is ignored. + * Digital Unix: + * not specified, but seems to behave as HPUX does. + * Solaris: If an h, l, or L appears before any other conversion + * specifier (other than d, i, u, o, x, or X), the behavior + * is undefined. (Actually %hp converts only 16-bits of address + * and %llp treats address as 64-bit data which is incompatible + * with (void *) argument on a 32-bit system). + */ #ifdef SOLARIS_COMPATIBLE # ifdef SOLARIS_BUG_COMPATIBLE - /* keep length modifiers even if it represents 'll' */ + /* keep length modifiers even if it represents 'll' */ # else - if (length_modifier == '2') length_modifier = '\0'; + if (length_modifier == '2') length_modifier = '\0'; # endif #else - length_modifier = '\0'; + length_modifier = '\0'; #endif - ptr_arg = va_arg(ap, void *); - if (ptr_arg != NULL) arg_sign = 1; - } else if (fmt_spec == 'd') { /* signed */ - switch (length_modifier) { - case '\0': - case 'h': - /* It is non-portable to specify a second argument of char or short - * to va_arg, because arguments seen by the called function - * are not char or short. C converts char and short arguments - * to int before passing them to a function. - */ - int_arg = va_arg(ap, int); - if (int_arg > 0) arg_sign = 1; - else if (int_arg < 0) arg_sign = -1; - break; - case 'l': - long_arg = va_arg(ap, long int); - if (long_arg > 0) arg_sign = 1; - else if (long_arg < 0) arg_sign = -1; - break; + ptr_arg = va_arg(ap, void *); + if (ptr_arg != NULL) arg_sign = 1; + } else if (fmt_spec == 'd') { /* signed */ + switch (length_modifier) { + case '\0': + case 'h': + /* It is non-portable to specify a second argument of char or short + * to va_arg, because arguments seen by the called function + * are not char or short. C converts char and short arguments + * to int before passing them to a function. + */ + int_arg = va_arg(ap, int); + if (int_arg > 0) arg_sign = 1; + else if (int_arg < 0) arg_sign = -1; + break; + case 'l': + long_arg = va_arg(ap, long int); + if (long_arg > 0) arg_sign = 1; + else if (long_arg < 0) arg_sign = -1; + break; #ifdef SNPRINTF_LONGLONG_SUPPORT - case '2': - long_long_arg = va_arg(ap, long long int); - if (long_long_arg > 0) arg_sign = 1; - else if (long_long_arg < 0) arg_sign = -1; - break; + case '2': + long_long_arg = va_arg(ap, long long int); + if (long_long_arg > 0) arg_sign = 1; + else if (long_long_arg < 0) arg_sign = -1; + break; #endif - } - } else { /* unsigned */ - switch (length_modifier) { - case '\0': - case 'h': - uint_arg = va_arg(ap, unsigned int); - if (uint_arg) arg_sign = 1; - break; - case 'l': - ulong_arg = va_arg(ap, unsigned long int); - if (ulong_arg) arg_sign = 1; - break; + } + } else { /* unsigned */ + switch (length_modifier) { + case '\0': + case 'h': + uint_arg = va_arg(ap, unsigned int); + if (uint_arg) arg_sign = 1; + break; + case 'l': + ulong_arg = va_arg(ap, unsigned long int); + if (ulong_arg) arg_sign = 1; + break; #ifdef SNPRINTF_LONGLONG_SUPPORT - case '2': - ulong_long_arg = va_arg(ap, unsigned long long int); - if (ulong_long_arg) arg_sign = 1; - break; + case '2': + ulong_long_arg = va_arg(ap, unsigned long long int); + if (ulong_long_arg) arg_sign = 1; + break; #endif - } - } - str_arg = tmp; str_arg_l = 0; - /* NOTE: - * For d, i, u, o, x, and X conversions, if precision is specified, - * the '0' flag should be ignored. This is so with Solaris 2.6, - * Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl. - */ + } + } + str_arg = tmp; str_arg_l = 0; + /* NOTE: + * For d, i, u, o, x, and X conversions, if precision is specified, + * the '0' flag should be ignored. This is so with Solaris 2.6, + * Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl. + */ #ifndef PERL_COMPATIBLE - if (precision_specified) zero_padding = 0; + if (precision_specified) zero_padding = 0; #endif - if (fmt_spec == 'd') { - if (force_sign && arg_sign >= 0) - tmp[str_arg_l++] = space_for_positive ? ' ' : '+'; - /* leave negative numbers for sprintf to handle, + if (fmt_spec == 'd') { + if (force_sign && arg_sign >= 0) + tmp[str_arg_l++] = space_for_positive ? ' ' : '+'; + /* leave negative numbers for sprintf to handle, to avoid handling tricky cases like (short int)(-32768) */ #ifdef LINUX_COMPATIBLE - } else if (fmt_spec == 'p' && force_sign && arg_sign > 0) { - tmp[str_arg_l++] = space_for_positive ? ' ' : '+'; + } else if (fmt_spec == 'p' && force_sign && arg_sign > 0) { + tmp[str_arg_l++] = space_for_positive ? ' ' : '+'; #endif - } else if (alternate_form) { - if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X') ) - { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = fmt_spec; } - /* alternate form should have no effect for p conversion, but ... */ + } else if (alternate_form) { + if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X') ) + { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = fmt_spec; } + /* alternate form should have no effect for p conversion, but ... */ #ifdef HPUX_COMPATIBLE - else if (fmt_spec == 'p' - /* HPUX 10: for an alternate form of p conversion, - * a nonzero result is prefixed by 0x. */ + else if (fmt_spec == 'p' + /* HPUX 10: for an alternate form of p conversion, + * a nonzero result is prefixed by 0x. */ #ifndef HPUX_BUG_COMPATIBLE - /* Actually it uses 0x prefix even for a zero value. */ - && arg_sign != 0 + /* Actually it uses 0x prefix even for a zero value. */ + && arg_sign != 0 #endif ) { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = 'x'; } #endif - } - zero_padding_insertion_ind = str_arg_l; - if (!precision_specified) precision = 1; /* default precision is 1 */ - if (precision == 0 && arg_sign == 0 + } + zero_padding_insertion_ind = str_arg_l; + if (!precision_specified) precision = 1; /* default precision is 1 */ + if (precision == 0 && arg_sign == 0 #if defined(HPUX_BUG_COMPATIBLE) || defined(LINUX_COMPATIBLE) - && fmt_spec != 'p' - /* HPUX 10 man page claims: With conversion character p the result of - * converting a zero value with a precision of zero is a null string. - * Actually HP returns all zeroes, and Linux returns "(nil)". */ + && fmt_spec != 'p' + /* HPUX 10 man page claims: With conversion character p the result of + * converting a zero value with a precision of zero is a null string. + * Actually HP returns all zeroes, and Linux returns "(nil)". */ #endif - ) { - /* converted to null string */ - /* When zero value is formatted with an explicit precision 0, + ) { + /* converted to null string */ + /* When zero value is formatted with an explicit precision 0, the resulting formatted string is empty (d, i, u, o, x, X, p). */ - } else { - char f[5]; int f_l = 0; - f[f_l++] = '%'; /* construct a simple format string for sprintf */ - if (!length_modifier) { } - else if (length_modifier=='2') { f[f_l++] = 'l'; f[f_l++] = 'l'; } - else f[f_l++] = length_modifier; - f[f_l++] = fmt_spec; f[f_l++] = '\0'; - if (fmt_spec == 'p') str_arg_l += sprintf(tmp+str_arg_l, f, ptr_arg); - else if (fmt_spec == 'd') { /* signed */ - switch (length_modifier) { - case '\0': - case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, int_arg); break; - case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, long_arg); break; + } else { + char f[5]; int f_l = 0; + f[f_l++] = '%'; /* construct a simple format string for sprintf */ + if (!length_modifier) { } + else if (length_modifier=='2') { f[f_l++] = 'l'; f[f_l++] = 'l'; } + else f[f_l++] = length_modifier; + f[f_l++] = fmt_spec; f[f_l++] = '\0'; + if (fmt_spec == 'p') str_arg_l += sprintf(tmp+str_arg_l, f, ptr_arg); + else if (fmt_spec == 'd') { /* signed */ + switch (length_modifier) { + case '\0': + case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, int_arg); break; + case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, long_arg); break; #ifdef SNPRINTF_LONGLONG_SUPPORT - case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,long_long_arg); break; + case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,long_long_arg); break; #endif - } - } else { /* unsigned */ - switch (length_modifier) { - case '\0': - case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, uint_arg); break; - case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, ulong_arg); break; + } + } else { /* unsigned */ + switch (length_modifier) { + case '\0': + case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, uint_arg); break; + case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, ulong_arg); break; #ifdef SNPRINTF_LONGLONG_SUPPORT - case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,ulong_long_arg);break; + case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,ulong_long_arg);break; #endif - } - } - /* include the optional minus sign and possible "0x" + } + } + /* include the optional minus sign and possible "0x" in the region before the zero padding insertion point */ - if (zero_padding_insertion_ind < str_arg_l && - tmp[zero_padding_insertion_ind] == '-') { - zero_padding_insertion_ind++; - } - if (zero_padding_insertion_ind+1 < str_arg_l && - tmp[zero_padding_insertion_ind] == '0' && - (tmp[zero_padding_insertion_ind+1] == 'x' || - tmp[zero_padding_insertion_ind+1] == 'X') ) { - zero_padding_insertion_ind += 2; - } - } - { size_t num_of_digits = str_arg_l - zero_padding_insertion_ind; - if (alternate_form && fmt_spec == 'o' + if (zero_padding_insertion_ind < str_arg_l && + tmp[zero_padding_insertion_ind] == '-') { + zero_padding_insertion_ind++; + } + if (zero_padding_insertion_ind+1 < str_arg_l && + tmp[zero_padding_insertion_ind] == '0' && + (tmp[zero_padding_insertion_ind+1] == 'x' || + tmp[zero_padding_insertion_ind+1] == 'X') ) { + zero_padding_insertion_ind += 2; + } + } + { size_t num_of_digits = str_arg_l - zero_padding_insertion_ind; + if (alternate_form && fmt_spec == 'o' #ifdef HPUX_COMPATIBLE /* ("%#.o",0) -> "" */ - && (str_arg_l > 0) + && (str_arg_l > 0) #endif #ifdef DIGITAL_UNIX_BUG_COMPATIBLE /* ("%#o",0) -> "00" */ #else - /* unless zero is already the first character */ - && !(zero_padding_insertion_ind < str_arg_l - && tmp[zero_padding_insertion_ind] == '0') + /* unless zero is already the first character */ + && !(zero_padding_insertion_ind < str_arg_l + && tmp[zero_padding_insertion_ind] == '0') #endif - ) { /* assure leading zero for alternate-form octal numbers */ - if (!precision_specified || precision < num_of_digits+1) { - /* precision is increased to force the first character to be zero, + ) { /* assure leading zero for alternate-form octal numbers */ + if (!precision_specified || precision < num_of_digits+1) { + /* precision is increased to force the first character to be zero, except if a zero value is formatted with an explicit precision of zero */ - precision = num_of_digits+1; precision_specified = 1; - } - } - /* zero padding to specified precision? */ - if (num_of_digits < precision) - number_of_zeros_to_pad = precision - num_of_digits; - } - /* zero padding to specified minimal field width? */ - if (!justify_left && zero_padding) { - int n = min_field_width - (str_arg_l+number_of_zeros_to_pad); - if (n > 0) number_of_zeros_to_pad += n; - } - break; - } - default: /* unrecognized conversion specifier, keep format string as-is*/ - zero_padding = 0; /* turn zero padding off for non-numeric convers. */ + precision = num_of_digits+1; precision_specified = 1; + } + } + /* zero padding to specified precision? */ + if (num_of_digits < precision) + number_of_zeros_to_pad = precision - num_of_digits; + } + /* zero padding to specified minimal field width? */ + if (!justify_left && zero_padding) { + int n = min_field_width - (str_arg_l+number_of_zeros_to_pad); + if (n > 0) number_of_zeros_to_pad += n; + } + break; + } + default: /* unrecognized conversion specifier, keep format string as-is*/ + zero_padding = 0; /* turn zero padding off for non-numeric convers. */ #ifndef DIGITAL_UNIX_COMPATIBLE - justify_left = 1; min_field_width = 0; /* reset flags */ + justify_left = 1; min_field_width = 0; /* reset flags */ #endif #if defined(PERL_COMPATIBLE) || defined(LINUX_COMPATIBLE) - /* keep the entire format string unchanged */ - str_arg = starting_p; str_arg_l = p - starting_p; - /* well, not exactly so for Linux, which does something inbetween, - * and I don't feel an urge to imitate it: "%+++++hy" -> "%+y" */ + /* keep the entire format string unchanged */ + str_arg = starting_p; str_arg_l = p - starting_p; + /* well, not exactly so for Linux, which does something inbetween, + * and I don't feel an urge to imitate it: "%+++++hy" -> "%+y" */ #else - /* discard the unrecognized conversion, just keep * - * the unrecognized conversion character */ - str_arg = p; str_arg_l = 0; + /* discard the unrecognized conversion, just keep * + * the unrecognized conversion character */ + str_arg = p; str_arg_l = 0; #endif - if (*p) str_arg_l++; /* include invalid conversion specifier unchanged + if (*p) str_arg_l++; /* include invalid conversion specifier unchanged if not at end-of-string */ - break; - } - if (*p) p++; /* step over the just processed conversion specifier */ - /* insert padding to the left as requested by min_field_width; + break; + } + if (*p) p++; /* step over the just processed conversion specifier */ + /* insert padding to the left as requested by min_field_width; this does not include the zero padding in case of numerical conversions*/ - if (!justify_left) { /* left padding with blank or zero */ - int n = min_field_width - (str_arg_l+number_of_zeros_to_pad); - if (n > 0) { - if (str_l < str_m) { - int avail = str_m-str_l; - fast_memset(str+str_l, (zero_padding?'0':' '), (n>avail?avail:n)); + if (!justify_left) { /* left padding with blank or zero */ + int n = min_field_width - (str_arg_l+number_of_zeros_to_pad); + if (n > 0) { + if (str_l < str_m) { + int avail = str_m-str_l; + fast_memset(str+str_l, (zero_padding?'0':' '), (n>avail?avail:n)); + } + str_l += n; } - str_l += n; } - } - /* zero padding as requested by the precision or by the minimal field width - * for numeric conversions required? */ - if (number_of_zeros_to_pad <= 0) { - /* will not copy first part of numeric right now, * - * force it to be copied later in its entirety */ - zero_padding_insertion_ind = 0; - } else { - /* insert first part of numerics (sign or '0x') before zero padding */ - int n = zero_padding_insertion_ind; - if (n > 0) { - if (str_l < str_m) { - int avail = str_m-str_l; - fast_memcpy(str+str_l, str_arg, (n>avail?avail:n)); + /* zero padding as requested by the precision or by the minimal field width + * for numeric conversions required? */ + if (number_of_zeros_to_pad <= 0) { + /* will not copy first part of numeric right now, * + * force it to be copied later in its entirety */ + zero_padding_insertion_ind = 0; + } else { + /* insert first part of numerics (sign or '0x') before zero padding */ + int n = zero_padding_insertion_ind; + if (n > 0) { + if (str_l < str_m) { + int avail = str_m-str_l; + fast_memcpy(str+str_l, str_arg, (n>avail?avail:n)); + } + str_l += n; } - str_l += n; - } - /* insert zero padding as requested by the precision or min field width */ - n = number_of_zeros_to_pad; - if (n > 0) { - if (str_l < str_m) { - int avail = str_m-str_l; - fast_memset(str+str_l, '0', (n>avail?avail:n)); + /* insert zero padding as requested by the precision or min field width */ + n = number_of_zeros_to_pad; + if (n > 0) { + if (str_l < str_m) { + int avail = str_m-str_l; + fast_memset(str+str_l, '0', (n>avail?avail:n)); + } + str_l += n; } - str_l += n; } - } - /* insert formatted string - * (or as-is conversion specifier for unknown conversions) */ - { int n = str_arg_l - zero_padding_insertion_ind; + /* insert formatted string + * (or as-is conversion specifier for unknown conversions) */ + { int n = str_arg_l - zero_padding_insertion_ind; if (n > 0) { if (str_l < str_m) { int avail = str_m-str_l; @@ -1007,55 +1007,55 @@ int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) { } str_l += n; } - } - /* insert right padding */ - if (justify_left) { /* right blank padding to the field width */ - int n = min_field_width - (str_arg_l+number_of_zeros_to_pad); - if (n > 0) { - if (str_l < str_m) { - int avail = str_m-str_l; - fast_memset(str+str_l, ' ', (n>avail?avail:n)); + } + /* insert right padding */ + if (justify_left) { /* right blank padding to the field width */ + int n = min_field_width - (str_arg_l+number_of_zeros_to_pad); + if (n > 0) { + if (str_l < str_m) { + int avail = str_m-str_l; + fast_memset(str+str_l, ' ', (n>avail?avail:n)); + } + str_l += n; } - str_l += n; } } } - } #if defined(NEED_SNPRINTF_ONLY) - va_end(ap); + va_end(ap); #endif - if (str_m > 0) { /* make sure the string is null-terminated + if (str_m > 0) { /* make sure the string is null-terminated even at the expense of overwriting the last character (shouldn't happen, but just in case) */ - str[str_l <= str_m-1 ? str_l : str_m-1] = '\0'; + str[str_l <= str_m-1 ? str_l : str_m-1] = '\0'; + } + /* Return the number of characters formatted (excluding trailing null + * character), that is, the number of characters that would have been + * written to the buffer if it were large enough. + * + * The value of str_l should be returned, but str_l is of unsigned type + * size_t, and snprintf is int, possibly leading to an undetected + * integer overflow, resulting in a negative return value, which is illegal. + * Both XSH5 and ISO C99 (at least the draft) are silent on this issue. + * Should errno be set to EOVERFLOW and EOF returned in this case??? + */ + return (int) str_l; } - /* Return the number of characters formatted (excluding trailing null - * character), that is, the number of characters that would have been - * written to the buffer if it were large enough. - * - * The value of str_l should be returned, but str_l is of unsigned type - * size_t, and snprintf is int, possibly leading to an undetected - * integer overflow, resulting in a negative return value, which is illegal. - * Both XSH5 and ISO C99 (at least the draft) are silent on this issue. - * Should errno be set to EOVERFLOW and EOF returned in this case??? - */ - return (int) str_l; -} #endif -/* FIXME: better place */ + /* FIXME: better place */ #include "xbt/sysdep.h" -char *bprintf(const char*fmt, ...) { - va_list ap; - char *res; - - va_start(ap, fmt); - - - vasprintf(&res,fmt,ap); - - va_end(ap); - return res; -} + char *bprintf(const char*fmt, ...) { + va_list ap; + char *res; + + va_start(ap, fmt); + + + vasprintf(&res,fmt,ap); + + va_end(ap); + return res; + } diff --git a/src/xbt/swag.c b/src/xbt/swag.c index 67319cc17b..eda86e4f04 100644 --- a/src/xbt/swag.c +++ b/src/xbt/swag.c @@ -23,7 +23,7 @@ * \param offset where the hookup is located in the structure * \see xbt_swag_offset * - * Usage : xbt_swag_new(&obj.setA-&obj); + * Usage : xbt_swag_new(&obj.setA-&obj); */ xbt_swag_t xbt_swag_new(size_t offset) { @@ -34,9 +34,9 @@ xbt_swag_t xbt_swag_new(size_t offset) return swag; } -/** +/** * \param swag poor victim - * + * * kilkil a swag but not it's content. If you do not understand why * xbt_swag_free should not free its content, don't use swags. */ @@ -50,7 +50,7 @@ void xbt_swag_free(xbt_swag_t swag) * \param offset where the hookup is located in the structure * \see xbt_swag_offset * - * Usage : xbt_swag_init(swag,&obj.setA-&obj); + * Usage : xbt_swag_init(swag,&obj.setA-&obj); */ void xbt_swag_init(xbt_swag_t swag, size_t offset) { @@ -61,7 +61,7 @@ void xbt_swag_init(xbt_swag_t swag, size_t offset) } -/** +/** * \param obj the objet to insert in the swag * \param swag a swag * @@ -87,7 +87,7 @@ void xbt_swag_insert(void *obj, xbt_swag_t swag) swag->tail = obj; } -/** +/** * \param obj the objet to insert in the swag * \param swag a swag * @@ -114,7 +114,7 @@ void xbt_swag_insert_at_head(void *obj, xbt_swag_t swag) swag->head = obj; } -/** +/** * \param obj the objet to insert in the swag * \param swag a swag * @@ -141,7 +141,7 @@ void xbt_swag_insert_at_tail(void *obj, xbt_swag_t swag) swag->tail = obj; } -/** +/** * \param obj the objet to remove from the swag * \param swag a swag * \return \a obj if it was in the \a swag and NULL otherwise @@ -156,7 +156,7 @@ void *xbt_swag_remove(void *obj, xbt_swag_t swag) return NULL; if(!xbt_swag_belongs(obj, swag)) /* Trying to remove an object that was not in this swag */ - return NULL; + return NULL; if (swag->head == swag->tail) { /* special case */ if (swag->head != obj) /* Trying to remove an object that was not in this swag */ @@ -181,7 +181,7 @@ void *xbt_swag_remove(void *obj, xbt_swag_t swag) return obj; } -/** +/** * \param swag a swag * \return an object from the \a swag */ @@ -207,7 +207,7 @@ void *xbt_swag_extract(xbt_swag_t swag) return obj; } -/** +/** * \param swag a swag * \return the number of objects in \a swag */ @@ -216,7 +216,7 @@ int xbt_swag_size(xbt_swag_t swag) return (swag->count); } -/** +/** * \param obj an object * \param swag a swag * \return 1 if \a obj is in the \a swag and 0 otherwise @@ -224,7 +224,7 @@ int xbt_swag_size(xbt_swag_t swag) int xbt_swag_belongs(void *obj, xbt_swag_t swag) { return ((NEXT(obj, swag->offset)) || (PREV(obj, swag->offset)) - || (swag->head == obj)); + || (swag->head == obj)); } @@ -251,7 +251,7 @@ XBT_TEST_UNIT("basic",test_swag_basic,"Basic usage") { xbt_test_add0("Basic usage"); xbt_test_log3("%p %p %ld\n",obj1,&(obj1->setB), - (long)((char *)&(obj1->setB) - (char *)obj1)); + (long)((char *)&(obj1->setB) - (char *)obj1)); setA = xbt_swag_new(xbt_swag_offset(*obj1,setA)); setB = xbt_swag_new(xbt_swag_offset(*obj1,setB)); @@ -283,7 +283,7 @@ XBT_TEST_UNIT("basic",test_swag_basic,"Basic usage") { xbt_test_assert(xbt_swag_size(setA) == 2); xbt_test_assert(xbt_swag_size(setB) == 1); - + xbt_swag_free(setA); xbt_swag_free(setB); } diff --git a/src/xbt/xbt_context.c b/src/xbt/xbt_context.c index a683fcd637..42673a941d 100644 --- a/src/xbt/xbt_context.c +++ b/src/xbt/xbt_context.c @@ -26,7 +26,7 @@ xbt_swag_t context_to_destroy = NULL; /* this list contains the contexts in use */ xbt_swag_t context_living = NULL; -/* the context factory used to create the appropriate context +/* the context factory used to create the appropriate context * each context implementation define its own context factory * a context factory is responsable of the creation of the context * associated with the maestro and of all the context based on @@ -97,7 +97,7 @@ void xbt_context_mod_exit(void) /* remove the context of the scheduler from the list of the contexts in use */ xbt_swag_remove(maestro_context, context_living); - /* + /* * kill all the contexts in use : * the killed contexts are added in the list of the contexts to destroy */ @@ -120,12 +120,12 @@ void xbt_context_mod_exit(void) /*******************************/ /* Object creation/destruction */ /*******************************/ -/** +/** * \param code a main function * \param startup_func a function to call when running the context for * the first time and just before the main function \a code * \param startup_arg the argument passed to the previous function (\a startup_func) - * \param cleanup_func a function to call when running the context, just after + * \param cleanup_func a function to call when running the context, just after the termination of the main function \a code * \param cleanup_arg the argument passed to the previous function (\a cleanup_func) * \param argc first argument of function \a code @@ -138,13 +138,13 @@ xbt_context_new(const char *name, void *startup_arg, void_f_pvoid_t cleanup_func, void *cleanup_arg, int argc, char *argv[] - ) +) { /* use the appropriate context factory to create the appropriate context */ xbt_context_t context = (*(context_factory->create_context)) (name, code, startup_func, - startup_arg, cleanup_func, - cleanup_arg, argc, argv); + startup_arg, cleanup_func, + cleanup_arg, argc, argv); /* add the context in the list of the contexts in use */ xbt_swag_insert(context, context_living); @@ -153,22 +153,22 @@ xbt_context_new(const char *name, } /* Scenario for the end of a context: - * + * * CASE 1: death after end of function * __context_wrapper, called by os thread, calls xbt_context_stop after user code stops * xbt_context_stop calls user cleanup_func if any (in context settings), * add current to trashbin * yields back to maestro (destroy os thread on need) - * From time to time, maestro calls xbt_context_empty_trash, + * From time to time, maestro calls xbt_context_empty_trash, * which maps xbt_context_free on the content - * xbt_context_free frees some more memory, + * xbt_context_free frees some more memory, * joins os thread - * + * * CASE 2: brutal death * xbt_context_kill (from any context) * set context->wannadie to 1 * yields to the context - * the context is awaken in the middle of __yield. + * the context is awaken in the middle of __yield. * At the end of it, it checks that wannadie == 1, and call xbt_context_stop * (same than first case afterward) */ @@ -186,10 +186,10 @@ void xbt_context_kill(xbt_context_t context) (*(context->kill)) (context); } -/** +/** * \param context the context to start - * - * Calling this function prepares \a context to be run. It will + * + * Calling this function prepares \a context to be run. It will however run effectively only when calling #xbt_context_schedule */ void xbt_context_start(xbt_context_t context) @@ -197,11 +197,11 @@ void xbt_context_start(xbt_context_t context) (*(context->start)) (context); } -/** +/** * Calling this function makes the current context yield. The context * that scheduled it returns from xbt_context_schedule as if nothing * had happened. - * + * * Only the processes can call this function, giving back the control * to the maestro */ @@ -210,13 +210,13 @@ void xbt_context_yield(void) (*(current_context->yield)) (); } -/** +/** * \param context the winner * - * Calling this function blocks the current context and schedule \a context. + * Calling this function blocks the current context and schedule \a context. * When \a context will call xbt_context_yield, it will return * to this function as if nothing had happened. - * + * * Only the maestro can call this function to run a given process. */ void xbt_context_schedule(xbt_context_t context) diff --git a/src/xbt/xbt_context_java.h b/src/xbt/xbt_context_java.h index 7c7531549f..fdbc2eace1 100644 --- a/src/xbt/xbt_context_java.h +++ b/src/xbt/xbt_context_java.h @@ -10,11 +10,11 @@ SG_BEGIN_DECL() - typedef struct s_xbt_ctx_java { - XBT_CTX_BASE_T; - jobject jprocess; /* the java process instance binded with the msg process structure */ - JNIEnv *jenv; /* jni interface pointer associated to this thread */ - } s_xbt_ctx_java_t, *xbt_ctx_java_t; +typedef struct s_xbt_ctx_java { + XBT_CTX_BASE_T; + jobject jprocess; /* the java process instance binded with the msg process structure */ + JNIEnv *jenv; /* jni interface pointer associated to this thread */ +} s_xbt_ctx_java_t, *xbt_ctx_java_t; SG_END_DECL() #endif /* !_XBT_CONTEXT_JAVA_H */ diff --git a/src/xbt/xbt_context_private.h b/src/xbt/xbt_context_private.h index 5a953495fe..c95e4380bb 100644 --- a/src/xbt/xbt_context_private.h +++ b/src/xbt/xbt_context_private.h @@ -19,89 +19,89 @@ SG_BEGIN_DECL() /* Context type definition */ /* *********************** */ /* the following function pointers describe the interface that all context concepts must implement */ - typedef void (*xbt_pfn_context_free_t) (xbt_context_t); /* pointer type to the function used to destroy the specified context */ +typedef void (*xbt_pfn_context_free_t) (xbt_context_t); /* pointer type to the function used to destroy the specified context */ - typedef void (*xbt_pfn_context_kill_t) (xbt_context_t); /* pointer type to the function used to kill the specified context */ +typedef void (*xbt_pfn_context_kill_t) (xbt_context_t); /* pointer type to the function used to kill the specified context */ - typedef void (*xbt_pfn_context_schedule_t) (xbt_context_t); /* pointer type to the function used to resume the specified context */ +typedef void (*xbt_pfn_context_schedule_t) (xbt_context_t); /* pointer type to the function used to resume the specified context */ - typedef void (*xbt_pfn_context_yield_t) (void); /* pointer type to the function used to yield the specified context */ +typedef void (*xbt_pfn_context_yield_t) (void); /* pointer type to the function used to yield the specified context */ - typedef void (*xbt_pfn_context_start_t) (xbt_context_t); /* pointer type to the function used to start the specified context */ +typedef void (*xbt_pfn_context_start_t) (xbt_context_t); /* pointer type to the function used to start the specified context */ - typedef void (*xbt_pfn_context_stop_t) (int); /* pointer type to the function used to stop the current context */ +typedef void (*xbt_pfn_context_stop_t) (int); /* pointer type to the function used to stop the current context */ /* each context type must contain this macro at its begining -- OOP in C :/ */ #define XBT_CTX_BASE_T \ - s_xbt_swag_hookup_t hookup; \ - char *name; \ - void_f_pvoid_t cleanup_func; \ - void *cleanup_arg; \ - ex_ctx_t *exception; \ - int iwannadie; \ - xbt_main_func_t code; \ - int argc; \ - char **argv; \ - void_f_pvoid_t startup_func; \ - void *startup_arg; \ - xbt_pfn_context_free_t free; \ - xbt_pfn_context_kill_t kill; \ - xbt_pfn_context_schedule_t schedule; \ - xbt_pfn_context_yield_t yield; \ - xbt_pfn_context_start_t start; \ - xbt_pfn_context_stop_t stop + s_xbt_swag_hookup_t hookup; \ + char *name; \ + void_f_pvoid_t cleanup_func; \ + void *cleanup_arg; \ + ex_ctx_t *exception; \ + int iwannadie; \ + xbt_main_func_t code; \ + int argc; \ + char **argv; \ + void_f_pvoid_t startup_func; \ + void *startup_arg; \ + xbt_pfn_context_free_t free; \ + xbt_pfn_context_kill_t kill; \ + xbt_pfn_context_schedule_t schedule; \ + xbt_pfn_context_yield_t yield; \ + xbt_pfn_context_start_t start; \ + xbt_pfn_context_stop_t stop /* all other context types derive from this structure */ - typedef struct s_xbt_context { - XBT_CTX_BASE_T; - } s_xbt_context_t; +typedef struct s_xbt_context { + XBT_CTX_BASE_T; +} s_xbt_context_t; /* ****************** */ /* Globals definition */ /* ****************** */ /* Important guys */ - extern xbt_context_t current_context; +extern xbt_context_t current_context; - extern xbt_context_t maestro_context; +extern xbt_context_t maestro_context; /* All dudes lists */ - extern xbt_swag_t context_living; +extern xbt_swag_t context_living; - extern xbt_swag_t context_to_destroy; +extern xbt_swag_t context_to_destroy; /* *********************** */ /* factory type definition */ /* *********************** */ - typedef struct s_xbt_context_factory *xbt_context_factory_t; +typedef struct s_xbt_context_factory *xbt_context_factory_t; /* this function describes the interface that all context factory must implement */ - typedef xbt_context_t(*xbt_pfn_context_factory_create_context_t) (const - char *, - xbt_main_func_t, - void_f_pvoid_t, - void *, - void_f_pvoid_t, - void *, - int, - char - **); - typedef - int (*xbt_pfn_context_factory_create_maestro_context_t) (xbt_context_t - *); +typedef xbt_context_t(*xbt_pfn_context_factory_create_context_t) (const + char *, + xbt_main_func_t, + void_f_pvoid_t, + void *, + void_f_pvoid_t, + void *, + int, + char + **); +typedef +int (*xbt_pfn_context_factory_create_maestro_context_t) (xbt_context_t + *); /* this function finalize the specified context factory */ - typedef int (*xbt_pfn_context_factory_finalize_t) (xbt_context_factory_t - *); +typedef int (*xbt_pfn_context_factory_finalize_t) (xbt_context_factory_t + *); /* this interface is used by the xbt context module to create the appropriate concept */ - typedef struct s_xbt_context_factory { - xbt_pfn_context_factory_create_maestro_context_t create_maestro_context; /* create the context of the maestro */ - xbt_pfn_context_factory_create_context_t create_context; /* create a new context */ - xbt_pfn_context_factory_finalize_t finalize; /* finalize the context factory */ - const char *name; /* the name of the context factory */ +typedef struct s_xbt_context_factory { + xbt_pfn_context_factory_create_maestro_context_t create_maestro_context; /* create the context of the maestro */ + xbt_pfn_context_factory_create_context_t create_context; /* create a new context */ + xbt_pfn_context_factory_finalize_t finalize; /* finalize the context factory */ + const char *name; /* the name of the context factory */ - } s_xbt_context_factory_t; +} s_xbt_context_factory_t; /** * This function select a context factory associated with the name specified by @@ -109,27 +109,27 @@ SG_BEGIN_DECL() * If successful the function returns 0. Otherwise the function returns the error * code. */ - int - xbt_context_select_factory(const char *name); +int +xbt_context_select_factory(const char *name); /** * This function initialize a context factory from the name specified by the parameter * name. * If the factory cannot be found, an exception is raised. */ - void +void - - xbt_context_init_factory_by_name(xbt_context_factory_t * factory, - const char *name); + +xbt_context_init_factory_by_name(xbt_context_factory_t * factory, + const char *name); /* All factories init */ - void xbt_ctx_thread_factory_init(xbt_context_factory_t * factory); +void xbt_ctx_thread_factory_init(xbt_context_factory_t * factory); - void xbt_ctx_sysv_factory_init(xbt_context_factory_t * factory); +void xbt_ctx_sysv_factory_init(xbt_context_factory_t * factory); - void xbt_ctx_java_factory_init(xbt_context_factory_t * factory); +void xbt_ctx_java_factory_init(xbt_context_factory_t * factory); diff --git a/src/xbt/xbt_log_appender_file.c b/src/xbt/xbt_log_appender_file.c index 83af8a5b07..3c72683485 100644 --- a/src/xbt/xbt_log_appender_file.c +++ b/src/xbt/xbt_log_appender_file.c @@ -19,7 +19,7 @@ extern const char *xbt_log_priority_names[7]; static void append_file(xbt_log_appender_t this_appender, - char *str) { + char *str) { fprintf((FILE*)(this_appender->data), "%s", str); } diff --git a/src/xbt/xbt_log_layout_format.c b/src/xbt/xbt_log_layout_format.c index 9d05e31824..4fc14b252d 100644 --- a/src/xbt/xbt_log_layout_format.c +++ b/src/xbt/xbt_log_layout_format.c @@ -20,38 +20,38 @@ extern const char *xbt_log_priority_names[7]; static double begin_of_time = -1; #define append1(fmt,fmt2,elm) \ - do { \ - if (precision == -1) { \ - xbt_strbuff_append(buff, tmp=bprintf(fmt,elm)); \ - free(tmp); \ - } else { \ - xbt_strbuff_append(buff, tmp=bprintf(fmt2,precision,elm)); \ - free(tmp); \ - precision = -1; \ - } \ - } while (0) + do { \ + if (precision == -1) { \ + xbt_strbuff_append(buff, tmp=bprintf(fmt,elm)); \ + free(tmp); \ + } else { \ + xbt_strbuff_append(buff, tmp=bprintf(fmt2,precision,elm)); \ + free(tmp); \ + precision = -1; \ + } \ + } while (0) #define append2(fmt,elm,elm2) \ - do { \ - xbt_strbuff_append(buff, tmp=bprintf(fmt,elm,elm2)); \ - free(tmp); \ - precision = -1; \ - } while (0) + do { \ + xbt_strbuff_append(buff, tmp=bprintf(fmt,elm,elm2)); \ + free(tmp); \ + precision = -1; \ + } while (0) #define ERRMSG "Unknown %%%c sequence in layout format (%s).\nKnown sequences:\n" \ - " what: %%m: user message %%c: log category %%p: log priority\n" \ - " where:\n" \ - " source: %%F: file %%L: line %%M: function %%l: location (%%F:%%L)\n" \ - " runtime: %%h: hostname %%t: thread %%P: process %%i: PID\n" \ - " backtrace: %%b: full %%B: short\n" \ - " when: %%d: date %%r: app. age\n" \ - " other: %%%%: %% %%n: new line %%e: plain space\n" - + " what: %%m: user message %%c: log category %%p: log priority\n" \ + " where:\n" \ + " source: %%F: file %%L: line %%M: function %%l: location (%%F:%%L)\n" \ + " runtime: %%h: hostname %%t: thread %%P: process %%i: PID\n" \ + " backtrace: %%b: full %%B: short\n" \ + " when: %%d: date %%r: app. age\n" \ + " other: %%%%: %% %%n: new line %%e: plain space\n" + static void xbt_log_layout_format_dynamic(xbt_log_layout_t l, - xbt_log_event_t ev, - const char*fmt, - xbt_log_appender_t app) { - xbt_strbuff_t buff = xbt_strbuff_new(); + xbt_log_event_t ev, + const char*fmt, + xbt_log_appender_t app) { + xbt_strbuff_t buff = xbt_strbuff_new(); int precision=-1; char *q = l->data; char *tmp; @@ -60,102 +60,102 @@ static void xbt_log_layout_format_dynamic(xbt_log_layout_t l, while (*q != '\0') { if (*q == '%') { q++; - handle_modifier: + handle_modifier: switch (*q) { - case '\0': - fprintf(stderr,"Layout format (%s) ending with %%\n",(char*)l->data); - abort(); - case '%': - xbt_strbuff_append(buff,"%"); - break; - case 'n': /* platform-dependant line separator (LOG4J compliant) */ - xbt_strbuff_append(buff,"\n"); - break; - case 'e': /* plain space (SimGrid extension) */ - xbt_strbuff_append(buff," "); - break; - - case '.': /* precision specifyier */ - q++; - q += sscanf(q,"%d",&precision); - goto handle_modifier; - - case 'c': /* category name; LOG4J compliant + case '\0': + fprintf(stderr,"Layout format (%s) ending with %%\n",(char*)l->data); + abort(); + case '%': + xbt_strbuff_append(buff,"%"); + break; + case 'n': /* platform-dependant line separator (LOG4J compliant) */ + xbt_strbuff_append(buff,"\n"); + break; + case 'e': /* plain space (SimGrid extension) */ + xbt_strbuff_append(buff," "); + break; + + case '.': /* precision specifyier */ + q++; + q += sscanf(q,"%d",&precision); + goto handle_modifier; + + case 'c': /* category name; LOG4J compliant should accept a precision postfix to show the hierarchy */ - append1("%s","%.*s",ev->cat->name); - break; - case 'p': /* priority name; LOG4J compliant */ - append1("%s","%.*s",xbt_log_priority_names[ev->priority]); - break; - - case 'h': /* host name; SimGrid extension */ - append1("%s","%.*s",gras_os_myname()); - break; - case 't': /* thread name; LOG4J compliant */ - append1("%s","%.*s",xbt_thread_self_name()); - break; - case 'P': /* process name; SimGrid extension */ - append1("%s","%.*s",xbt_procname()); - break; - case 'i': /* process PID name; SimGrid extension */ - append1("%d","%.*d",(*xbt_getpid)()); - break; - - case 'F': /* file name; LOG4J compliant */ - append1("%s","%.*s",ev->fileName); - break; - case 'l': /* location; LOG4J compliant */ - append2("%s:%d",ev->fileName,ev->lineNum); - precision = -1; /* Ignored */ - break; - case 'L': /* line number; LOG4J compliant */ - append1("%d","%.*d",ev->lineNum); - break; - case 'M': /* method (ie, function) name; LOG4J compliant */ - append1("%s","%.*s",ev->functionName); - break; - case 'b': /* backtrace; called %throwable in LOG4J */ - case 'B': /* short backtrace; called %throwable{short} in LOG4J */ + append1("%s","%.*s",ev->cat->name); + break; + case 'p': /* priority name; LOG4J compliant */ + append1("%s","%.*s",xbt_log_priority_names[ev->priority]); + break; + + case 'h': /* host name; SimGrid extension */ + append1("%s","%.*s",gras_os_myname()); + break; + case 't': /* thread name; LOG4J compliant */ + append1("%s","%.*s",xbt_thread_self_name()); + break; + case 'P': /* process name; SimGrid extension */ + append1("%s","%.*s",xbt_procname()); + break; + case 'i': /* process PID name; SimGrid extension */ + append1("%d","%.*d",(*xbt_getpid)()); + break; + + case 'F': /* file name; LOG4J compliant */ + append1("%s","%.*s",ev->fileName); + break; + case 'l': /* location; LOG4J compliant */ + append2("%s:%d",ev->fileName,ev->lineNum); + precision = -1; /* Ignored */ + break; + case 'L': /* line number; LOG4J compliant */ + append1("%d","%.*d",ev->lineNum); + break; + case 'M': /* method (ie, function) name; LOG4J compliant */ + append1("%s","%.*s",ev->functionName); + break; + case 'b': /* backtrace; called %throwable in LOG4J */ + case 'B': /* short backtrace; called %throwable{short} in LOG4J */ #if defined(HAVE_EXECINFO_H) && defined(HAVE_POPEN) && defined(ADDR2LINE) - { - xbt_ex_t e; - int i; - - e.used = backtrace((void**)e.bt,XBT_BACKTRACE_SIZE); - e.bt_strings = NULL; - e.msg=NULL; - e.remote=0; - xbt_backtrace_current(&e); - if (*q=='B') { - append1("%s","%.*s",e.bt_strings[2]+8); - } else { - for (i=2; iap_copy); - append1("%s","%.*s",tmp2); - free(tmp2); - break; - - default: - fprintf(stderr,ERRMSG, *q,(char*)l->data); - abort(); + break; + + case 'd': /* date; LOG4J compliant */ + append1("%f","%.*f", gras_os_time()); + break; + case 'r': /* application age; LOG4J compliant */ + append1("%f","%.*f", gras_os_time()-begin_of_time); + break; + + case 'm': /* user-provided message; LOG4J compliant */ + vasprintf(&tmp2, fmt, ev->ap_copy); + append1("%s","%.*s",tmp2); + free(tmp2); + break; + + default: + fprintf(stderr,ERRMSG, *q,(char*)l->data); + abort(); } q++; } else { @@ -171,17 +171,17 @@ static void xbt_log_layout_format_dynamic(xbt_log_layout_t l, #define check_overflow \ if (p-ev->buffer > XBT_LOG_BUFF_SIZE) { /* buffer overflow */ \ - xbt_log_layout_format_dynamic(l,ev,msg_fmt,app); \ - return;\ - } + xbt_log_layout_format_dynamic(l,ev,msg_fmt,app); \ + return;\ + } static void xbt_log_layout_format_doit(xbt_log_layout_t l, - xbt_log_event_t ev, - const char *msg_fmt, - xbt_log_appender_t app) { + xbt_log_event_t ev, + const char *msg_fmt, + xbt_log_appender_t app) { char *p,*q; int precision=-1; - if (begin_of_time<0) + if (begin_of_time<0) begin_of_time=gras_os_time(); p = ev->buffer; @@ -190,212 +190,212 @@ static void xbt_log_layout_format_doit(xbt_log_layout_t l, while (*q != '\0') { if (*q == '%') { q++; - handle_modifier: + handle_modifier: switch (*q) { - case '\0': - fprintf(stderr,"Layout format (%s) ending with %%\n",(char*)l->data); - abort(); - case '%': - *p++ = '%'; - break; - case 'n': /* platform-dependant line separator (LOG4J compliant) */ - p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer),"\n"); - check_overflow; - break; - case 'e': /* plain space (SimGrid extension) */ - p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer)," "); - check_overflow; - break; - - case '.': /* precision specifyier */ - q++; - q += sscanf(q,"%d",&precision); - goto handle_modifier; - - case 'c': /* category name; LOG4J compliant + case '\0': + fprintf(stderr,"Layout format (%s) ending with %%\n",(char*)l->data); + abort(); + case '%': + *p++ = '%'; + break; + case 'n': /* platform-dependant line separator (LOG4J compliant) */ + p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer),"\n"); + check_overflow; + break; + case 'e': /* plain space (SimGrid extension) */ + p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer)," "); + check_overflow; + break; + + case '.': /* precision specifyier */ + q++; + q += sscanf(q,"%d",&precision); + goto handle_modifier; + + case 'c': /* category name; LOG4J compliant should accept a precision postfix to show the hierarchy */ - if (precision == -1) { - p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer),"%s",ev->cat->name); - check_overflow; - } else { - p += sprintf(p,"%.*s",(int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision),ev->cat->name); - check_overflow; - precision = -1; - } - break; - case 'p': /* priority name; LOG4J compliant */ - if (precision == -1) { - p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer), "%s", xbt_log_priority_names[ev->priority] ); - check_overflow; - } else { - p += sprintf(p, "%.*s", (int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision), xbt_log_priority_names[ev->priority] ); - check_overflow; - precision = -1; - } - break; - - case 'h': /* host name; SimGrid extension */ - if (precision == -1) { - p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer), "%s", gras_os_myname()); - check_overflow; - } else { - p += sprintf(p, "%.*s", (int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision), gras_os_myname()); - check_overflow; - precision = -1; - } - break; - case 't': /* thread name; LOG4J compliant */ - if (precision == -1) { - p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer), "%s", xbt_thread_self_name()); - check_overflow; - } else { - p += sprintf(p, "%.*s", (int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision), xbt_thread_self_name()); - check_overflow; - precision = -1; - } - break; - case 'P': /* process name; SimGrid extension */ - if (precision == -1) { - p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer), "%s", xbt_procname()); - check_overflow; - } else { - p += sprintf(p, "%.*s", (int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision),xbt_procname()); - check_overflow; - precision = -1; - } - break; - case 'i': /* process PID name; SimGrid extension */ - if (precision == -1) { - p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer), "%d", (*xbt_getpid)()); - check_overflow; - } else { - p += sprintf(p, "%.*d", (int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision), (*xbt_getpid)()); - check_overflow; - precision = -1; - } - break; - - case 'F': /* file name; LOG4J compliant */ - if (precision == -1) { - p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer),"%s",ev->fileName); - check_overflow; - } else { - p += sprintf(p,"%.*s",(int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision), ev->fileName); - check_overflow; - precision = -1; - } - break; - case 'l': /* location; LOG4J compliant */ - if (precision == -1) { - p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer), "%s:%d", ev->fileName, ev->lineNum); - check_overflow; - } else { - p += snprintf(p, (int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision), "%s:%d", ev->fileName, ev->lineNum); - check_overflow; - precision = -1; - } - break; - case 'L': /* line number; LOG4J compliant */ - if (precision == -1) { - p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer), "%d", ev->lineNum); - check_overflow; - } else { - p += sprintf(p, "%.*d", (int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision), ev->lineNum); - check_overflow; - precision = -1; - } - break; - case 'M': /* method (ie, function) name; LOG4J compliant */ - if (precision == -1) { - p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer), "%s", ev->functionName); - check_overflow; - } else { - p += sprintf(p, "%.*s", (int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision), ev->functionName); - check_overflow; - precision = -1; - } - break; - case 'b': /* backtrace; called %throwable in LOG4J */ - case 'B': /* short backtrace; called %throwable{short} in LOG4J */ + if (precision == -1) { + p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer),"%s",ev->cat->name); + check_overflow; + } else { + p += sprintf(p,"%.*s",(int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision),ev->cat->name); + check_overflow; + precision = -1; + } + break; + case 'p': /* priority name; LOG4J compliant */ + if (precision == -1) { + p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer), "%s", xbt_log_priority_names[ev->priority] ); + check_overflow; + } else { + p += sprintf(p, "%.*s", (int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision), xbt_log_priority_names[ev->priority] ); + check_overflow; + precision = -1; + } + break; + + case 'h': /* host name; SimGrid extension */ + if (precision == -1) { + p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer), "%s", gras_os_myname()); + check_overflow; + } else { + p += sprintf(p, "%.*s", (int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision), gras_os_myname()); + check_overflow; + precision = -1; + } + break; + case 't': /* thread name; LOG4J compliant */ + if (precision == -1) { + p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer), "%s", xbt_thread_self_name()); + check_overflow; + } else { + p += sprintf(p, "%.*s", (int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision), xbt_thread_self_name()); + check_overflow; + precision = -1; + } + break; + case 'P': /* process name; SimGrid extension */ + if (precision == -1) { + p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer), "%s", xbt_procname()); + check_overflow; + } else { + p += sprintf(p, "%.*s", (int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision),xbt_procname()); + check_overflow; + precision = -1; + } + break; + case 'i': /* process PID name; SimGrid extension */ + if (precision == -1) { + p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer), "%d", (*xbt_getpid)()); + check_overflow; + } else { + p += sprintf(p, "%.*d", (int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision), (*xbt_getpid)()); + check_overflow; + precision = -1; + } + break; + + case 'F': /* file name; LOG4J compliant */ + if (precision == -1) { + p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer),"%s",ev->fileName); + check_overflow; + } else { + p += sprintf(p,"%.*s",(int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision), ev->fileName); + check_overflow; + precision = -1; + } + break; + case 'l': /* location; LOG4J compliant */ + if (precision == -1) { + p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer), "%s:%d", ev->fileName, ev->lineNum); + check_overflow; + } else { + p += snprintf(p, (int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision), "%s:%d", ev->fileName, ev->lineNum); + check_overflow; + precision = -1; + } + break; + case 'L': /* line number; LOG4J compliant */ + if (precision == -1) { + p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer), "%d", ev->lineNum); + check_overflow; + } else { + p += sprintf(p, "%.*d", (int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision), ev->lineNum); + check_overflow; + precision = -1; + } + break; + case 'M': /* method (ie, function) name; LOG4J compliant */ + if (precision == -1) { + p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer), "%s", ev->functionName); + check_overflow; + } else { + p += sprintf(p, "%.*s", (int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision), ev->functionName); + check_overflow; + precision = -1; + } + break; + case 'b': /* backtrace; called %throwable in LOG4J */ + case 'B': /* short backtrace; called %throwable{short} in LOG4J */ #if defined(HAVE_EXECINFO_H) && defined(HAVE_POPEN) && defined(ADDR2LINE) - { - xbt_ex_t e; - int i; - - e.used = backtrace((void**)e.bt,XBT_BACKTRACE_SIZE); - e.bt_strings = NULL; - e.msg=NULL; - e.remote=0; - xbt_backtrace_current(&e); - if (*q=='B') { - if (precision == -1) { - p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer),"%s",e.bt_strings[2]+8); - check_overflow; - } else { - p += sprintf(p,"%.*s",(int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision), e.bt_strings[2]+8); - check_overflow; - precision = -1; - } - } else { - for (i=2; ibuffer),"%s\n",e.bt_strings[i]+8); - check_overflow; - } else { - p += sprintf(p,"%.*s\n",(int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision),e.bt_strings[i]+8); - check_overflow; - precision = -1; - } - } - - xbt_ex_free(e); - } + { + xbt_ex_t e; + int i; + + e.used = backtrace((void**)e.bt,XBT_BACKTRACE_SIZE); + e.bt_strings = NULL; + e.msg=NULL; + e.remote=0; + xbt_backtrace_current(&e); + if (*q=='B') { + if (precision == -1) { + p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer),"%s",e.bt_strings[2]+8); + check_overflow; + } else { + p += sprintf(p,"%.*s",(int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision), e.bt_strings[2]+8); + check_overflow; + precision = -1; + } + } else { + for (i=2; ibuffer),"%s\n",e.bt_strings[i]+8); + check_overflow; + } else { + p += sprintf(p,"%.*s\n",(int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision),e.bt_strings[i]+8); + check_overflow; + precision = -1; + } + } + + xbt_ex_free(e); + } #else - p+=snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer),"(no backtrace on this arch)"); - check_overflow; + p+=snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer),"(no backtrace on this arch)"); + check_overflow; #endif - break; - - case 'd': /* date; LOG4J compliant */ - if (precision == -1) { - p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer),"%f", gras_os_time()); - check_overflow; - } else { - p += sprintf(p,"%.*f", (int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision), gras_os_time()); - check_overflow; - precision = -1; - } - break; - case 'r': /* application age; LOG4J compliant */ - if (precision == -1) { - p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer),"%f", gras_os_time()-begin_of_time); - check_overflow; - } else { - p += sprintf(p,"%.*f", (int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision), gras_os_time()-begin_of_time); - check_overflow; - precision = -1; - } - break; - - case 'm': /* user-provided message; LOG4J compliant */ - if (precision == -1) { - p += vsnprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer), msg_fmt, ev->ap); - check_overflow; - } else { - p += vsnprintf(p, (int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision), msg_fmt, ev->ap); - check_overflow; - precision = -1; - } - break; - - default: - fprintf(stderr,ERRMSG,*q,(char*)l->data); - abort(); + break; + + case 'd': /* date; LOG4J compliant */ + if (precision == -1) { + p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer),"%f", gras_os_time()); + check_overflow; + } else { + p += sprintf(p,"%.*f", (int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision), gras_os_time()); + check_overflow; + precision = -1; + } + break; + case 'r': /* application age; LOG4J compliant */ + if (precision == -1) { + p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer),"%f", gras_os_time()-begin_of_time); + check_overflow; + } else { + p += sprintf(p,"%.*f", (int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision), gras_os_time()-begin_of_time); + check_overflow; + precision = -1; + } + break; + + case 'm': /* user-provided message; LOG4J compliant */ + if (precision == -1) { + p += vsnprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer), msg_fmt, ev->ap); + check_overflow; + } else { + p += vsnprintf(p, (int)MIN(XBT_LOG_BUFF_SIZE-(p-ev->buffer),precision), msg_fmt, ev->ap); + check_overflow; + precision = -1; + } + break; + + default: + fprintf(stderr,ERRMSG,*q,(char*)l->data); + abort(); } q++; } else { *(p++) = *(q++); - check_overflow; + check_overflow; } } *p = '\0'; diff --git a/src/xbt/xbt_log_layout_simple.c b/src/xbt/xbt_log_layout_simple.c index 867294cbe3..17e18b86bc 100644 --- a/src/xbt/xbt_log_layout_simple.c +++ b/src/xbt/xbt_log_layout_simple.c @@ -21,58 +21,58 @@ extern const char *xbt_log_priority_names[7]; static double begin_of_time = -1; static void xbt_log_layout_simple_dynamic(xbt_log_layout_t l, - xbt_log_event_t ev, - const char*fmt, - xbt_log_appender_t app) { - xbt_strbuff_t buff = xbt_strbuff_new(); - char loc_buff[256]; - char *p; - - /* Put every static information in a static buffer, and copy them in the dyn one */ - p = loc_buff; - p += snprintf(p,256-(p-ev->buffer),"["); - - if(strlen(xbt_procname())) - p += snprintf(p,256-(p-ev->buffer),"%s:%s:(%d) ", - gras_os_myname(), xbt_procname(),(*xbt_getpid)()); - p += snprintf(p,256-(p-ev->buffer),"%f] ", gras_os_time()-begin_of_time); - if (ev->priority != xbt_log_priority_info) - p += snprintf(p,256-(p-ev->buffer), "%s:%d: ", ev->fileName, ev->lineNum); - p += snprintf(p,256-(p-ev->buffer), "[%s/%s] ", - ev->cat->name, xbt_log_priority_names[ev->priority] ); - - xbt_strbuff_append(buff,loc_buff); - - vasprintf(&p,fmt,ev->ap_copy); - xbt_strbuff_append(buff,p); - free(p); - - xbt_strbuff_append(buff,"\n"); - - app->do_append(app,buff->data); - xbt_strbuff_free(buff); + xbt_log_event_t ev, + const char*fmt, + xbt_log_appender_t app) { + xbt_strbuff_t buff = xbt_strbuff_new(); + char loc_buff[256]; + char *p; + + /* Put every static information in a static buffer, and copy them in the dyn one */ + p = loc_buff; + p += snprintf(p,256-(p-ev->buffer),"["); + + if(strlen(xbt_procname())) + p += snprintf(p,256-(p-ev->buffer),"%s:%s:(%d) ", + gras_os_myname(), xbt_procname(),(*xbt_getpid)()); + p += snprintf(p,256-(p-ev->buffer),"%f] ", gras_os_time()-begin_of_time); + if (ev->priority != xbt_log_priority_info) + p += snprintf(p,256-(p-ev->buffer), "%s:%d: ", ev->fileName, ev->lineNum); + p += snprintf(p,256-(p-ev->buffer), "[%s/%s] ", + ev->cat->name, xbt_log_priority_names[ev->priority] ); + + xbt_strbuff_append(buff,loc_buff); + + vasprintf(&p,fmt,ev->ap_copy); + xbt_strbuff_append(buff,p); + free(p); + + xbt_strbuff_append(buff,"\n"); + + app->do_append(app,buff->data); + xbt_strbuff_free(buff); } /* only used after the format using: we suppose that the buffer is big enough to display our data */ #define check_overflow \ if (p-ev->buffer > XBT_LOG_BUFF_SIZE) { /* buffer overflow */ \ - xbt_log_layout_simple_dynamic(l,ev,fmt,app); \ - return; \ - } + xbt_log_layout_simple_dynamic(l,ev,fmt,app); \ + return; \ + } static void xbt_log_layout_simple_doit(xbt_log_layout_t l, - xbt_log_event_t ev, - const char *fmt, - xbt_log_appender_t app) { - char *p; + xbt_log_event_t ev, + const char *fmt, + xbt_log_appender_t app) { + char *p; xbt_assert0(ev->priority>=0, - "Negative logging priority naturally forbidden"); + "Negative logging priority naturally forbidden"); xbt_assert1(ev->prioritypriority); + "Priority %d is greater than the biggest allowed value", + ev->priority); - if (begin_of_time<0) + if (begin_of_time<0) begin_of_time=gras_os_time(); p = ev->buffer; @@ -81,11 +81,11 @@ static void xbt_log_layout_simple_doit(xbt_log_layout_t l, /* Display the proc info if available */ if(strlen(xbt_procname())) { - p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer),"%s:%s:(%d) ", - gras_os_myname(), xbt_procname(),(*xbt_getpid)()); + p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer),"%s:%s:(%d) ", + gras_os_myname(), xbt_procname(),(*xbt_getpid)()); check_overflow; } - + /* Display the date */ p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer),"%f] ", gras_os_time()-begin_of_time); check_overflow; @@ -95,13 +95,13 @@ static void xbt_log_layout_simple_doit(xbt_log_layout_t l, p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer), "%s:%d: ", ev->fileName, ev->lineNum); /* Display category name */ - p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer), "[%s/%s] ", - ev->cat->name, xbt_log_priority_names[ev->priority] ); + p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer), "[%s/%s] ", + ev->cat->name, xbt_log_priority_names[ev->priority] ); /* Display user-provided message */ p += vsnprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer), fmt, ev->ap); check_overflow; - + /* End it */ p += snprintf(p,XBT_LOG_BUFF_SIZE-(p-ev->buffer), "\n"); check_overflow; diff --git a/src/xbt/xbt_main.c b/src/xbt/xbt_main.c index e96f666f18..54c9ac61a6 100644 --- a/src/xbt/xbt_main.c +++ b/src/xbt/xbt_main.c @@ -47,7 +47,7 @@ XBT_LOG_EXTERNAL_CATEGORY(xbt_set); XBT_LOG_EXTERNAL_CATEGORY(xbt_sync_os); /** @brief Initialize the xbt mechanisms. */ -void +void xbt_init(int *argc, char **argv) { xbt_initialized++; @@ -62,13 +62,13 @@ xbt_init(int *argc, char **argv) { XBT_LOG_CONNECT(strbuff, xbt); XBT_LOG_CONNECT(xbt_cfg, xbt); XBT_LOG_CONNECT(xbt_dict, xbt); - XBT_LOG_CONNECT(xbt_dict_add, xbt_dict); - XBT_LOG_CONNECT(xbt_dict_collapse, xbt_dict); - XBT_LOG_CONNECT(xbt_dict_cursor, xbt_dict); - XBT_LOG_CONNECT(xbt_dict_elm, xbt_dict); - XBT_LOG_CONNECT(xbt_dict_multi, xbt_dict); - XBT_LOG_CONNECT(xbt_dict_remove, xbt_dict); - XBT_LOG_CONNECT(xbt_dict_search, xbt_dict); + XBT_LOG_CONNECT(xbt_dict_add, xbt_dict); + XBT_LOG_CONNECT(xbt_dict_collapse, xbt_dict); + XBT_LOG_CONNECT(xbt_dict_cursor, xbt_dict); + XBT_LOG_CONNECT(xbt_dict_elm, xbt_dict); + XBT_LOG_CONNECT(xbt_dict_multi, xbt_dict); + XBT_LOG_CONNECT(xbt_dict_remove, xbt_dict); + XBT_LOG_CONNECT(xbt_dict_search, xbt_dict); XBT_LOG_CONNECT(xbt_dyn, xbt); XBT_LOG_CONNECT(xbt_ex, xbt); XBT_LOG_CONNECT(xbt_fifo, xbt); @@ -77,11 +77,11 @@ xbt_init(int *argc, char **argv) { XBT_LOG_CONNECT(xbt_queue, xbt); XBT_LOG_CONNECT(xbt_set, xbt); XBT_LOG_CONNECT(xbt_sync_os, xbt); - + xbt_binary_name = xbt_strdup(argv[0]); srand((unsigned int)time(NULL)); VERB0("Initialize XBT"); - + xbt_backtrace_init(); xbt_log_init(argc,argv); xbt_os_thread_mod_init(); @@ -89,7 +89,7 @@ xbt_init(int *argc, char **argv) { } /** @brief Finalize the xbt mechanisms. */ -void +void xbt_exit(){ xbt_initialized--; if (xbt_initialized == 0) { @@ -107,11 +107,11 @@ xbt_exit(){ /* these two functions belong to xbt/sysdep.h, which have no corresponding .c file */ /** @brief like free, but you can be sure that it is a function */ XBT_PUBLIC(void) xbt_free_f(void* p) { - free(p); + free(p); } /** @brief should be given a pointer to pointer, and frees the second one */ XBT_PUBLIC(void) xbt_free_ref(void *d){ - free(*(void**)d); + free(*(void**)d); } diff --git a/src/xbt/xbt_matrix.c b/src/xbt/xbt_matrix.c index 53ac04041c..32a28af4f8 100644 --- a/src/xbt/xbt_matrix.c +++ b/src/xbt/xbt_matrix.c @@ -15,28 +15,28 @@ XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_matrix,xbt,"2D data storage"); /** \brief constructor */ -xbt_matrix_t xbt_matrix_new(int lines, int rows, - const unsigned long elmsize, - void_f_pvoid_t const free_f) { - xbt_matrix_t res=xbt_new(s_xbt_matrix_t, 1); - res->lines = lines; - res->rows = rows; - res->elmsize = elmsize; - res->free_f = free_f; - res->data = xbt_malloc(elmsize*lines*rows); - return res; +xbt_matrix_t xbt_matrix_new(int lines, int rows, + const unsigned long elmsize, + void_f_pvoid_t const free_f) { + xbt_matrix_t res=xbt_new(s_xbt_matrix_t, 1); + res->lines = lines; + res->rows = rows; + res->elmsize = elmsize; + res->free_f = free_f; + res->data = xbt_malloc(elmsize*lines*rows); + return res; } /** \brief Creates a matrix being a submatrix of another one */ -xbt_matrix_t xbt_matrix_new_sub(xbt_matrix_t from, - int lsize, int rsize, - int lpos, int rpos, - pvoid_f_pvoid_t const cpy_f) { - - xbt_matrix_t res=xbt_matrix_new(lsize,rsize, - from->elmsize, from->free_f); - xbt_matrix_copy_values(res,from,lsize,rsize,0,0,lpos,rpos,cpy_f); - return res; +xbt_matrix_t xbt_matrix_new_sub(xbt_matrix_t from, + int lsize, int rsize, + int lpos, int rpos, + pvoid_f_pvoid_t const cpy_f) { + + xbt_matrix_t res=xbt_matrix_new(lsize,rsize, + from->elmsize, from->free_f); + xbt_matrix_copy_values(res,from,lsize,rsize,0,0,lpos,rpos,cpy_f); + return res; } /** \brief destructor */ @@ -45,7 +45,7 @@ void xbt_matrix_free(xbt_matrix_t mat) { if (mat) { if (mat->free_f) { for (i=0; i < (mat->lines * mat->rows) ; i++) { - (*(mat->free_f))( (void*)& (mat->data[i*mat->elmsize]) ); + (*(mat->free_f))( (void*)& (mat->data[i*mat->elmsize]) ); } } free(mat->data); @@ -55,25 +55,25 @@ void xbt_matrix_free(xbt_matrix_t mat) { /** \brief Freeing function for containers of xbt_matrix_t */ void xbt_matrix_free_voidp(void *d) { - xbt_matrix_free( (xbt_matrix_t) *(void**)d ); + xbt_matrix_free( (xbt_matrix_t) *(void**)d ); } -/** \brief Display the content of a matrix (debugging purpose) +/** \brief Display the content of a matrix (debugging purpose) * \param coords: boolean indicating whether we should add the coords of each cell to the output*/ void xbt_matrix_dump(xbt_matrix_t matrix, const char*name, int coords, - void_f_pvoid_t display_fun) { + void_f_pvoid_t display_fun) { unsigned int i,j; fprintf(stderr,">>> Matrix %s dump (%d x %d)\n",name,matrix->lines,matrix->rows); for (i=0; ilines; i++) { fprintf(stderr," "); for (j=0; jrows; j++) { - if (coords) - fprintf(stderr," (%d,%d)=",i,j); - else - fprintf(stderr," "); - (*display_fun)(xbt_matrix_get_ptr(matrix,i,j)); + if (coords) + fprintf(stderr," (%d,%d)=",i,j); + else + fprintf(stderr," "); + (*display_fun)(xbt_matrix_get_ptr(matrix,i,j)); } fprintf(stderr,"\n"); } @@ -94,45 +94,45 @@ void xbt_matrix_dump_display_double(void*d) { * \param rpos_src: row offset on destination matrix */ void xbt_matrix_copy_values(xbt_matrix_t dst, xbt_matrix_t src, - unsigned int lsize, unsigned int rsize, - unsigned int lpos_dst,unsigned int rpos_dst, - unsigned int lpos_src,unsigned int rpos_src, - pvoid_f_pvoid_t const cpy_f) { - unsigned int i,j; - - DEBUG10("Copy a %dx%d submatrix from %dx%d(of %dx%d) to %dx%d (of %dx%d)", - lsize,rsize, - lpos_src,rpos_src,src->lines,src->rows, - lpos_dst,rpos_dst,dst->lines,dst->rows); - - /* everybody knows that issue is between the chair and the screen (particulary in my office) */ - xbt_assert(src->elmsize == dst->elmsize); - /* don't check free_f since the user may play weird games with this */ - - xbt_assert(lpos_src+lsize <= src->lines); - xbt_assert(rpos_src+rsize <= src->rows); - - xbt_assert(lpos_dst+lsize <= dst->lines); - xbt_assert(rpos_dst+rsize <= dst->rows); - - /* Lets get serious here */ - for (i=0;ielmsize*lsize); - } - } + unsigned int lsize, unsigned int rsize, + unsigned int lpos_dst,unsigned int rpos_dst, + unsigned int lpos_src,unsigned int rpos_src, + pvoid_f_pvoid_t const cpy_f) { + unsigned int i,j; + + DEBUG10("Copy a %dx%d submatrix from %dx%d(of %dx%d) to %dx%d (of %dx%d)", + lsize,rsize, + lpos_src,rpos_src,src->lines,src->rows, + lpos_dst,rpos_dst,dst->lines,dst->rows); + + /* everybody knows that issue is between the chair and the screen (particulary in my office) */ + xbt_assert(src->elmsize == dst->elmsize); + /* don't check free_f since the user may play weird games with this */ + + xbt_assert(lpos_src+lsize <= src->lines); + xbt_assert(rpos_src+rsize <= src->rows); + + xbt_assert(lpos_dst+lsize <= dst->lines); + xbt_assert(rpos_dst+rsize <= dst->rows); + + /* Lets get serious here */ + for (i=0;ielmsize*lsize); + } + } } /** \brief Creates a new matrix of double filled with zeros */ xbt_matrix_t xbt_matrix_double_new_zeros(int lines, int rows) { xbt_matrix_t res = xbt_matrix_new(lines, rows,sizeof(double),NULL); - + memset(res->data,0, res->elmsize * res->lines * res->rows); return res; } @@ -141,8 +141,8 @@ xbt_matrix_t xbt_matrix_double_new_zeros(int lines, int rows) { xbt_matrix_t xbt_matrix_double_new_id(int lines, int rows) { xbt_matrix_t res = xbt_matrix_double_new_zeros(lines, rows); int i; - - for (i=0; idata[i*res->elmsize] = i; + *(double*)&res->data[i*res->elmsize] = i; return res; } @@ -178,19 +178,19 @@ xbt_matrix_t xbt_matrix_double_new_mult(xbt_matrix_t A,xbt_matrix_t B) { /** \brief add to C the result of A*B */ void xbt_matrix_double_addmult(xbt_matrix_t A,xbt_matrix_t B, - /*OUT*/ xbt_matrix_t C) { + /*OUT*/ xbt_matrix_t C) { unsigned int i,j,k; xbt_assert2(A->lines == C->lines, - "A->lines != C->lines (%d vs %d)",A->lines,C->lines); + "A->lines != C->lines (%d vs %d)",A->lines,C->lines); xbt_assert(B->rows == C->rows); - - for (i=0; ilines; i++) - for (j=0; jrows; j++) - for (k=0; klines; k++) - xbt_matrix_get_as(C,i,j,double) += - xbt_matrix_get_as(A,i,k,double) * xbt_matrix_get_as(B,k,j,double); + + for (i=0; ilines; i++) + for (j=0; jrows; j++) + for (k=0; klines; k++) + xbt_matrix_get_as(C,i,j,double) += + xbt_matrix_get_as(A,i,k,double) * xbt_matrix_get_as(B,k,j,double); } - + diff --git a/src/xbt/xbt_os_thread.c b/src/xbt/xbt_os_thread.c index 46196d6be7..b3f41ba8de 100644 --- a/src/xbt/xbt_os_thread.c +++ b/src/xbt/xbt_os_thread.c @@ -29,22 +29,22 @@ XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_sync_os,xbt,"Synchronization mechanism (OS-l #ifdef HAVE_MUTEX_TIMEDLOCK /* redefine the function header since we fail to get this from system headers on amd (at least) */ int pthread_mutex_timedlock(pthread_mutex_t *mutex, - const struct timespec *abs_timeout); + const struct timespec *abs_timeout); #endif - + /* use named sempahore when sem_init() does not work */ #ifndef HAVE_SEM_INIT - static int next_sem_ID = 0; - static xbt_os_mutex_t next_sem_ID_lock; +static int next_sem_ID = 0; +static xbt_os_mutex_t next_sem_ID_lock; #endif typedef struct xbt_os_thread_ { - pthread_t t; - char *name; - void *param; - pvoid_f_pvoid_t start_routine; - ex_ctx_t *exception; + pthread_t t; + char *name; + void *param; + pvoid_f_pvoid_t start_routine; + ex_ctx_t *exception; } s_xbt_os_thread_t ; static xbt_os_thread_t main_thread = NULL; @@ -54,7 +54,7 @@ static int thread_mod_inited = 0; /* frees the xbt_os_thread_t corresponding to the current thread */ static void xbt_os_thread_free_thread_data(void*d){ - free(d); + free(d); } /* callback: context fetching */ @@ -71,44 +71,44 @@ static void _os_thread_ex_terminate(xbt_ex_t * e) { } void xbt_os_thread_mod_init(void) { - int errcode; + int errcode; - if (thread_mod_inited) - return; + if (thread_mod_inited) + return; - if ((errcode=pthread_key_create(&xbt_self_thread_key, NULL))) - THROW0(system_error,errcode,"pthread_key_create failed for xbt_self_thread_key"); + if ((errcode=pthread_key_create(&xbt_self_thread_key, NULL))) + THROW0(system_error,errcode,"pthread_key_create failed for xbt_self_thread_key"); - main_thread=xbt_new(s_xbt_os_thread_t,1); - main_thread->name = (char*)"main"; - main_thread->start_routine = NULL; - main_thread->param = NULL; - main_thread->exception = xbt_new(ex_ctx_t, 1); - XBT_CTX_INITIALIZE(main_thread->exception); + main_thread=xbt_new(s_xbt_os_thread_t,1); + main_thread->name = (char*)"main"; + main_thread->start_routine = NULL; + main_thread->param = NULL; + main_thread->exception = xbt_new(ex_ctx_t, 1); + XBT_CTX_INITIALIZE(main_thread->exception); - __xbt_ex_ctx = _os_thread_ex_ctx; - __xbt_ex_terminate = _os_thread_ex_terminate; + __xbt_ex_ctx = _os_thread_ex_ctx; + __xbt_ex_terminate = _os_thread_ex_terminate; - thread_mod_inited = 1; - - #ifndef HAVE_SEM_WAIT - next_sem_ID_lock = xbt_os_mutex_init(); - #endif + thread_mod_inited = 1; + +#ifndef HAVE_SEM_WAIT + next_sem_ID_lock = xbt_os_mutex_init(); +#endif } void xbt_os_thread_mod_exit(void) { - /* FIXME: don't try to free our key on shutdown. + /* FIXME: don't try to free our key on shutdown. Valgrind detects no leak if we don't, and whine if we try to */ -// int errcode; - -// if ((errcode=pthread_key_delete(xbt_self_thread_key))) -// THROW0(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key"); - free(main_thread->exception); - free(main_thread); - main_thread = NULL; - thread_mod_inited=0; + // int errcode; + + // if ((errcode=pthread_key_delete(xbt_self_thread_key))) + // THROW0(system_error,errcode,"pthread_key_delete failed for xbt_self_thread_key"); + free(main_thread->exception); + free(main_thread); + main_thread = NULL; + thread_mod_inited=0; #ifndef HAVE_SEM_WAIT - xbt_os_mutex_destroy(next_sem_ID_lock); + xbt_os_mutex_destroy(next_sem_ID_lock); #endif } @@ -118,38 +118,38 @@ static void * wrapper_start_routine(void *s) { if ((errcode=pthread_setspecific(xbt_self_thread_key,t))) THROW0(system_error,errcode, - "pthread_setspecific failed for xbt_self_thread_key"); + "pthread_setspecific failed for xbt_self_thread_key"); return (*(t->start_routine))(t->param); } xbt_os_thread_t xbt_os_thread_create(const char*name, - pvoid_f_pvoid_t start_routine, - void* param) { - int errcode; + pvoid_f_pvoid_t start_routine, + void* param) { + int errcode; - xbt_os_thread_t res_thread=xbt_new(s_xbt_os_thread_t,1); - res_thread->name = xbt_strdup(name); - res_thread->start_routine = start_routine; - res_thread->param = param; - res_thread->exception = xbt_new(ex_ctx_t, 1); - XBT_CTX_INITIALIZE(res_thread->exception); + xbt_os_thread_t res_thread=xbt_new(s_xbt_os_thread_t,1); + res_thread->name = xbt_strdup(name); + res_thread->start_routine = start_routine; + res_thread->param = param; + res_thread->exception = xbt_new(ex_ctx_t, 1); + XBT_CTX_INITIALIZE(res_thread->exception); - if ((errcode = pthread_create(&(res_thread->t), NULL, - wrapper_start_routine, res_thread))) - THROW1(system_error,errcode, - "pthread_create failed: %s",strerror(errcode)); + if ((errcode = pthread_create(&(res_thread->t), NULL, + wrapper_start_routine, res_thread))) + THROW1(system_error,errcode, + "pthread_create failed: %s",strerror(errcode)); - return res_thread; + return res_thread; } const char* xbt_os_thread_name(xbt_os_thread_t t) { - return t->name; + return t->name; } const char* xbt_os_thread_self_name(void) { - xbt_os_thread_t self = xbt_os_thread_self(); - return self?self->name:"main"; + xbt_os_thread_t self = xbt_os_thread_self(); + return self?self->name:"main"; } void xbt_os_thread_join(xbt_os_thread_t thread,void ** thread_return) { @@ -158,21 +158,21 @@ xbt_os_thread_join(xbt_os_thread_t thread,void ** thread_return) { if ((errcode = pthread_join(thread->t,thread_return))) THROW1(system_error,errcode, "pthread_join failed: %s", - strerror(errcode)); - if (thread->exception) - free(thread->exception); + strerror(errcode)); + if (thread->exception) + free(thread->exception); - if (thread->name) - free(thread->name); - - if (thread == main_thread) /* just killed main thread */ - main_thread = NULL; + if (thread->name) + free(thread->name); - free(thread); + if (thread == main_thread) /* just killed main thread */ + main_thread = NULL; + + free(thread); } void xbt_os_thread_exit(int *retval) { - pthread_exit(retval); + pthread_exit(retval); } xbt_os_thread_t xbt_os_thread_self(void) { @@ -190,199 +190,199 @@ xbt_os_thread_t xbt_os_thread_self(void) { #include void xbt_os_thread_yield(void) { - sched_yield(); + sched_yield(); } void xbt_os_thread_cancel(xbt_os_thread_t t) { - pthread_cancel(t->t); + pthread_cancel(t->t); } /****** mutex related functions ******/ typedef struct xbt_os_mutex_ { /* KEEP IT IN SYNC WITH xbt_thread.c */ - pthread_mutex_t m; + pthread_mutex_t m; } s_xbt_os_mutex_t; #include #include xbt_os_mutex_t xbt_os_mutex_init(void) { - xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t,1); - int errcode; + xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t,1); + int errcode; - if ((errcode = pthread_mutex_init(&(res->m),NULL))) - THROW1(system_error,errcode,"pthread_mutex_init() failed: %s", - strerror(errcode)); + if ((errcode = pthread_mutex_init(&(res->m),NULL))) + THROW1(system_error,errcode,"pthread_mutex_init() failed: %s", + strerror(errcode)); - return res; + return res; } void xbt_os_mutex_acquire(xbt_os_mutex_t mutex) { - int errcode; + int errcode; - if ((errcode=pthread_mutex_lock(&(mutex->m)))) - THROW2(system_error,errcode,"pthread_mutex_lock(%p) failed: %s", - mutex, strerror(errcode)); + if ((errcode=pthread_mutex_lock(&(mutex->m)))) + THROW2(system_error,errcode,"pthread_mutex_lock(%p) failed: %s", + mutex, strerror(errcode)); } void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay) { - int errcode; - - if (delay < 0) { - xbt_os_mutex_acquire(mutex); - - } else if (delay == 0) { - errcode=pthread_mutex_trylock(&(mutex->m)); - - switch (errcode) { - case 0: - return; - case ETIMEDOUT: - THROW1(timeout_error,0,"mutex %p not ready",mutex); - default: - THROW2(system_error,errcode,"xbt_mutex_timedacquire(%p) failed: %s",mutex, strerror(errcode)); - } - - - } else { - + int errcode; + + if (delay < 0) { + xbt_os_mutex_acquire(mutex); + + } else if (delay == 0) { + errcode=pthread_mutex_trylock(&(mutex->m)); + + switch (errcode) { + case 0: + return; + case ETIMEDOUT: + THROW1(timeout_error,0,"mutex %p not ready",mutex); + default: + THROW2(system_error,errcode,"xbt_mutex_timedacquire(%p) failed: %s",mutex, strerror(errcode)); + } + + + } else { + #ifdef HAVE_MUTEX_TIMEDLOCK - struct timespec ts_end; - double end = delay + xbt_os_time(); - - ts_end.tv_sec = (time_t) floor(end); - ts_end.tv_nsec = (long) ( ( end - ts_end.tv_sec) * 1000000000); - DEBUG2("pthread_mutex_timedlock(%p,%p)",&(mutex->m), &ts_end); - - errcode=pthread_mutex_timedlock(&(mutex->m),&ts_end); - + struct timespec ts_end; + double end = delay + xbt_os_time(); + + ts_end.tv_sec = (time_t) floor(end); + ts_end.tv_nsec = (long) ( ( end - ts_end.tv_sec) * 1000000000); + DEBUG2("pthread_mutex_timedlock(%p,%p)",&(mutex->m), &ts_end); + + errcode=pthread_mutex_timedlock(&(mutex->m),&ts_end); + #else /* Well, let's reimplement it since those lazy libc dudes didn't */ - double start = xbt_os_time(); - do { - errcode = pthread_mutex_trylock(&(mutex->m)); - if (errcode == EBUSY) - xbt_os_thread_yield(); - } while (errcode == EBUSY && xbt_os_time()-start m)); if (errcode == EBUSY) - errcode = ETIMEDOUT; - + xbt_os_thread_yield(); + } while (errcode == EBUSY && xbt_os_time()-start m)))) - THROW2(system_error,errcode,"pthread_mutex_unlock(%p) failed: %s", - mutex, strerror(errcode)); + if ((errcode=pthread_mutex_unlock(&(mutex->m)))) + THROW2(system_error,errcode,"pthread_mutex_unlock(%p) failed: %s", + mutex, strerror(errcode)); } void xbt_os_mutex_destroy(xbt_os_mutex_t mutex) { - int errcode; + int errcode; - if (!mutex) return; + if (!mutex) return; - if ((errcode=pthread_mutex_destroy(&(mutex->m)))) - THROW2(system_error,errcode,"pthread_mutex_destroy(%p) failed: %s", - mutex, strerror(errcode)); - free(mutex); + if ((errcode=pthread_mutex_destroy(&(mutex->m)))) + THROW2(system_error,errcode,"pthread_mutex_destroy(%p) failed: %s", + mutex, strerror(errcode)); + free(mutex); } /***** condition related functions *****/ typedef struct xbt_os_cond_ { /* KEEP IT IN SYNC WITH xbt_thread.c */ - pthread_cond_t c; + pthread_cond_t c; } s_xbt_os_cond_t; xbt_os_cond_t xbt_os_cond_init(void) { - xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t,1); - int errcode; - if ((errcode=pthread_cond_init(&(res->c),NULL))) - THROW1(system_error,errcode,"pthread_cond_init() failed: %s", - strerror(errcode)); + xbt_os_cond_t res = xbt_new(s_xbt_os_cond_t,1); + int errcode; + if ((errcode=pthread_cond_init(&(res->c),NULL))) + THROW1(system_error,errcode,"pthread_cond_init() failed: %s", + strerror(errcode)); - return res; + return res; } void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex) { - int errcode; - if ((errcode=pthread_cond_wait(&(cond->c),&(mutex->m)))) - THROW3(system_error,errcode,"pthread_cond_wait(%p,%p) failed: %s", - cond,mutex, strerror(errcode)); + int errcode; + if ((errcode=pthread_cond_wait(&(cond->c),&(mutex->m)))) + THROW3(system_error,errcode,"pthread_cond_wait(%p,%p) failed: %s", + cond,mutex, strerror(errcode)); } void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex, double delay) { - int errcode; - struct timespec ts_end; - double end = delay + xbt_os_time(); - - if (delay < 0) { - xbt_os_cond_wait(cond,mutex); - } else { - ts_end.tv_sec = (time_t) floor(end); - ts_end.tv_nsec = (long) ( ( end - ts_end.tv_sec) * 1000000000); - DEBUG3("pthread_cond_timedwait(%p,%p,%p)",&(cond->c),&(mutex->m), &ts_end); - switch ( (errcode=pthread_cond_timedwait(&(cond->c),&(mutex->m), &ts_end)) ) { - case 0: - return; - case ETIMEDOUT: - THROW3(timeout_error,errcode,"condition %p (mutex %p) wasn't signaled before timeout (%f)", - cond,mutex, delay); - default: - THROW4(system_error,errcode,"pthread_cond_timedwait(%p,%p,%f) failed: %s", - cond,mutex, delay, strerror(errcode)); - } - } + int errcode; + struct timespec ts_end; + double end = delay + xbt_os_time(); + + if (delay < 0) { + xbt_os_cond_wait(cond,mutex); + } else { + ts_end.tv_sec = (time_t) floor(end); + ts_end.tv_nsec = (long) ( ( end - ts_end.tv_sec) * 1000000000); + DEBUG3("pthread_cond_timedwait(%p,%p,%p)",&(cond->c),&(mutex->m), &ts_end); + switch ( (errcode=pthread_cond_timedwait(&(cond->c),&(mutex->m), &ts_end)) ) { + case 0: + return; + case ETIMEDOUT: + THROW3(timeout_error,errcode,"condition %p (mutex %p) wasn't signaled before timeout (%f)", + cond,mutex, delay); + default: + THROW4(system_error,errcode,"pthread_cond_timedwait(%p,%p,%f) failed: %s", + cond,mutex, delay, strerror(errcode)); + } + } } void xbt_os_cond_signal(xbt_os_cond_t cond) { - int errcode; - if ((errcode=pthread_cond_signal(&(cond->c)))) - THROW2(system_error,errcode,"pthread_cond_signal(%p) failed: %s", - cond, strerror(errcode)); + int errcode; + if ((errcode=pthread_cond_signal(&(cond->c)))) + THROW2(system_error,errcode,"pthread_cond_signal(%p) failed: %s", + cond, strerror(errcode)); } void xbt_os_cond_broadcast(xbt_os_cond_t cond){ - int errcode; - if ((errcode=pthread_cond_broadcast(&(cond->c)))) - THROW2(system_error,errcode,"pthread_cond_broadcast(%p) failed: %s", - cond, strerror(errcode)); + int errcode; + if ((errcode=pthread_cond_broadcast(&(cond->c)))) + THROW2(system_error,errcode,"pthread_cond_broadcast(%p) failed: %s", + cond, strerror(errcode)); } void xbt_os_cond_destroy(xbt_os_cond_t cond){ - int errcode; + int errcode; - if (!cond) return; + if (!cond) return; - if ((errcode=pthread_cond_destroy(&(cond->c)))) - THROW2(system_error,errcode,"pthread_cond_destroy(%p) failed: %s", - cond, strerror(errcode)); - free(cond); + if ((errcode=pthread_cond_destroy(&(cond->c)))) + THROW2(system_error,errcode,"pthread_cond_destroy(%p) failed: %s", + cond, strerror(errcode)); + free(cond); } void *xbt_os_thread_getparam(void) { - xbt_os_thread_t t = xbt_os_thread_self(); - return t?t->param:NULL; + xbt_os_thread_t t = xbt_os_thread_self(); + return t?t->param:NULL; } typedef struct xbt_os_sem_ { - #ifndef HAVE_SEM_INIT - char* name; - #endif - sem_t s; - sem_t *ps; +#ifndef HAVE_SEM_INIT + char* name; +#endif + sem_t s; + sem_t *ps; }s_xbt_os_sem_t ; #ifndef SEM_FAILED @@ -391,144 +391,144 @@ typedef struct xbt_os_sem_ { xbt_os_sem_t xbt_os_sem_init(unsigned int value) { - xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t,1); + xbt_os_sem_t res = xbt_new(s_xbt_os_sem_t,1); - /* On some systems (MAC OS X), only the stub of sem_init is to be found. - * Any attempt to use it leads to ENOSYS (function not implemented). - * If such a prehistoric system is detected, do the job with sem_open instead - */ + /* On some systems (MAC OS X), only the stub of sem_init is to be found. + * Any attempt to use it leads to ENOSYS (function not implemented). + * If such a prehistoric system is detected, do the job with sem_open instead + */ #ifdef HAVE_SEM_INIT - if(sem_init(&(res->s),0,value) != 0) - THROW1(system_error,errno,"sem_init() failed: %s", strerror(errno)); - res->ps = &(res->s); - + if(sem_init(&(res->s),0,value) != 0) + THROW1(system_error,errno,"sem_init() failed: %s", strerror(errno)); + res->ps = &(res->s); + #else /* damn, no sem_init(). Reimplement it */ - xbt_os_mutex_acquire(next_sem_ID_lock); - res->name = bprintf("/%d.%d",(*xbt_getpid)(),++next_sem_ID); - xbt_os_mutex_release(next_sem_ID_lock); - - res->ps = sem_open(res->name, O_CREAT, 0644, value); - if ((res->ps == (sem_t *)SEM_FAILED) && (errno == ENAMETOOLONG)) { - /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */ - res->name[13] = '\0'; - res->ps = sem_open(res->name, O_CREAT, 0644, 1); - } - if ((res->ps == (sem_t *)SEM_FAILED)) - THROW1(system_error,errno,"sem_open() failed: %s",strerror(errno)); - - /* Remove the name from the semaphore namespace: we never join on it */ - if(sem_unlink(res->name) < 0) - THROW1(system_error,errno,"sem_unlink() failed: %s", strerror(errno)); + xbt_os_mutex_acquire(next_sem_ID_lock); + res->name = bprintf("/%d.%d",(*xbt_getpid)(),++next_sem_ID); + xbt_os_mutex_release(next_sem_ID_lock); + + res->ps = sem_open(res->name, O_CREAT, 0644, value); + if ((res->ps == (sem_t *)SEM_FAILED) && (errno == ENAMETOOLONG)) { + /* Old darwins only allow 13 chars. Did you create *that* amount of semaphores? */ + res->name[13] = '\0'; + res->ps = sem_open(res->name, O_CREAT, 0644, 1); + } + if ((res->ps == (sem_t *)SEM_FAILED)) + THROW1(system_error,errno,"sem_open() failed: %s",strerror(errno)); + + /* Remove the name from the semaphore namespace: we never join on it */ + if(sem_unlink(res->name) < 0) + THROW1(system_error,errno,"sem_unlink() failed: %s", strerror(errno)); #endif - return res; + return res; } void xbt_os_sem_acquire(xbt_os_sem_t sem) { - if(!sem) - THROW0(arg_error,EINVAL,"Cannot acquire of the NULL semaphore"); - if(sem_wait(sem->ps) < 0) - THROW1(system_error,errno,"sem_wait() failed: %s", strerror(errno)); + if(!sem) + THROW0(arg_error,EINVAL,"Cannot acquire of the NULL semaphore"); + if(sem_wait(sem->ps) < 0) + THROW1(system_error,errno,"sem_wait() failed: %s", strerror(errno)); } void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double delay) { - int errcode; + int errcode; - if(!sem) - THROW0(arg_error,EINVAL,"Cannot acquire of the NULL semaphore"); + if(!sem) + THROW0(arg_error,EINVAL,"Cannot acquire of the NULL semaphore"); - if (delay < 0) { - xbt_os_sem_acquire(sem); - } else if (delay==0) { - errcode = sem_trywait(sem->ps); + if (delay < 0) { + xbt_os_sem_acquire(sem); + } else if (delay==0) { + errcode = sem_trywait(sem->ps); - switch (errcode) { - case 0: - return; - case ETIMEDOUT: - THROW1(timeout_error,0,"semaphore %p not ready",sem); - default: - THROW2(system_error,errcode,"xbt_os_sem_timedacquire(%p) failed: %s",sem, strerror(errcode)); - } - - } else { + switch (errcode) { + case 0: + return; + case ETIMEDOUT: + THROW1(timeout_error,0,"semaphore %p not ready",sem); + default: + THROW2(system_error,errcode,"xbt_os_sem_timedacquire(%p) failed: %s",sem, strerror(errcode)); + } + + } else { #ifdef HAVE_SEM_WAIT - struct timespec ts_end; - double end = delay + xbt_os_time(); - - ts_end.tv_sec = (time_t) floor(end); - ts_end.tv_nsec = (long) ( ( end - ts_end.tv_sec) * 1000000000); - DEBUG2("sem_timedwait(%p,%p)",sem->ps,&ts_end); - errcode = sem_timedwait(sem->s,&ts_end); - + struct timespec ts_end; + double end = delay + xbt_os_time(); + + ts_end.tv_sec = (time_t) floor(end); + ts_end.tv_nsec = (long) ( ( end - ts_end.tv_sec) * 1000000000); + DEBUG2("sem_timedwait(%p,%p)",sem->ps,&ts_end); + errcode = sem_timedwait(sem->s,&ts_end); + #else /* Okay, reimplement this function then */ - double start = xbt_os_time(); - do { - errcode = sem_trywait(sem->ps); - if (errcode == EBUSY) - xbt_os_thread_yield(); - } while (errcode == EBUSY && xbt_os_time()-start ps); if (errcode == EBUSY) - errcode = ETIMEDOUT; + xbt_os_thread_yield(); + } while (errcode == EBUSY && xbt_os_time()-start ps) < 0) - THROW1(system_error,errno,"sem_post() failed: %s", - strerror(errno)); + if(sem_post(sem->ps) < 0) + THROW1(system_error,errno,"sem_post() failed: %s", + strerror(errno)); } void xbt_os_sem_destroy(xbt_os_sem_t sem) { - if(!sem) - THROW0(arg_error,EINVAL,"Cannot destroy the NULL sempahore"); + if(!sem) + THROW0(arg_error,EINVAL,"Cannot destroy the NULL sempahore"); #ifdef HAVE_SEM_INIT - if(sem_destroy(sem->ps)) < 0) - THROW1(system_error,errno,"sem_destroy() failed: %s", - strerror(errno)); + if(sem_destroy(sem->ps)) < 0) + THROW1(system_error,errno,"sem_destroy() failed: %s", + strerror(errno)); #else - if(sem_close(sem->ps) < 0) - THROW1(system_error,errno,"sem_close() failed: %s", - strerror(errno)); - xbt_free(sem->name); + if(sem_close(sem->ps) < 0) + THROW1(system_error,errno,"sem_close() failed: %s", + strerror(errno)); + xbt_free(sem->name); #endif - xbt_free(sem); + xbt_free(sem); } void xbt_os_sem_get_value(xbt_os_sem_t sem, int* svalue) { - if(!sem) - THROW0(arg_error,EINVAL,"Cannot get the value of the NULL semaphore"); + if(!sem) + THROW0(arg_error,EINVAL,"Cannot get the value of the NULL semaphore"); - if(sem_getvalue(&(sem->s),svalue) < 0) - THROW1(system_error,errno,"sem_getvalue() failed: %s", - strerror(errno)); + if(sem_getvalue(&(sem->s),svalue) < 0) + THROW1(system_error,errno,"sem_getvalue() failed: %s", + strerror(errno)); } /* ********************************* WINDOWS IMPLEMENTATION ************************************ */ @@ -557,329 +557,329 @@ typedef struct xbt_os_thread_ { static unsigned long xbt_self_thread_key; void xbt_os_thread_mod_init(void) { - xbt_self_thread_key = TlsAlloc(); + xbt_self_thread_key = TlsAlloc(); } void xbt_os_thread_mod_exit(void) { - if (!TlsFree(xbt_self_thread_key)) - THROW0(system_error,(int)GetLastError(),"TlsFree() failed to cleanup the thread submodule"); + if (!TlsFree(xbt_self_thread_key)) + THROW0(system_error,(int)GetLastError(),"TlsFree() failed to cleanup the thread submodule"); } static DWORD WINAPI wrapper_start_routine(void *s) { xbt_os_thread_t t = (xbt_os_thread_t)s; DWORD* rv; - if(!TlsSetValue(xbt_self_thread_key,t)) - THROW0(system_error,(int)GetLastError(),"TlsSetValue of data describing the created thread failed"); + if(!TlsSetValue(xbt_self_thread_key,t)) + THROW0(system_error,(int)GetLastError(),"TlsSetValue of data describing the created thread failed"); + + rv = (DWORD*)((t->start_routine)(t->param)); - rv = (DWORD*)((t->start_routine)(t->param)); + return rv ? *rv : 0; - return rv ? *rv : 0; - } xbt_os_thread_t xbt_os_thread_create(const char *name,pvoid_f_pvoid_t start_routine, - void* param) { + void* param) { - xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t,1); + xbt_os_thread_t t = xbt_new(s_xbt_os_thread_t,1); - t->name = xbt_strdup(name); - t->start_routine = start_routine ; - t->param = param; + t->name = xbt_strdup(name); + t->start_routine = start_routine ; + t->param = param; - t->handle = CreateThread(NULL,XBT_DEFAULT_THREAD_STACK_SIZE, - (LPTHREAD_START_ROUTINE)wrapper_start_routine, - t,STACK_SIZE_PARAM_IS_A_RESERVATION,&(t->id)); + t->handle = CreateThread(NULL,XBT_DEFAULT_THREAD_STACK_SIZE, + (LPTHREAD_START_ROUTINE)wrapper_start_routine, + t,STACK_SIZE_PARAM_IS_A_RESERVATION,&(t->id)); - if(!t->handle) { - xbt_free(t); - THROW0(system_error,(int)GetLastError(),"CreateThread failed"); - } + if(!t->handle) { + xbt_free(t); + THROW0(system_error,(int)GetLastError(),"CreateThread failed"); + } - return t; + return t; } const char* xbt_os_thread_name(xbt_os_thread_t t) { - return t->name; + return t->name; } const char* xbt_os_thread_self_name(void) { - xbt_os_thread_t t = xbt_os_thread_self(); - return t?t->name:"main"; + xbt_os_thread_t t = xbt_os_thread_self(); + return t?t->name:"main"; } void xbt_os_thread_join(xbt_os_thread_t thread,void ** thread_return) { - if(WAIT_OBJECT_0 != WaitForSingleObject(thread->handle,INFINITE)) - THROW0(system_error,(int)GetLastError(), "WaitForSingleObject failed"); + if(WAIT_OBJECT_0 != WaitForSingleObject(thread->handle,INFINITE)) + THROW0(system_error,(int)GetLastError(), "WaitForSingleObject failed"); - if(thread_return){ + if(thread_return){ - if(!GetExitCodeThread(thread->handle,(DWORD*)(*thread_return))) - THROW0(system_error,(int)GetLastError(), "GetExitCodeThread failed"); - } + if(!GetExitCodeThread(thread->handle,(DWORD*)(*thread_return))) + THROW0(system_error,(int)GetLastError(), "GetExitCodeThread failed"); + } - CloseHandle(thread->handle); - - if(thread->name) - free(thread->name); - - free(thread); + CloseHandle(thread->handle); + + if(thread->name) + free(thread->name); + + free(thread); } void xbt_os_thread_exit(int *retval) { - if(retval) - ExitThread(*retval); - else - ExitThread(0); + if(retval) + ExitThread(*retval); + else + ExitThread(0); } xbt_os_thread_t xbt_os_thread_self(void) { - return TlsGetValue(xbt_self_thread_key); + return TlsGetValue(xbt_self_thread_key); } void *xbt_os_thread_getparam(void) { - xbt_os_thread_t t = xbt_os_thread_self(); - return t->param; + xbt_os_thread_t t = xbt_os_thread_self(); + return t->param; } void xbt_os_thread_yield(void) { - Sleep(0); + Sleep(0); } void xbt_os_thread_cancel(xbt_os_thread_t t) { if(!TerminateThread(t->handle,0)) - THROW0(system_error,(int)GetLastError(), "TerminateThread failed"); + THROW0(system_error,(int)GetLastError(), "TerminateThread failed"); } /****** mutex related functions ******/ typedef struct xbt_os_mutex_ { /* KEEP IT IN SYNC WITH xbt_thread.c */ - CRITICAL_SECTION lock; + CRITICAL_SECTION lock; } s_xbt_os_mutex_t; xbt_os_mutex_t xbt_os_mutex_init(void) { - xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t,1); + xbt_os_mutex_t res = xbt_new(s_xbt_os_mutex_t,1); - /* initialize the critical section object */ - InitializeCriticalSection(&(res->lock)); + /* initialize the critical section object */ + InitializeCriticalSection(&(res->lock)); - return res; + return res; } void xbt_os_mutex_acquire(xbt_os_mutex_t mutex) { - EnterCriticalSection(& mutex->lock); + EnterCriticalSection(& mutex->lock); } void xbt_os_mutex_timedacquire(xbt_os_mutex_t mutex, double delay) { - THROW_UNIMPLEMENTED; + THROW_UNIMPLEMENTED; } void xbt_os_mutex_release(xbt_os_mutex_t mutex) { - LeaveCriticalSection (&mutex->lock); + LeaveCriticalSection (&mutex->lock); } void xbt_os_mutex_destroy(xbt_os_mutex_t mutex) { - if (!mutex) return; + if (!mutex) return; - DeleteCriticalSection(& mutex->lock); - free(mutex); + DeleteCriticalSection(& mutex->lock); + free(mutex); } /***** condition related functions *****/ - enum { /* KEEP IT IN SYNC WITH xbt_thread.c */ - SIGNAL = 0, - BROADCAST = 1, - MAX_EVENTS = 2 - }; +enum { /* KEEP IT IN SYNC WITH xbt_thread.c */ + SIGNAL = 0, + BROADCAST = 1, + MAX_EVENTS = 2 +}; typedef struct xbt_os_cond_ { /* KEEP IT IN SYNC WITH xbt_thread.c */ - HANDLE events[MAX_EVENTS]; + HANDLE events[MAX_EVENTS]; - unsigned int waiters_count; /* the number of waiters */ - CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */ + unsigned int waiters_count; /* the number of waiters */ + CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */ } s_xbt_os_cond_t; xbt_os_cond_t xbt_os_cond_init(void) { - xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t,1); + xbt_os_cond_t res = xbt_new0(s_xbt_os_cond_t,1); - memset(& res->waiters_count_lock,0,sizeof(CRITICAL_SECTION)); + memset(& res->waiters_count_lock,0,sizeof(CRITICAL_SECTION)); - /* initialize the critical section object */ - InitializeCriticalSection(& res->waiters_count_lock); + /* initialize the critical section object */ + InitializeCriticalSection(& res->waiters_count_lock); - res->waiters_count = 0; + res->waiters_count = 0; - /* Create an auto-reset event */ - res->events[SIGNAL] = CreateEvent (NULL, FALSE, FALSE, NULL); + /* Create an auto-reset event */ + res->events[SIGNAL] = CreateEvent (NULL, FALSE, FALSE, NULL); - if(!res->events[SIGNAL]){ - DeleteCriticalSection(& res->waiters_count_lock); - free(res); - THROW0(system_error,0,"CreateEvent failed for the signals"); - } + if(!res->events[SIGNAL]){ + DeleteCriticalSection(& res->waiters_count_lock); + free(res); + THROW0(system_error,0,"CreateEvent failed for the signals"); + } - /* Create a manual-reset event. */ - res->events[BROADCAST] = CreateEvent (NULL, TRUE, FALSE,NULL); + /* Create a manual-reset event. */ + res->events[BROADCAST] = CreateEvent (NULL, TRUE, FALSE,NULL); - if(!res->events[BROADCAST]){ + if(!res->events[BROADCAST]){ - DeleteCriticalSection(& res->waiters_count_lock); - CloseHandle(res->events[SIGNAL]); - free(res); - THROW0(system_error,0,"CreateEvent failed for the broadcasts"); - } + DeleteCriticalSection(& res->waiters_count_lock); + CloseHandle(res->events[SIGNAL]); + free(res); + THROW0(system_error,0,"CreateEvent failed for the broadcasts"); + } - return res; + return res; } void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex) { - unsigned long wait_result; - int is_last_waiter; + unsigned long wait_result; + int is_last_waiter; - /* lock the threads counter and increment it */ - EnterCriticalSection (& cond->waiters_count_lock); - cond->waiters_count++; - LeaveCriticalSection (& cond->waiters_count_lock); + /* lock the threads counter and increment it */ + EnterCriticalSection (& cond->waiters_count_lock); + cond->waiters_count++; + LeaveCriticalSection (& cond->waiters_count_lock); - /* unlock the mutex associate with the condition */ - LeaveCriticalSection (& mutex->lock); + /* unlock the mutex associate with the condition */ + LeaveCriticalSection (& mutex->lock); - /* wait for a signal (broadcast or no) */ - wait_result = WaitForMultipleObjects (2, cond->events, FALSE, INFINITE); + /* wait for a signal (broadcast or no) */ + wait_result = WaitForMultipleObjects (2, cond->events, FALSE, INFINITE); - if(wait_result == WAIT_FAILED) - THROW0(system_error,0,"WaitForMultipleObjects failed, so we cannot wait on the condition"); + if(wait_result == WAIT_FAILED) + THROW0(system_error,0,"WaitForMultipleObjects failed, so we cannot wait on the condition"); - /* we have a signal lock the condition */ - EnterCriticalSection (& cond->waiters_count_lock); - cond->waiters_count--; + /* we have a signal lock the condition */ + EnterCriticalSection (& cond->waiters_count_lock); + cond->waiters_count--; - /* it's the last waiter or it's a broadcast ? */ - is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1) && (cond->waiters_count == 0)); + /* it's the last waiter or it's a broadcast ? */ + is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1) && (cond->waiters_count == 0)); - LeaveCriticalSection (& cond->waiters_count_lock); + LeaveCriticalSection (& cond->waiters_count_lock); - /* yes it's the last waiter or it's a broadcast - * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function - * by the system. - */ - if (is_last_waiter) - if(!ResetEvent (cond->events[BROADCAST])) - THROW0(system_error,0,"ResetEvent failed"); + /* yes it's the last waiter or it's a broadcast + * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function + * by the system. + */ + if (is_last_waiter) + if(!ResetEvent (cond->events[BROADCAST])) + THROW0(system_error,0,"ResetEvent failed"); - /* relock the mutex associated with the condition in accordance with the posix thread specification */ - EnterCriticalSection (& mutex->lock); + /* relock the mutex associated with the condition in accordance with the posix thread specification */ + EnterCriticalSection (& mutex->lock); } void xbt_os_cond_timedwait(xbt_os_cond_t cond, xbt_os_mutex_t mutex, double delay) { - unsigned long wait_result = WAIT_TIMEOUT; - int is_last_waiter; - unsigned long end = (unsigned long)(delay * 1000); + unsigned long wait_result = WAIT_TIMEOUT; + int is_last_waiter; + unsigned long end = (unsigned long)(delay * 1000); - if (delay < 0) { - xbt_os_cond_wait(cond,mutex); - } else { - DEBUG3("xbt_cond_timedwait(%p,%p,%lu)",&(cond->events),&(mutex->lock),end); + if (delay < 0) { + xbt_os_cond_wait(cond,mutex); + } else { + DEBUG3("xbt_cond_timedwait(%p,%p,%lu)",&(cond->events),&(mutex->lock),end); - /* lock the threads counter and increment it */ - EnterCriticalSection (& cond->waiters_count_lock); - cond->waiters_count++; - LeaveCriticalSection (& cond->waiters_count_lock); + /* lock the threads counter and increment it */ + EnterCriticalSection (& cond->waiters_count_lock); + cond->waiters_count++; + LeaveCriticalSection (& cond->waiters_count_lock); - /* unlock the mutex associate with the condition */ - LeaveCriticalSection (& mutex->lock); - /* wait for a signal (broadcast or no) */ + /* unlock the mutex associate with the condition */ + LeaveCriticalSection (& mutex->lock); + /* wait for a signal (broadcast or no) */ - wait_result = WaitForMultipleObjects (2, cond->events, FALSE, end); + wait_result = WaitForMultipleObjects (2, cond->events, FALSE, end); - switch(wait_result) { - case WAIT_TIMEOUT: - THROW3(timeout_error,GetLastError(),"condition %p (mutex %p) wasn't signaled before timeout (%f)",cond,mutex, delay); - case WAIT_FAILED: - THROW0(system_error,GetLastError(),"WaitForMultipleObjects failed, so we cannot wait on the condition"); - } + switch(wait_result) { + case WAIT_TIMEOUT: + THROW3(timeout_error,GetLastError(),"condition %p (mutex %p) wasn't signaled before timeout (%f)",cond,mutex, delay); + case WAIT_FAILED: + THROW0(system_error,GetLastError(),"WaitForMultipleObjects failed, so we cannot wait on the condition"); + } - /* we have a signal lock the condition */ - EnterCriticalSection (& cond->waiters_count_lock); - cond->waiters_count--; + /* we have a signal lock the condition */ + EnterCriticalSection (& cond->waiters_count_lock); + cond->waiters_count--; - /* it's the last waiter or it's a broadcast ? */ - is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1) && (cond->waiters_count == 0)); + /* it's the last waiter or it's a broadcast ? */ + is_last_waiter = ((wait_result == WAIT_OBJECT_0 + BROADCAST - 1) && (cond->waiters_count == 0)); - LeaveCriticalSection (& cond->waiters_count_lock); + LeaveCriticalSection (& cond->waiters_count_lock); - /* yes it's the last waiter or it's a broadcast - * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function - * by the system. - */ - if (is_last_waiter) + /* yes it's the last waiter or it's a broadcast + * only reset the manual event (the automatic event is reset in the WaitForMultipleObjects() function + * by the system. + */ + if (is_last_waiter) if(!ResetEvent (cond->events[BROADCAST])) - THROW0(system_error,0,"ResetEvent failed"); + THROW0(system_error,0,"ResetEvent failed"); - /* relock the mutex associated with the condition in accordance with the posix thread specification */ - EnterCriticalSection (& mutex->lock); - } - /*THROW_UNIMPLEMENTED;*/ + /* relock the mutex associated with the condition in accordance with the posix thread specification */ + EnterCriticalSection (& mutex->lock); + } + /*THROW_UNIMPLEMENTED;*/ } void xbt_os_cond_signal(xbt_os_cond_t cond) { - int have_waiters; + int have_waiters; - EnterCriticalSection (& cond->waiters_count_lock); - have_waiters = cond->waiters_count > 0; - LeaveCriticalSection (& cond->waiters_count_lock); + EnterCriticalSection (& cond->waiters_count_lock); + have_waiters = cond->waiters_count > 0; + LeaveCriticalSection (& cond->waiters_count_lock); - if (have_waiters) - if(!SetEvent(cond->events[SIGNAL])) - THROW0(system_error,0,"SetEvent failed"); + if (have_waiters) + if(!SetEvent(cond->events[SIGNAL])) + THROW0(system_error,0,"SetEvent failed"); - xbt_os_thread_yield(); + xbt_os_thread_yield(); } void xbt_os_cond_broadcast(xbt_os_cond_t cond){ - int have_waiters; + int have_waiters; - EnterCriticalSection (& cond->waiters_count_lock); - have_waiters = cond->waiters_count > 0; - LeaveCriticalSection (& cond->waiters_count_lock); + EnterCriticalSection (& cond->waiters_count_lock); + have_waiters = cond->waiters_count > 0; + LeaveCriticalSection (& cond->waiters_count_lock); - if (have_waiters) - SetEvent(cond->events[BROADCAST]); + if (have_waiters) + SetEvent(cond->events[BROADCAST]); } void xbt_os_cond_destroy(xbt_os_cond_t cond){ - int error = 0; + int error = 0; - if (!cond) return; + if (!cond) return; - if(!CloseHandle(cond->events[SIGNAL])) - error = 1; + if(!CloseHandle(cond->events[SIGNAL])) + error = 1; - if(!CloseHandle(cond->events[BROADCAST])) - error = 1; + if(!CloseHandle(cond->events[BROADCAST])) + error = 1; - DeleteCriticalSection(& cond->waiters_count_lock); + DeleteCriticalSection(& cond->waiters_count_lock); - xbt_free(cond); + xbt_free(cond); - if (error) - THROW0(system_error,0,"Error while destroying the condition"); + if (error) + THROW0(system_error,0,"Error while destroying the condition"); } typedef struct xbt_os_sem_ { - HANDLE h; - unsigned int value; - CRITICAL_SECTION value_lock; /* protect access to value of the semaphore */ + HANDLE h; + unsigned int value; + CRITICAL_SECTION value_lock; /* protect access to value of the semaphore */ }s_xbt_os_sem_t ; #ifndef INT_MAX @@ -889,118 +889,118 @@ typedef struct xbt_os_sem_ { xbt_os_sem_t xbt_os_sem_init(unsigned int value) { - xbt_os_sem_t res; + xbt_os_sem_t res; - if(value > INT_MAX) - THROW1(arg_error,value,"Semaphore initial value too big: %ud cannot be stored as a signed int",value); + if(value > INT_MAX) + THROW1(arg_error,value,"Semaphore initial value too big: %ud cannot be stored as a signed int",value); - res = (xbt_os_sem_t)xbt_new0(s_xbt_os_sem_t,1); + res = (xbt_os_sem_t)xbt_new0(s_xbt_os_sem_t,1); - if(!(res->h = CreateSemaphore(NULL,value,(long)INT_MAX,NULL))) { - THROW1(system_error,GetLastError(),"CreateSemaphore() failed: %s", - strerror(GetLastError())); - return NULL; - } + if(!(res->h = CreateSemaphore(NULL,value,(long)INT_MAX,NULL))) { + THROW1(system_error,GetLastError(),"CreateSemaphore() failed: %s", + strerror(GetLastError())); + return NULL; + } - res->value = value; + res->value = value; - InitializeCriticalSection(&(res->value_lock)); + InitializeCriticalSection(&(res->value_lock)); - return res; + return res; } void xbt_os_sem_acquire(xbt_os_sem_t sem) { - if(!sem) - THROW0(arg_error,EINVAL,"Cannot acquire the NULL semaphore"); + if(!sem) + THROW0(arg_error,EINVAL,"Cannot acquire the NULL semaphore"); - /* wait failure */ - if(WAIT_OBJECT_0 != WaitForSingleObject(sem->h,INFINITE)) - THROW1(system_error,GetLastError(),"WaitForSingleObject() failed: %s", - strerror(GetLastError())); - EnterCriticalSection(&(sem->value_lock)); - sem->value--; - LeaveCriticalSection(&(sem->value_lock)); + /* wait failure */ + if(WAIT_OBJECT_0 != WaitForSingleObject(sem->h,INFINITE)) + THROW1(system_error,GetLastError(),"WaitForSingleObject() failed: %s", + strerror(GetLastError())); + EnterCriticalSection(&(sem->value_lock)); + sem->value--; + LeaveCriticalSection(&(sem->value_lock)); } void xbt_os_sem_timedacquire(xbt_os_sem_t sem, double timeout) { - long seconds; - long milliseconds; - double end = timeout + xbt_os_time(); - - if(!sem) - THROW0(arg_error,EINVAL,"Cannot acquire the NULL semaphore"); - - if (timeout < 0) - { - xbt_os_sem_acquire(sem); - } - else /* timeout can be zero <-> try acquire ) */ - { - - seconds = (long) floor(end); - milliseconds = (long)( ( end - seconds) * 1000); - milliseconds += (seconds * 1000); - - switch(WaitForSingleObject(sem->h,milliseconds)) - { - case WAIT_OBJECT_0: - EnterCriticalSection(&(sem->value_lock)); - sem->value--; - LeaveCriticalSection(&(sem->value_lock)); - return; - - case WAIT_TIMEOUT: - THROW2(timeout_error,GetLastError(),"semaphore %p wasn't signaled before timeout (%f)",sem,timeout); - return; - - default: - THROW3(system_error,GetLastError(),"WaitForSingleObject(%p,%f) failed: %s",sem,timeout, strerror(GetLastError())); - } - } + long seconds; + long milliseconds; + double end = timeout + xbt_os_time(); + + if(!sem) + THROW0(arg_error,EINVAL,"Cannot acquire the NULL semaphore"); + + if (timeout < 0) + { + xbt_os_sem_acquire(sem); + } + else /* timeout can be zero <-> try acquire ) */ + { + + seconds = (long) floor(end); + milliseconds = (long)( ( end - seconds) * 1000); + milliseconds += (seconds * 1000); + + switch(WaitForSingleObject(sem->h,milliseconds)) + { + case WAIT_OBJECT_0: + EnterCriticalSection(&(sem->value_lock)); + sem->value--; + LeaveCriticalSection(&(sem->value_lock)); + return; + + case WAIT_TIMEOUT: + THROW2(timeout_error,GetLastError(),"semaphore %p wasn't signaled before timeout (%f)",sem,timeout); + return; + + default: + THROW3(system_error,GetLastError(),"WaitForSingleObject(%p,%f) failed: %s",sem,timeout, strerror(GetLastError())); + } + } } void xbt_os_sem_release(xbt_os_sem_t sem) { - if(!sem) - THROW0(arg_error,EINVAL,"Cannot release the NULL semaphore"); + if(!sem) + THROW0(arg_error,EINVAL,"Cannot release the NULL semaphore"); - if(!ReleaseSemaphore(sem->h,1, NULL)) - THROW1(system_error,GetLastError(),"ReleaseSemaphore() failed: %s", - strerror(GetLastError())); - EnterCriticalSection (&(sem->value_lock)); - sem->value++; - LeaveCriticalSection(&(sem->value_lock)); + if(!ReleaseSemaphore(sem->h,1, NULL)) + THROW1(system_error,GetLastError(),"ReleaseSemaphore() failed: %s", + strerror(GetLastError())); + EnterCriticalSection (&(sem->value_lock)); + sem->value++; + LeaveCriticalSection(&(sem->value_lock)); } void xbt_os_sem_destroy(xbt_os_sem_t sem) { - if(!sem) - THROW0(arg_error,EINVAL,"Cannot destroy the NULL semaphore"); + if(!sem) + THROW0(arg_error,EINVAL,"Cannot destroy the NULL semaphore"); - if(!CloseHandle(sem->h)) - THROW1(system_error,GetLastError(),"CloseHandle() failed: %s", - strerror(GetLastError())); + if(!CloseHandle(sem->h)) + THROW1(system_error,GetLastError(),"CloseHandle() failed: %s", + strerror(GetLastError())); - DeleteCriticalSection(&(sem->value_lock)); + DeleteCriticalSection(&(sem->value_lock)); - xbt_free(sem); + xbt_free(sem); } void xbt_os_sem_get_value(xbt_os_sem_t sem, int* svalue) { - if(!sem) - THROW0(arg_error,EINVAL,"Cannot get the value of the NULL semaphore"); + if(!sem) + THROW0(arg_error,EINVAL,"Cannot get the value of the NULL semaphore"); - EnterCriticalSection(&(sem->value_lock)); - *svalue = sem->value; - LeaveCriticalSection(&(sem->value_lock)); + EnterCriticalSection(&(sem->value_lock)); + *svalue = sem->value; + LeaveCriticalSection(&(sem->value_lock)); } #endif diff --git a/src/xbt/xbt_os_time.c b/src/xbt/xbt_os_time.c index 6e63660a63..2976a7633e 100644 --- a/src/xbt/xbt_os_time.c +++ b/src/xbt/xbt_os_time.c @@ -20,37 +20,37 @@ double xbt_os_time(void) { #ifdef HAVE_GETTIMEOFDAY - struct timeval tv; - gettimeofday(&tv, NULL); + struct timeval tv; + gettimeofday(&tv, NULL); #elif defined(WIN32) - struct timeval tv; + struct timeval tv; # if defined(WIN32_WCE) || (_WIN32_WINNT < 0x0400) - struct _timeb tm; + struct _timeb tm; - _ftime (&tm); + _ftime (&tm); - tv.tv_sec = tm.time; - tv.tv_usec = tm.millitm * 1000; + tv.tv_sec = tm.time; + tv.tv_usec = tm.millitm * 1000; # else - FILETIME ft; - unsigned __int64 tm; + FILETIME ft; + unsigned __int64 tm; - GetSystemTimeAsFileTime (&ft); - tm = (unsigned __int64)ft.dwHighDateTime << 32; - tm |= ft.dwLowDateTime; - tm /=10; - tm -= 11644473600000000ULL; + GetSystemTimeAsFileTime (&ft); + tm = (unsigned __int64)ft.dwHighDateTime << 32; + tm |= ft.dwLowDateTime; + tm /=10; + tm -= 11644473600000000ULL; - tv.tv_sec = (long) (tm / 1000000L); - tv.tv_usec = (long) (tm % 1000000L); + tv.tv_sec = (long) (tm / 1000000L); + tv.tv_usec = (long) (tm % 1000000L); # endif /* windows version checker */ #else /* not windows, no gettimeofday => poor resolution */ - return (double)(time(NULL)); + return (double)(time(NULL)); #endif /* HAVE_GETTIMEOFDAY? */ - return (double)(tv.tv_sec + tv.tv_usec / 1000000.0); + return (double)(tv.tv_sec + tv.tv_usec / 1000000.0); } void xbt_os_sleep(double sec) { @@ -59,21 +59,21 @@ void xbt_os_sleep(double sec) { (void)usleep( (sec - floor(sec)) * 1000000); #elif WIN32 - Sleep((floor(sec) * 1000) +((sec - floor(sec)) * 1000)); - + Sleep((floor(sec) * 1000) +((sec - floor(sec)) * 1000)); + #else /* don't have usleep. Use select to sleep less than one second */ struct timeval timeout; - + timeout.tv_sec = (unsigned long)(sec); timeout.tv_usec = (sec - floor(sec)) * 1000000; - + select(0, NULL, NULL, NULL, &timeout); #endif } -/* TSC (tick-level) timers are said to be unreliable on SMP hosts and thus - disabled in SDL source code */ +/* TSC (tick-level) timers are said to be unreliable on SMP hosts and thus + disabled in SDL source code */ /* \defgroup XBT_sysdep All system dependency @@ -84,38 +84,38 @@ void xbt_os_sleep(double sec) { struct s_xbt_os_timer { #ifdef HAVE_GETTIMEOFDAY - struct timeval start,stop; + struct timeval start,stop; #else - unsigned long int start,stop; + unsigned long int start,stop; #endif }; xbt_os_timer_t xbt_os_timer_new(void) { - return xbt_new0(struct s_xbt_os_timer,1); + return xbt_new0(struct s_xbt_os_timer,1); } void xbt_os_timer_free(xbt_os_timer_t timer) { - free (timer); + free (timer); } void xbt_os_timer_start(xbt_os_timer_t timer) { #ifdef HAVE_GETTIMEOFDAY gettimeofday(&(timer->start), NULL); -#else +#else timer->start = (unsigned long int)(time(NULL)); #endif } void xbt_os_timer_stop(xbt_os_timer_t timer) { #ifdef HAVE_GETTIMEOFDAY gettimeofday(&(timer->stop), NULL); -#else +#else timer->stop = (unsigned long int)(time(NULL)); #endif } double xbt_os_timer_elapsed(xbt_os_timer_t timer) { #ifdef HAVE_GETTIMEOFDAY - return ((double)timer->stop.tv_sec) - ((double)timer->start.tv_sec) + - ((((double)timer->stop.tv_usec) - ((double)timer->start.tv_usec)) / 1000000.0); -#else - return (double)timer->stop - (double)timer->start; + return ((double)timer->stop.tv_sec) - ((double)timer->start.tv_sec) + + ((((double)timer->stop.tv_usec) - ((double)timer->start.tv_usec)) / 1000000.0); +#else + return (double)timer->stop - (double)timer->start; #endif } diff --git a/src/xbt/xbt_peer.c b/src/xbt/xbt_peer.c index 9e7c3e866f..1d47f29640 100644 --- a/src/xbt/xbt_peer.c +++ b/src/xbt/xbt_peer.c @@ -15,40 +15,40 @@ XBT_LOG_NEW_DEFAULT_SUBCATEGORY(peer,xbt,"peer management"); /** \brief constructor */ xbt_peer_t xbt_peer_new(const char *name, int port) { - xbt_peer_t res=xbt_new(s_xbt_peer_t, 1); - res->name = xbt_strdup(name); - res->port = port; - return res; + xbt_peer_t res=xbt_new(s_xbt_peer_t, 1); + res->name = xbt_strdup(name); + res->port = port; + return res; } xbt_peer_t xbt_peer_copy(xbt_peer_t h) { - return xbt_peer_new(h->name,h->port); + return xbt_peer_new(h->name,h->port); } /** \brief constructor. Argument should be of form '(peername):(port)'. */ xbt_peer_t xbt_peer_from_string(const char *peerport) { - xbt_peer_t res=xbt_new(s_xbt_peer_t, 1); - char *name=xbt_strdup(peerport); - char *port_str=strchr(name,':'); - xbt_assert1(port_str,"argument of xbt_peer_from_string should be of form :, it's '%s'", peerport); - *port_str='\0'; - port_str++; - - res->name = xbt_strdup(name); /* it will be shorter now that we cut the port */ - res->port = atoi(port_str); - free(name); - return res; + xbt_peer_t res=xbt_new(s_xbt_peer_t, 1); + char *name=xbt_strdup(peerport); + char *port_str=strchr(name,':'); + xbt_assert1(port_str,"argument of xbt_peer_from_string should be of form :, it's '%s'", peerport); + *port_str='\0'; + port_str++; + + res->name = xbt_strdup(name); /* it will be shorter now that we cut the port */ + res->port = atoi(port_str); + free(name); + return res; } /** \brief destructor */ void xbt_peer_free(xbt_peer_t peer) { - if (peer) { - if (peer->name) free(peer->name); - free(peer); - } + if (peer) { + if (peer->name) free(peer->name); + free(peer); + } } /** \brief Freeing function for dynars of xbt_peer_t */ void xbt_peer_free_voidp(void *d) { - xbt_peer_free( (xbt_peer_t) *(void**)d ); + xbt_peer_free( (xbt_peer_t) *(void**)d ); } diff --git a/src/xbt/xbt_queue.c b/src/xbt/xbt_queue.c index 39643f41c3..976054fb8f 100644 --- a/src/xbt/xbt_queue.c +++ b/src/xbt/xbt_queue.c @@ -19,27 +19,27 @@ XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_queue,xbt,"Message exchanging queue"); typedef struct s_xbt_queue_ { - int capacity; - xbt_dynar_t data; - xbt_mutex_t mutex; - xbt_cond_t not_full, not_empty; + int capacity; + xbt_dynar_t data; + xbt_mutex_t mutex; + xbt_cond_t not_full, not_empty; } s_xbt_queue_t; /** @brief Create a new message exchange queue. - * + * * @param capacity the capacity of the queue. If non-nul, any attempt to push an item which would let the size of the queue over this number will be blocking until someone else pop some data * @param elm_size size of each element stored in it (see #xbt_dynar_new) */ xbt_queue_t xbt_queue_new(int capacity,unsigned long elm_size) { - xbt_queue_t res = xbt_new0(s_xbt_queue_t,1); - xbt_assert0(capacity>=0,"Capacity cannot be negative"); - - res->capacity = capacity; - res->data = xbt_dynar_new(elm_size,NULL); - res->mutex = xbt_mutex_init(); - res->not_full = xbt_cond_init(); - res->not_empty = xbt_cond_init(); - return res; + xbt_queue_t res = xbt_new0(s_xbt_queue_t,1); + xbt_assert0(capacity>=0,"Capacity cannot be negative"); + + res->capacity = capacity; + res->data = xbt_dynar_new(elm_size,NULL); + res->mutex = xbt_mutex_init(); + res->not_full = xbt_cond_init(); + res->not_empty = xbt_cond_init(); + return res; } /** @brief Destroy a message exchange queue. * @@ -47,100 +47,100 @@ xbt_queue_t xbt_queue_new(int capacity,unsigned long elm_size) { */ void xbt_queue_free(xbt_queue_t *queue) { - xbt_dynar_free(&( (*queue)->data )); - xbt_mutex_destroy( (*queue)->mutex ); - xbt_cond_destroy( (*queue)->not_full ); - xbt_cond_destroy( (*queue)->not_empty ); - free((*queue)); - *queue = NULL; + xbt_dynar_free(&( (*queue)->data )); + xbt_mutex_destroy( (*queue)->mutex ); + xbt_cond_destroy( (*queue)->not_full ); + xbt_cond_destroy( (*queue)->not_empty ); + free((*queue)); + *queue = NULL; } /** @brief Get the queue size */ unsigned long xbt_queue_length(const xbt_queue_t queue) { - unsigned long res; - xbt_mutex_acquire(queue->mutex); - res=xbt_dynar_length(queue->data); - xbt_mutex_release(queue->mutex); - return res; + unsigned long res; + xbt_mutex_acquire(queue->mutex); + res=xbt_dynar_length(queue->data); + xbt_mutex_release(queue->mutex); + return res; } /** @brief Push something to the message exchange queue. - * + * * This is blocking if the declared capacity is non-nul, and if this amount is reached. - * + * * @see #xbt_dynar_push */ void xbt_queue_push(xbt_queue_t queue, const void *src) { - xbt_mutex_acquire(queue->mutex); - while (queue->capacity != 0 && queue->capacity == xbt_dynar_length(queue->data)) { - DEBUG2("Capacity of %p exceded (=%d). Waiting",queue,queue->capacity); - xbt_cond_wait(queue->not_full,queue->mutex); - } - xbt_dynar_push(queue->data,src); - xbt_cond_signal(queue->not_empty); - xbt_mutex_release(queue->mutex); + xbt_mutex_acquire(queue->mutex); + while (queue->capacity != 0 && queue->capacity == xbt_dynar_length(queue->data)) { + DEBUG2("Capacity of %p exceded (=%d). Waiting",queue,queue->capacity); + xbt_cond_wait(queue->not_full,queue->mutex); + } + xbt_dynar_push(queue->data,src); + xbt_cond_signal(queue->not_empty); + xbt_mutex_release(queue->mutex); } - + /** @brief Pop something from the message exchange queue. - * + * * This is blocking if the queue is empty. - * + * * @see #xbt_dynar_pop - * + * */ void xbt_queue_pop(xbt_queue_t queue, void* const dst) { - xbt_mutex_acquire(queue->mutex); - while (xbt_dynar_length(queue->data) == 0) { - DEBUG1("Queue %p empty. Waiting",queue); - xbt_cond_wait(queue->not_empty,queue->mutex); - } - xbt_dynar_pop(queue->data,dst); - xbt_cond_signal(queue->not_full); - xbt_mutex_release(queue->mutex); + xbt_mutex_acquire(queue->mutex); + while (xbt_dynar_length(queue->data) == 0) { + DEBUG1("Queue %p empty. Waiting",queue); + xbt_cond_wait(queue->not_empty,queue->mutex); + } + xbt_dynar_pop(queue->data,dst); + xbt_cond_signal(queue->not_full); + xbt_mutex_release(queue->mutex); } /** @brief Unshift something to the message exchange queue. - * + * * This is blocking if the declared capacity is non-nul, and if this amount is reached. - * + * * @see #xbt_dynar_unshift */ void xbt_queue_unshift(xbt_queue_t queue, const void *src) { - xbt_mutex_acquire(queue->mutex); - while (queue->capacity != 0 && queue->capacity == xbt_dynar_length(queue->data)) { - DEBUG2("Capacity of %p exceded (=%d). Waiting",queue,queue->capacity); - xbt_cond_wait(queue->not_full,queue->mutex); - } - xbt_dynar_unshift(queue->data,src); - xbt_cond_signal(queue->not_empty); - xbt_mutex_release(queue->mutex); + xbt_mutex_acquire(queue->mutex); + while (queue->capacity != 0 && queue->capacity == xbt_dynar_length(queue->data)) { + DEBUG2("Capacity of %p exceded (=%d). Waiting",queue,queue->capacity); + xbt_cond_wait(queue->not_full,queue->mutex); + } + xbt_dynar_unshift(queue->data,src); + xbt_cond_signal(queue->not_empty); + xbt_mutex_release(queue->mutex); } - + /** @brief Shift something from the message exchange queue. - * + * * This is blocking if the queue is empty. - * + * * @see #xbt_dynar_shift - * + * */ void xbt_queue_shift(xbt_queue_t queue, void* const dst) { - xbt_mutex_acquire(queue->mutex); - while (xbt_dynar_length(queue->data) == 0) { - DEBUG1("Queue %p empty. Waiting",queue); - xbt_cond_wait(queue->not_empty,queue->mutex); - } - xbt_dynar_shift(queue->data,dst); - xbt_cond_signal(queue->not_full); - xbt_mutex_release(queue->mutex); + xbt_mutex_acquire(queue->mutex); + while (xbt_dynar_length(queue->data) == 0) { + DEBUG1("Queue %p empty. Waiting",queue); + xbt_cond_wait(queue->not_empty,queue->mutex); + } + xbt_dynar_shift(queue->data,dst); + xbt_cond_signal(queue->not_full); + xbt_mutex_release(queue->mutex); } /** @brief Push something to the message exchange queue, with a timeout. - * + * * @see #xbt_queue_push */ void xbt_queue_push_timed(xbt_queue_t queue, const void *src,double delay) { @@ -150,26 +150,26 @@ void xbt_queue_push_timed(xbt_queue_t queue, const void *src,double delay) { xbt_mutex_acquire(queue->mutex); if (delay == 0) { - if (queue->capacity != 0 && - queue->capacity == xbt_dynar_length(queue->data)) { + if (queue->capacity != 0 && + queue->capacity == xbt_dynar_length(queue->data)) { xbt_mutex_release(queue->mutex); THROW2(timeout_error,0,"Capacity of %p exceded (=%d), and delay = 0", - queue,queue->capacity); + queue,queue->capacity); } } else { - while (queue->capacity != 0 && - queue->capacity == xbt_dynar_length(queue->data) && - (delay<0 || (xbt_time() - begin) <= delay) ) { - + while (queue->capacity != 0 && + queue->capacity == xbt_dynar_length(queue->data) && + (delay<0 || (xbt_time() - begin) <= delay) ) { + DEBUG2("Capacity of %p exceded (=%d). Waiting", - queue,queue->capacity); + queue,queue->capacity); TRY { - xbt_cond_timedwait(queue->not_full,queue->mutex, - delay < 0 ? -1 : delay - (xbt_time()-begin)); + xbt_cond_timedwait(queue->not_full,queue->mutex, + delay < 0 ? -1 : delay - (xbt_time()-begin)); } CATCH(e) { - xbt_mutex_release(queue->mutex); - RETHROW; + xbt_mutex_release(queue->mutex); + RETHROW; } } } @@ -179,11 +179,11 @@ void xbt_queue_push_timed(xbt_queue_t queue, const void *src,double delay) { xbt_mutex_release(queue->mutex); } - + /** @brief Pop something from the message exchange queue, with a timeout. - * + * * @see #xbt_queue_pop - * + * */ void xbt_queue_pop_timed(xbt_queue_t queue, void* const dst,double delay) { double begin = xbt_time(); @@ -197,15 +197,15 @@ void xbt_queue_pop_timed(xbt_queue_t queue, void* const dst,double delay) { THROW0(timeout_error,0,"Delay = 0, and queue is empty"); } } else { - while ( (xbt_dynar_length(queue->data) == 0) && - (delay<0 || (xbt_time() - begin) <= delay) ) { + while ( (xbt_dynar_length(queue->data) == 0) && + (delay<0 || (xbt_time() - begin) <= delay) ) { DEBUG1("Queue %p empty. Waiting",queue); TRY { - xbt_cond_timedwait(queue->not_empty,queue->mutex, - delay<0 ? -1 : delay - (xbt_time()-begin)); + xbt_cond_timedwait(queue->not_empty,queue->mutex, + delay<0 ? -1 : delay - (xbt_time()-begin)); } CATCH(e) { - xbt_mutex_release(queue->mutex); - RETHROW; + xbt_mutex_release(queue->mutex); + RETHROW; } } } @@ -216,7 +216,7 @@ void xbt_queue_pop_timed(xbt_queue_t queue, void* const dst,double delay) { } /** @brief Unshift something to the message exchange queue, with a timeout. - * + * * @see #xbt_queue_unshift */ void xbt_queue_unshift_timed(xbt_queue_t queue, const void *src,double delay) { @@ -226,26 +226,26 @@ void xbt_queue_unshift_timed(xbt_queue_t queue, const void *src,double delay) { xbt_mutex_acquire(queue->mutex); if (delay==0) { - if (queue->capacity != 0 && - queue->capacity == xbt_dynar_length(queue->data)) { + if (queue->capacity != 0 && + queue->capacity == xbt_dynar_length(queue->data)) { xbt_mutex_release(queue->mutex); THROW2(timeout_error,0,"Capacity of %p exceded (=%d), and delay = 0", - queue,queue->capacity); + queue,queue->capacity); } } else { - while (queue->capacity != 0 && - queue->capacity == xbt_dynar_length(queue->data) && - (delay<0 || (xbt_time() - begin) <= delay) ) { - + while (queue->capacity != 0 && + queue->capacity == xbt_dynar_length(queue->data) && + (delay<0 || (xbt_time() - begin) <= delay) ) { + DEBUG2("Capacity of %p exceded (=%d). Waiting", - queue,queue->capacity); + queue,queue->capacity); TRY { - xbt_cond_timedwait(queue->not_full,queue->mutex, - delay < 0 ? -1 : delay - (xbt_time()-begin)); + xbt_cond_timedwait(queue->not_full,queue->mutex, + delay < 0 ? -1 : delay - (xbt_time()-begin)); } CATCH(e) { - xbt_mutex_release(queue->mutex); - RETHROW; + xbt_mutex_release(queue->mutex); + RETHROW; } } } @@ -254,12 +254,12 @@ void xbt_queue_unshift_timed(xbt_queue_t queue, const void *src,double delay) { xbt_cond_signal(queue->not_empty); xbt_mutex_release(queue->mutex); } - + /** @brief Shift something from the message exchange queue, with a timeout. - * + * * @see #xbt_queue_shift - * + * */ void xbt_queue_shift_timed(xbt_queue_t queue, void* const dst,double delay) { double begin = xbt_time(); @@ -273,24 +273,24 @@ void xbt_queue_shift_timed(xbt_queue_t queue, void* const dst,double delay) { THROW0(timeout_error,0,"Delay = 0, and queue is empty"); } } else { - while ( (xbt_dynar_length(queue->data) == 0) && - (delay<0 || (xbt_time() - begin) <= delay) ) { + while ( (xbt_dynar_length(queue->data) == 0) && + (delay<0 || (xbt_time() - begin) <= delay) ) { DEBUG1("Queue %p empty. Waiting",queue); TRY { - xbt_cond_timedwait(queue->not_empty,queue->mutex, - delay<0 ? -1 : delay - (xbt_time()-begin)); + xbt_cond_timedwait(queue->not_empty,queue->mutex, + delay<0 ? -1 : delay - (xbt_time()-begin)); } CATCH(e) { - xbt_mutex_release(queue->mutex); - RETHROW; + xbt_mutex_release(queue->mutex); + RETHROW; } } } if (xbt_dynar_length(queue->data) == 0) { - xbt_mutex_release(queue->mutex); - THROW1(timeout_error,0,"Timeout (%f) elapsed, but queue still empty",delay); + xbt_mutex_release(queue->mutex); + THROW1(timeout_error,0,"Timeout (%f) elapsed, but queue still empty",delay); } - + xbt_dynar_shift(queue->data,dst); xbt_cond_signal(queue->not_full); xbt_mutex_release(queue->mutex); diff --git a/src/xbt/xbt_rl_synchro.c b/src/xbt/xbt_rl_synchro.c index d7d8a4dfa7..88c6859af4 100644 --- a/src/xbt/xbt_rl_synchro.c +++ b/src/xbt/xbt_rl_synchro.c @@ -6,7 +6,7 @@ /* This is the real life implementation, using xbt_os_thread to be portable */ /* to windows and linux. */ -/* Copyright 2006,2007 Malek Cherier, Martin Quinson +/* Copyright 2006,2007 Malek Cherier, Martin Quinson * All right reserved. */ /* This program is free software; you can redistribute it and/or modify it @@ -22,146 +22,146 @@ /* the implementation would be cleaner (and faster) with ELF symbol aliasing */ XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_sync_rl,xbt,"Synchronization mechanism (RL)"); -typedef struct s_xbt_thread_ { - xbt_os_thread_t os_thread; - void_f_pvoid_t code; - void *userparam; +typedef struct s_xbt_thread_ { + xbt_os_thread_t os_thread; + void_f_pvoid_t code; + void *userparam; }s_xbt_thread_t; -static void *xbt_thread_create_wrapper(void *p) { - xbt_thread_t t = (xbt_thread_t)p; - DEBUG1("I'm thread %p",p); - (*t->code)(t->userparam); - return NULL; +static void *xbt_thread_create_wrapper(void *p) { + xbt_thread_t t = (xbt_thread_t)p; + DEBUG1("I'm thread %p",p); + (*t->code)(t->userparam); + return NULL; } xbt_thread_t xbt_thread_create(const char*name,void_f_pvoid_t code, void* param) { - xbt_thread_t res = xbt_new0(s_xbt_thread_t,1); - res->userparam = param; - res->code = code; - DEBUG1("Create thread %p",res); - res->os_thread = xbt_os_thread_create(name,xbt_thread_create_wrapper,res); - return res; + xbt_thread_t res = xbt_new0(s_xbt_thread_t,1); + res->userparam = param; + res->code = code; + DEBUG1("Create thread %p",res); + res->os_thread = xbt_os_thread_create(name,xbt_thread_create_wrapper,res); + return res; } const char* xbt_thread_name(xbt_thread_t t) { - return xbt_os_thread_name(t->os_thread); + return xbt_os_thread_name(t->os_thread); } const char* xbt_thread_self_name(void) { - return xbt_os_thread_self_name(); + return xbt_os_thread_self_name(); } -void +void xbt_thread_join(xbt_thread_t thread) { - DEBUG1("Join thread %p",thread); - xbt_os_thread_join( thread->os_thread, NULL ); -} + DEBUG1("Join thread %p",thread); + xbt_os_thread_join( thread->os_thread, NULL ); +} void xbt_thread_exit() { - DEBUG0("Thread exits"); - xbt_os_thread_exit(NULL); + DEBUG0("Thread exits"); + xbt_os_thread_exit(NULL); } xbt_thread_t xbt_thread_self(void) { - return (xbt_thread_t)xbt_os_thread_self(); + return (xbt_thread_t)xbt_os_thread_self(); } void xbt_thread_yield(void) { - DEBUG0("Thread yields"); - xbt_os_thread_yield(); + DEBUG0("Thread yields"); + xbt_os_thread_yield(); } void xbt_thread_cancel(xbt_thread_t t) { - DEBUG1("Cancel thread %p",t); - xbt_os_thread_cancel(t->os_thread); + DEBUG1("Cancel thread %p",t); + xbt_os_thread_cancel(t->os_thread); } /****** mutex related functions ******/ struct xbt_mutex_ { - /* KEEP IT IN SYNC WITH OS IMPLEMENTATION (both win and lin) */ -#ifdef HAVE_PTHREAD_H - pthread_mutex_t m; + /* KEEP IT IN SYNC WITH OS IMPLEMENTATION (both win and lin) */ +#ifdef HAVE_PTHREAD_H + pthread_mutex_t m; #elif defined(WIN32) - CRITICAL_SECTION lock; -#endif + CRITICAL_SECTION lock; +#endif }; xbt_mutex_t xbt_mutex_init(void) { - xbt_mutex_t res = (xbt_mutex_t)xbt_os_mutex_init(); - DEBUG1("Create mutex %p", res); - return res; + xbt_mutex_t res = (xbt_mutex_t)xbt_os_mutex_init(); + DEBUG1("Create mutex %p", res); + return res; } void xbt_mutex_acquire(xbt_mutex_t mutex) { - DEBUG1("Acquire mutex %p", mutex); - xbt_os_mutex_acquire( (xbt_os_mutex_t)mutex ); + DEBUG1("Acquire mutex %p", mutex); + xbt_os_mutex_acquire( (xbt_os_mutex_t)mutex ); } void xbt_mutex_timedacquire(xbt_mutex_t mutex, double delay) { - DEBUG2("Acquire mutex %p with delay %lf", mutex,delay); - xbt_os_mutex_timedacquire( (xbt_os_mutex_t)mutex,delay ); + DEBUG2("Acquire mutex %p with delay %lf", mutex,delay); + xbt_os_mutex_timedacquire( (xbt_os_mutex_t)mutex,delay ); } void xbt_mutex_release(xbt_mutex_t mutex) { - DEBUG1("Unlock mutex %p", mutex); - xbt_os_mutex_release( (xbt_os_mutex_t)mutex ); + DEBUG1("Unlock mutex %p", mutex); + xbt_os_mutex_release( (xbt_os_mutex_t)mutex ); } void xbt_mutex_destroy(xbt_mutex_t mutex) { - DEBUG1("Destroy mutex %p", mutex); - xbt_os_mutex_destroy( (xbt_os_mutex_t)mutex ); + DEBUG1("Destroy mutex %p", mutex); + xbt_os_mutex_destroy( (xbt_os_mutex_t)mutex ); } #ifdef WIN32 - enum { /* KEEP IT IN SYNC WITH OS IMPLEM */ - SIGNAL = 0, - BROADCAST = 1, - MAX_EVENTS = 2 - }; +enum { /* KEEP IT IN SYNC WITH OS IMPLEM */ + SIGNAL = 0, + BROADCAST = 1, + MAX_EVENTS = 2 +}; #endif /***** condition related functions *****/ typedef struct xbt_cond_ { - /* KEEP IT IN SYNC WITH OS IMPLEMENTATION (both win and lin) */ -#ifdef HAVE_PTHREAD_H - pthread_cond_t c; -#elif defined(WIN32) - HANDLE events[MAX_EVENTS]; - - unsigned int waiters_count; /* the number of waiters */ - CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */ + /* KEEP IT IN SYNC WITH OS IMPLEMENTATION (both win and lin) */ +#ifdef HAVE_PTHREAD_H + pthread_cond_t c; +#elif defined(WIN32) + HANDLE events[MAX_EVENTS]; + + unsigned int waiters_count; /* the number of waiters */ + CRITICAL_SECTION waiters_count_lock; /* protect access to waiters_count */ #endif } s_xbt_cond_t; xbt_cond_t xbt_cond_init(void) { - xbt_cond_t res = (xbt_cond_t) xbt_os_cond_init(); - DEBUG1("Create cond %p", res); - return res; + xbt_cond_t res = (xbt_cond_t) xbt_os_cond_init(); + DEBUG1("Create cond %p", res); + return res; } void xbt_cond_wait(xbt_cond_t cond, xbt_mutex_t mutex) { - DEBUG2("Wait cond %p, mutex %p", cond, mutex); - xbt_os_cond_wait( (xbt_os_cond_t)cond, (xbt_os_mutex_t)mutex ); + DEBUG2("Wait cond %p, mutex %p", cond, mutex); + xbt_os_cond_wait( (xbt_os_cond_t)cond, (xbt_os_mutex_t)mutex ); } void xbt_cond_timedwait(xbt_cond_t cond, xbt_mutex_t mutex, double delay) { - DEBUG3("Wait cond %p, mutex %p for %f sec", cond, mutex,delay); - xbt_os_cond_timedwait( (xbt_os_cond_t)cond, (xbt_os_mutex_t)mutex, delay ); - DEBUG3("Done waiting cond %p, mutex %p for %f sec", cond, mutex, delay); + DEBUG3("Wait cond %p, mutex %p for %f sec", cond, mutex,delay); + xbt_os_cond_timedwait( (xbt_os_cond_t)cond, (xbt_os_mutex_t)mutex, delay ); + DEBUG3("Done waiting cond %p, mutex %p for %f sec", cond, mutex, delay); } void xbt_cond_signal(xbt_cond_t cond) { - DEBUG1("Signal cond %p", cond); - xbt_os_cond_signal( (xbt_os_cond_t)cond ); + DEBUG1("Signal cond %p", cond); + xbt_os_cond_signal( (xbt_os_cond_t)cond ); } - + void xbt_cond_broadcast(xbt_cond_t cond){ - DEBUG1("Broadcast cond %p", cond); - xbt_os_cond_broadcast( (xbt_os_cond_t)cond ); + DEBUG1("Broadcast cond %p", cond); + xbt_os_cond_broadcast( (xbt_os_cond_t)cond ); } void xbt_cond_destroy(xbt_cond_t cond){ - DEBUG1("Destroy cond %p", cond); - xbt_os_cond_destroy( (xbt_os_cond_t)cond ); + DEBUG1("Destroy cond %p", cond); + xbt_os_cond_destroy( (xbt_os_cond_t)cond ); } diff --git a/src/xbt/xbt_rl_time.c b/src/xbt/xbt_rl_time.c index 35bd11daa1..1f1f1c4e36 100644 --- a/src/xbt/xbt_rl_time.c +++ b/src/xbt/xbt_rl_time.c @@ -18,8 +18,8 @@ XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(gras_virtu); double xbt_time(void) { - return xbt_os_time(); + return xbt_os_time(); } void xbt_sleep(double sec) { - xbt_os_sleep(sec); + xbt_os_sleep(sec); } diff --git a/src/xbt/xbt_sg_stubs.c b/src/xbt/xbt_sg_stubs.c index 2524e6da86..88d78e4056 100644 --- a/src/xbt/xbt_sg_stubs.c +++ b/src/xbt/xbt_sg_stubs.c @@ -10,7 +10,7 @@ /* In RL, java is useless, and threads are always part of the picture, */ /* ucontext never */ - + /* Copyright (c) 2007 Martin Quinson. */ /* All rights reserved. */ @@ -30,76 +30,76 @@ /* Mod_init/exit mecanism */ void xbt_os_thread_mod_init(void) {} - + void xbt_os_thread_mod_exit(void) {} /* Main functions */ xbt_os_thread_t xbt_os_thread_create(const char*name,pvoid_f_pvoid_t start_routine,void* param) { - xbt_backtrace_display_current(); - xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_thread_create)"); + xbt_backtrace_display_current(); + xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_thread_create)"); } void xbt_os_thread_exit(int *retcode){ - xbt_backtrace_display_current(); - xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_thread_exit)"); + xbt_backtrace_display_current(); + xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_thread_exit)"); } xbt_os_thread_t xbt_os_thread_self(void){ - xbt_backtrace_display_current(); - xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_thread_self)"); + xbt_backtrace_display_current(); + xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_thread_self)"); } void xbt_os_thread_yield(void){ - xbt_backtrace_display_current(); - xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_thread_yield)"); + xbt_backtrace_display_current(); + xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_thread_yield)"); } xbt_os_mutex_t xbt_os_mutex_init(void){ - xbt_backtrace_display_current(); - xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_mutex_init)"); + xbt_backtrace_display_current(); + xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_mutex_init)"); } void xbt_os_mutex_acquire(xbt_os_mutex_t mutex){ - xbt_backtrace_display_current(); - xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_mutex_acquire)"); + xbt_backtrace_display_current(); + xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_mutex_acquire)"); } void xbt_os_mutex_release(xbt_os_mutex_t mutex){ - xbt_backtrace_display_current(); - xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_mutex_release)"); + xbt_backtrace_display_current(); + xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_mutex_release)"); } void xbt_os_mutex_destroy(xbt_os_mutex_t mutex){ - xbt_backtrace_display_current(); - xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_mutex_destroy)"); + xbt_backtrace_display_current(); + xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_mutex_destroy)"); } xbt_os_cond_t xbt_os_cond_init(void){ - xbt_backtrace_display_current(); - xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_cond_init)"); + xbt_backtrace_display_current(); + xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_cond_init)"); } void xbt_os_cond_wait(xbt_os_cond_t cond, xbt_os_mutex_t mutex){ - xbt_backtrace_display_current(); - xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_cond_wait)"); + xbt_backtrace_display_current(); + xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_cond_wait)"); } void xbt_os_cond_signal(xbt_os_cond_t cond){ - xbt_backtrace_display_current(); - xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_cond_signal)"); + xbt_backtrace_display_current(); + xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_cond_signal)"); } void xbt_os_cond_broadcast(xbt_os_cond_t cond){ - xbt_backtrace_display_current(); - xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_cond_broadcast)"); + xbt_backtrace_display_current(); + xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_cond_broadcast)"); } void xbt_os_cond_destroy(xbt_os_cond_t cond){ - xbt_backtrace_display_current(); - xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_cond_destroy)"); + xbt_backtrace_display_current(); + xbt_die("No pthread in SG when compiled against the ucontext (xbt_os_cond_destroy)"); } #endif diff --git a/src/xbt/xbt_sg_synchro.c b/src/xbt/xbt_sg_synchro.c index e7c1586fcc..120a1f255a 100644 --- a/src/xbt/xbt_sg_synchro.c +++ b/src/xbt/xbt_sg_synchro.c @@ -5,7 +5,7 @@ /* This is the simulation implementation, using simix. */ -/* Copyright 2006,2007 Malek Cherier, Martin Quinson +/* Copyright 2006,2007 Malek Cherier, Martin Quinson * All right reserved. */ /* This program is free software; you can redistribute it and/or modify it @@ -21,128 +21,128 @@ /* the implementation would be cleaner (and faster) with ELF symbol aliasing */ typedef struct s_xbt_thread_ { - char *name; - smx_process_t s_process; - void_f_pvoid_t code; - void *userparam; - void *father_data; + char *name; + smx_process_t s_process; + void_f_pvoid_t code; + void *userparam; + void *father_data; } s_xbt_thread_t; static int xbt_thread_create_wrapper(int argc, char *argv[]) { - xbt_thread_t t = (xbt_thread_t)SIMIX_process_get_data(SIMIX_process_self()); - SIMIX_process_set_data(SIMIX_process_self(),t->father_data); - (*t->code)(t->userparam); - return 0; + xbt_thread_t t = (xbt_thread_t)SIMIX_process_get_data(SIMIX_process_self()); + SIMIX_process_set_data(SIMIX_process_self(),t->father_data); + (*t->code)(t->userparam); + return 0; } xbt_thread_t xbt_thread_create(const char*name,void_f_pvoid_t code, void* param) { - xbt_thread_t res = xbt_new0(s_xbt_thread_t,1); - res->name = xbt_strdup(name); - res->userparam = param; - res->code = code; - res->father_data = SIMIX_process_get_data(SIMIX_process_self()); -// char*name = bprintf("%s#%p",SIMIX_process_get_name(SIMIX_process_self()), param); - res->s_process = SIMIX_process_create(name, - xbt_thread_create_wrapper, res, - SIMIX_host_get_name(SIMIX_host_self()), - 0,NULL,/*props*/NULL); -// free(name); - return res; + xbt_thread_t res = xbt_new0(s_xbt_thread_t,1); + res->name = xbt_strdup(name); + res->userparam = param; + res->code = code; + res->father_data = SIMIX_process_get_data(SIMIX_process_self()); + // char*name = bprintf("%s#%p",SIMIX_process_get_name(SIMIX_process_self()), param); + res->s_process = SIMIX_process_create(name, + xbt_thread_create_wrapper, res, + SIMIX_host_get_name(SIMIX_host_self()), + 0,NULL,/*props*/NULL); + // free(name); + return res; } const char* xbt_thread_name(xbt_thread_t t) { - return t->name; + return t->name; } const char* xbt_thread_self_name(void) { - xbt_thread_t me = xbt_thread_self(); - return me ? me->name : "maestro"; + xbt_thread_t me = xbt_thread_self(); + return me ? me->name : "maestro"; } -void +void xbt_thread_join(xbt_thread_t thread) { - THROW_UNIMPLEMENTED; /* FIXME */ -} + THROW_UNIMPLEMENTED; /* FIXME */ +} -void +void xbt_thread_cancel(xbt_thread_t thread) { - SIMIX_process_kill(thread->s_process); - free(thread->name); - free(thread); -} + SIMIX_process_kill(thread->s_process); + free(thread->name); + free(thread); +} void xbt_thread_exit() { - xbt_thread_t me=SIMIX_process_get_data(SIMIX_process_self()); - SIMIX_process_kill(me->s_process); - free(me); + xbt_thread_t me=SIMIX_process_get_data(SIMIX_process_self()); + SIMIX_process_kill(me->s_process); + free(me); } xbt_thread_t xbt_thread_self(void) { - smx_process_t p = SIMIX_process_self(); - return p ? SIMIX_process_get_data(p) : NULL; + smx_process_t p = SIMIX_process_self(); + return p ? SIMIX_process_get_data(p) : NULL; } void xbt_thread_yield(void) { - THROW_UNIMPLEMENTED; /* FIXME */ + THROW_UNIMPLEMENTED; /* FIXME */ } /****** mutex related functions ******/ struct s_xbt_mutex_ { - - /* KEEP IT IN SYNC WITH src/simix/private.h::struct s_smx_mutex */ - xbt_swag_t sleeping; /* list of sleeping process */ - int refcount ; - /* KEEP IT IN SYNC WITH src/simix/private.h::struct s_smx_mutex */ - + + /* KEEP IT IN SYNC WITH src/simix/private.h::struct s_smx_mutex */ + xbt_swag_t sleeping; /* list of sleeping process */ + int refcount ; + /* KEEP IT IN SYNC WITH src/simix/private.h::struct s_smx_mutex */ + }; xbt_mutex_t xbt_mutex_init(void) { - return (xbt_mutex_t)SIMIX_mutex_init(); + return (xbt_mutex_t)SIMIX_mutex_init(); } void xbt_mutex_acquire(xbt_mutex_t mutex) { - SIMIX_mutex_lock( (smx_mutex_t)mutex) ; + SIMIX_mutex_lock( (smx_mutex_t)mutex) ; } void xbt_mutex_release(xbt_mutex_t mutex) { - SIMIX_mutex_unlock( (smx_mutex_t)mutex ); + SIMIX_mutex_unlock( (smx_mutex_t)mutex ); } void xbt_mutex_destroy(xbt_mutex_t mutex) { - SIMIX_mutex_destroy( (smx_mutex_t)mutex ); + SIMIX_mutex_destroy( (smx_mutex_t)mutex ); } /***** condition related functions *****/ struct s_xbt_cond_ { - - /* KEEP IT IN SYNC WITH src/simix/private.h::struct s_smx_cond */ - xbt_swag_t sleeping; /* list of sleeping process */ - smx_mutex_t mutex; - xbt_fifo_t actions; /* list of actions */ - /* KEEP IT IN SYNC WITH src/simix/private.h::struct s_smx_cond */ + + /* KEEP IT IN SYNC WITH src/simix/private.h::struct s_smx_cond */ + xbt_swag_t sleeping; /* list of sleeping process */ + smx_mutex_t mutex; + xbt_fifo_t actions; /* list of actions */ + /* KEEP IT IN SYNC WITH src/simix/private.h::struct s_smx_cond */ }; xbt_cond_t xbt_cond_init(void) { - return (xbt_cond_t)SIMIX_cond_init(); + return (xbt_cond_t)SIMIX_cond_init(); } void xbt_cond_wait(xbt_cond_t cond, xbt_mutex_t mutex) { - SIMIX_cond_wait( (smx_cond_t)cond , (smx_mutex_t)mutex ); + SIMIX_cond_wait( (smx_cond_t)cond , (smx_mutex_t)mutex ); } void xbt_cond_timedwait(xbt_cond_t cond, xbt_mutex_t mutex, double delay) { - SIMIX_cond_wait_timeout( (smx_cond_t)cond , (smx_mutex_t)mutex, delay ); + SIMIX_cond_wait_timeout( (smx_cond_t)cond , (smx_mutex_t)mutex, delay ); } void xbt_cond_signal(xbt_cond_t cond) { - SIMIX_cond_signal( (smx_cond_t)cond ); + SIMIX_cond_signal( (smx_cond_t)cond ); } - + void xbt_cond_broadcast(xbt_cond_t cond){ - SIMIX_cond_broadcast( (smx_cond_t)cond ); + SIMIX_cond_broadcast( (smx_cond_t)cond ); } void xbt_cond_destroy(xbt_cond_t cond){ - SIMIX_cond_destroy( (smx_cond_t)cond ); + SIMIX_cond_destroy( (smx_cond_t)cond ); } diff --git a/src/xbt/xbt_sg_time.c b/src/xbt/xbt_sg_time.c index 8c820d932b..84ba8dfed7 100644 --- a/src/xbt/xbt_sg_time.c +++ b/src/xbt/xbt_sg_time.c @@ -9,7 +9,7 @@ #include "gras/Virtu/virtu_sg.h" -/* +/* * Time elapsed since the begining of the simulation. */ double xbt_time() { @@ -20,25 +20,25 @@ double xbt_time() { * Freeze the process for the specified amount of time */ void xbt_sleep(double sec) { - smx_action_t act_sleep; - smx_process_t proc = SIMIX_process_self(); - smx_mutex_t mutex; - smx_cond_t cond; - /* create action to sleep */ - act_sleep = SIMIX_action_sleep(SIMIX_process_get_host(proc),sec); - - mutex = SIMIX_mutex_init(); - SIMIX_mutex_lock(mutex); - /* create conditional and register action to it */ - cond = SIMIX_cond_init(); - - SIMIX_register_action_to_condition(act_sleep, cond); - SIMIX_cond_wait(cond,mutex); - SIMIX_mutex_unlock(mutex); - - /* remove variables */ - SIMIX_cond_destroy(cond); - SIMIX_mutex_destroy(mutex); - SIMIX_action_destroy(act_sleep); + smx_action_t act_sleep; + smx_process_t proc = SIMIX_process_self(); + smx_mutex_t mutex; + smx_cond_t cond; + /* create action to sleep */ + act_sleep = SIMIX_action_sleep(SIMIX_process_get_host(proc),sec); + + mutex = SIMIX_mutex_init(); + SIMIX_mutex_lock(mutex); + /* create conditional and register action to it */ + cond = SIMIX_cond_init(); + + SIMIX_register_action_to_condition(act_sleep, cond); + SIMIX_cond_wait(cond,mutex); + SIMIX_mutex_unlock(mutex); + + /* remove variables */ + SIMIX_cond_destroy(cond); + SIMIX_mutex_destroy(mutex); + SIMIX_action_destroy(act_sleep); } diff --git a/src/xbt/xbt_sha.c b/src/xbt/xbt_sha.c index 898c86abc9..bca3bf22e5 100644 --- a/src/xbt/xbt_sha.c +++ b/src/xbt/xbt_sha.c @@ -14,10 +14,10 @@ #include "xbt/hash.h" struct s_xbt_sha_ { - unsigned int hash[5]; - unsigned int buf[80]; - int blen; - unsigned int lenhi, lenlo; + unsigned int hash[5]; + unsigned int buf[80]; + int blen; + unsigned int lenhi, lenlo; }; static void sha_calculate (xbt_sha_t sha); @@ -27,84 +27,84 @@ static void sha_calculate (xbt_sha_t sha); /** @brief constructor */ xbt_sha_t xbt_sha_new (void) { - xbt_sha_t sha; + xbt_sha_t sha; - sha = xbt_new(s_xbt_sha_t,1); - xbt_sha_reset (sha); - - return sha; + sha = xbt_new(s_xbt_sha_t,1); + xbt_sha_reset (sha); + + return sha; } /** @brief destructor */ void xbt_sha_free (xbt_sha_t sha) { - free (sha); + free (sha); } void xbt_sha_reset (xbt_sha_t sha) { - memset (sha, 0, sizeof (s_xbt_sha_t)); - sha->hash[0] = 0x67452301; - sha->hash[1] = 0xefcdab89; - sha->hash[2] = 0x98badcfe; - sha->hash[3] = 0x10325476; - sha->hash[4] = 0xc3d2e1f0; + memset (sha, 0, sizeof (s_xbt_sha_t)); + sha->hash[0] = 0x67452301; + sha->hash[1] = 0xefcdab89; + sha->hash[2] = 0x98badcfe; + sha->hash[3] = 0x10325476; + sha->hash[4] = 0xc3d2e1f0; } /* @brief Add some more data to the buffer */ void xbt_sha_feed (xbt_sha_t sha, const unsigned char *data, size_t len) { - int i; - - for (i=0; ibuf[sha->blen / 4] <<= 8; - sha->buf[sha->blen / 4] |= (unsigned int)data[i]; - if ((++sha->blen) % 64 == 0) { - sha_calculate (sha); - sha->blen = 0; - } - sha->lenlo += 8; - sha->lenhi += (sha->lenlo < 8); - } + int i; + + for (i=0; ibuf[sha->blen / 4] <<= 8; + sha->buf[sha->blen / 4] |= (unsigned int)data[i]; + if ((++sha->blen) % 64 == 0) { + sha_calculate (sha); + sha->blen = 0; + } + sha->lenlo += 8; + sha->lenhi += (sha->lenlo < 8); + } } /* finalize computation before displaying the result */ static void xbt_sha_finalize (xbt_sha_t sha) { - unsigned char pad[8]; - unsigned char padc; - - pad[0] = (unsigned char)((sha->lenhi >> 24) & 0xff); - pad[1] = (unsigned char)((sha->lenhi >> 16) & 0xff); - pad[2] = (unsigned char)((sha->lenhi >> 8) & 0xff); - pad[3] = (unsigned char)(sha->lenhi & 0xff); - pad[4] = (unsigned char)((sha->lenlo >> 24) & 0xff); - pad[5] = (unsigned char)((sha->lenlo >> 16) & 0xff); - pad[6] = (unsigned char)((sha->lenlo >> 8) & 0xff); - pad[7] = (unsigned char)(sha->lenlo & 255); - - padc = 0x80; - xbt_sha_feed (sha, &padc, 1); - - padc = 0x00; - while (sha->blen != 56) - xbt_sha_feed (sha, &padc, 1); - - xbt_sha_feed (sha, pad, 8); + unsigned char pad[8]; + unsigned char padc; + + pad[0] = (unsigned char)((sha->lenhi >> 24) & 0xff); + pad[1] = (unsigned char)((sha->lenhi >> 16) & 0xff); + pad[2] = (unsigned char)((sha->lenhi >> 8) & 0xff); + pad[3] = (unsigned char)(sha->lenhi & 0xff); + pad[4] = (unsigned char)((sha->lenlo >> 24) & 0xff); + pad[5] = (unsigned char)((sha->lenlo >> 16) & 0xff); + pad[6] = (unsigned char)((sha->lenlo >> 8) & 0xff); + pad[7] = (unsigned char)(sha->lenlo & 255); + + padc = 0x80; + xbt_sha_feed (sha, &padc, 1); + + padc = 0x00; + while (sha->blen != 56) + xbt_sha_feed (sha, &padc, 1); + + xbt_sha_feed (sha, pad, 8); } /** @brief returns the sha hash into a newly allocated buffer (+ reset sha object) */ char *xbt_sha_read(xbt_sha_t sha) { - char *res = xbt_malloc(40); - xbt_sha_print(sha,res); - return res; + char *res = xbt_malloc(40); + xbt_sha_print(sha,res); + return res; } /** @brief copy the content sha hash into the @a hash pre-allocated string (and reset buffer) */ void xbt_sha_print (xbt_sha_t sha, char *hash) { - int i; - - xbt_sha_finalize(sha); - for (i=0; i<5; i++) { - sprintf (hash, "%08x", sha->hash[i]); - hash += 8; - } + int i; + + xbt_sha_finalize(sha); + for (i=0; i<5; i++) { + sprintf (hash, "%08x", sha->hash[i]); + hash += 8; + } } @@ -114,7 +114,7 @@ void xbt_sha (const char *data, char *hash) { xbt_sha_reset (&sha); xbt_sha_feed (&sha, (const unsigned char*)data, strlen (data)); - + xbt_sha_print (&sha, hash); } @@ -124,39 +124,39 @@ void xbt_sha (const char *data, char *hash) { #define SRL(x,y) (((x) << (y)) | ((x) >> (32-(y)))) #define SHA(a,b,f,c) \ - for (i= (a) ; i<= (b) ; i++) { \ - TMP = SRL(A,5) + ( (f) ) + E + sha->buf[i] + (c) ; \ - E = D; \ - D = C; \ - C = SRL(B,30); \ - B = A; \ - A = TMP; \ - } + for (i= (a) ; i<= (b) ; i++) { \ + TMP = SRL(A,5) + ( (f) ) + E + sha->buf[i] + (c) ; \ + E = D; \ + D = C; \ + C = SRL(B,30); \ + B = A; \ + A = TMP; \ + } static void sha_calculate (xbt_sha_t sha) { - int i; - unsigned int A, B, C, D, E, TMP; - - for (i=16; i<80; i++) - sha->buf[i] = SRL (sha->buf[i-3] ^ sha->buf[i-8] ^ sha->buf[i-14] ^ sha->buf[i-16], 1); - - A = sha->hash[0]; - B = sha->hash[1]; - C = sha->hash[2]; - D = sha->hash[3]; - E = sha->hash[4]; - - SHA (0, 19, ((C^D)&B)^D, 0x5a827999); - SHA (20, 39, B^C^D, 0x6ed9eba1); - SHA (40, 59, (B&C)|(D&(B|C)), 0x8f1bbcdc); - SHA (60, 79, B^C^D, 0xca62c1d6); - - sha->hash[0] += A; - sha->hash[1] += B; - sha->hash[2] += C; - sha->hash[3] += D; - sha->hash[4] += E; + int i; + unsigned int A, B, C, D, E, TMP; + + for (i=16; i<80; i++) + sha->buf[i] = SRL (sha->buf[i-3] ^ sha->buf[i-8] ^ sha->buf[i-14] ^ sha->buf[i-16], 1); + + A = sha->hash[0]; + B = sha->hash[1]; + C = sha->hash[2]; + D = sha->hash[3]; + E = sha->hash[4]; + + SHA (0, 19, ((C^D)&B)^D, 0x5a827999); + SHA (20, 39, B^C^D, 0x6ed9eba1); + SHA (40, 59, (B&C)|(D&(B|C)), 0x8f1bbcdc); + SHA (60, 79, B^C^D, 0xca62c1d6); + + sha->hash[0] += A; + sha->hash[1] += B; + sha->hash[2] += C; + sha->hash[3] += D; + sha->hash[4] += E; } /* ************* */ @@ -168,7 +168,7 @@ static void sha_calculate (xbt_sha_t sha) static char* mycmp(const char *p1, const char *p2,size_t n) { int i; - + for (i=0; i= (*n) + 1) *buf = xbt_realloc(*buf, *n += 512); - + (*buf)[i] = ch; - + if ((*buf)[i] == '\n') { i++; (*buf)[i] = '\0'; break; - } + } } - - if (i == *n) + + if (i == *n) *buf = xbt_realloc(*buf, *n += 1); - + (*buf)[i] = '\0'; return (ssize_t)i; @@ -519,11 +519,11 @@ long getline(char **buf, size_t *n, FILE *stream) { #endif /* HAVE_GETLINE */ /* - * Diff related functions + * Diff related functions */ static xbt_matrix_t diff_build_LCS(xbt_dynar_t da, xbt_dynar_t db) { xbt_matrix_t C = xbt_matrix_new(xbt_dynar_length(da),xbt_dynar_length(db), - sizeof(int),NULL); + sizeof(int),NULL); unsigned long i,j; /* Compute the LCS */ @@ -542,14 +542,14 @@ static xbt_matrix_t diff_build_LCS(xbt_dynar_t da, xbt_dynar_t db) { return C[m,n] */ if (xbt_dynar_length(db) != 0) - for (i=0; i 0 and j > 0 and X[i] = Y[j] printDiff(C, X, Y, i-1, j-1) @@ -585,22 +585,22 @@ static void diff_build_diff(xbt_dynar_t res, diff_build_diff(res,C,da,db,i-1,j-1); topush = bprintf(" %s",xbt_dynar_get_as(da,i,char*)); xbt_dynar_push(res, &topush); - } else if (j>=0 && + } else if (j>=0 && (i<=0 ||j==0|| xbt_matrix_get_as(C,i,j-1,int) >= xbt_matrix_get_as(C,i-1,j,int))) { diff_build_diff(res,C,da,db,i,j-1); topush = bprintf("+ %s",xbt_dynar_get_as(db,j,char*)); xbt_dynar_push(res,&topush); - } else if (i>=0 && + } else if (i>=0 && (j<=0 || xbt_matrix_get_as(C,i,j-1,int) < xbt_matrix_get_as(C,i-1,j,int))) { diff_build_diff(res,C,da,db,i-1,j); topush = bprintf("- %s",xbt_dynar_get_as(da,i,char*)); - xbt_dynar_push(res,&topush); + xbt_dynar_push(res,&topush); } else if (i<=0 && j<=0) { return; } else { THROW2(arg_error,0,"Invalid values: i=%d, j=%d",i,j); } - + } /** @brief Compute the unified diff of two strings */ @@ -611,7 +611,7 @@ char *xbt_str_diff(char *a, char *b) { xbt_matrix_t C = diff_build_LCS(da,db); xbt_dynar_t diff = xbt_dynar_new(sizeof(char*),xbt_free_ref); char *res=NULL; - + diff_build_diff(diff, C, da,db, xbt_dynar_length(da)-1, xbt_dynar_length(db)-1); /* Clean empty lines at the end */ while (xbt_dynar_length(diff) > 0) { @@ -622,14 +622,14 @@ char *xbt_str_diff(char *a, char *b) { } else { xbt_dynar_push(diff,&str); break; - } - } + } + } res = xbt_str_join(diff, "\n"); xbt_dynar_free(&da); xbt_dynar_free(&db); xbt_dynar_free(&diff); xbt_matrix_free(C); - + return res; } diff --git a/src/xbt/xbt_virtu.c b/src/xbt/xbt_virtu.c index bed1aca7d8..041bbd4026 100644 --- a/src/xbt/xbt_virtu.c +++ b/src/xbt/xbt_virtu.c @@ -12,7 +12,7 @@ #include "xbt/function_types.h" static int xbt_fake_pid(void) { - return 0; + return 0; } int_f_void_t xbt_getpid=xbt_fake_pid; -- 2.20.1