Skip to content

Commit e125cab

Browse files
author
Warren Fernandes
authored
Merge pull request #28 from l2dy/pointer-semantics
output: fix misuse of unsafe.Pointer
2 parents 215d680 + b191f58 commit e125cab

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

output/output.go

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -69,15 +69,22 @@ func FLBPluginConfigKey(plugin unsafe.Pointer, key string) string {
6969
return value
7070
}
7171

72-
var contexts []interface{}
72+
var contexts = make(map[uintptr]interface{})
7373

7474
func FLBPluginSetContext(plugin unsafe.Pointer, ctx interface{}) {
75-
i := len(contexts)
76-
contexts = append(contexts, ctx)
75+
// Allocate a byte of memory in the C heap and fill it with '\0',
76+
// then convert its pointer into the C type void*, represented by unsafe.Pointer.
77+
// The C string is not managed by Go GC, so it will not be freed automatically.
78+
i := unsafe.Pointer(C.CString(""))
79+
// uintptr(i) produces the memory address of i, and malloc() guarantees uniqueness of it.
80+
//
81+
// FLBPluginSetContext must not be called concurrently with itself or FLBPluginGetContext.
82+
// A sync.RWMutex must be added if this might happen.
83+
contexts[uintptr(i)] = ctx
7784
p := (*FLBOutPlugin)(plugin)
78-
p.context.remote_context = unsafe.Pointer(uintptr(i))
85+
p.context.remote_context = i
7986
}
8087

8188
func FLBPluginGetContext(i unsafe.Pointer) interface{} {
82-
return contexts[int(uintptr(i))]
89+
return contexts[uintptr(i)]
8390
}

0 commit comments

Comments
 (0)