Skip to content

Commit

Permalink
Avoid potential race in gensym
Browse files Browse the repository at this point in the history
It is harmless as far as gensym result is used as uninterned symbols,
but we also dump the name to a file, expecting it is unique, so
it's better to avoid conflicts.
  • Loading branch information
shirok committed Nov 27, 2024
1 parent a8e04a5 commit 5715291
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
8 changes: 8 additions & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
2024-11-26 Shiro Kawai <shiro@acm.org>

* src/symbol.c (Scm_Gensym): Avoid race. It is theoretically
harmless as far as gensym result is used as uninterned symbols
(even two threads reads the same counter, created symbols are
different), but their name can be dumped to a file, and it
is better to avoid conflicts.

2024-11-25 Shiro Kawai <shiro@acm.org>

* src/libeval.scm (load-from-port): Use with-exception-handler
Expand Down
14 changes: 9 additions & 5 deletions src/symbol.c
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
#define LIBGAUCHE_BODY
#include "gauche.h"
#include "gauche/priv/configP.h"
#include "gauche/priv/atomicP.h"
#include "gauche/priv/builtin-syms.h"
#include "gauche/priv/moduleP.h"

Expand Down Expand Up @@ -158,13 +159,16 @@ static SCM_DEFINE_STRING_CONST(default_prefix, "G", 1, 1);
ScmObj Scm_Gensym(ScmString *prefix)
{
char numbuf[50];
/* We don't need mutex for this variable, since the race on it is
tolerated---multiple threads may get the same name symbols,
but they are uninterned and never be eq? to each other. */
static intptr_t gensym_count = 0;
static ScmAtomicVar gensym_count = 0;
ScmAtomicWord mycount = Scm_AtomicLoad(&gensym_count);

while (!Scm_AtomicCompareExchange(&gensym_count, &mycount, mycount+1)) {
mycount = Scm_AtomicLoad(&gensym_count);
Scm_YieldCPU();
}

if (prefix == NULL) prefix = &default_prefix;
int nc = snprintf(numbuf, 49, "%"PRIdPTR, gensym_count++);
int nc = snprintf(numbuf, 49, "%"PRIdPTR, mycount);
numbuf[49] = '\0';
ScmObj name = Scm_StringAppendC(prefix, numbuf, nc, nc);
ScmSymbol *sym = make_sym(SCM_CLASS_SYMBOL, SCM_STRING(name), FALSE);
Expand Down

0 comments on commit 5715291

Please sign in to comment.