Skip to content

Possible memory leak: runCode allocates C.CString(call.SourcePath) on every call and never frees it #53

Open

Description

@OvOhao

Description

In pkg/janet/exec.go (commit a08b5cb), runCode converts the source path for every call:

sourcePtr := C.CString(call.SourcePath)   // :118
...
C.janet_wrap_string(C.janet_cstring(sourcePtr))   // :139-141

janet_cstring copies the bytes into a Janet GC string (janet.c:30230 -> janet_string, janet.c:30191-30199), so sourcePtr is not needed after that call. It is never freed, on the normal path or on the early returns at :127-128, :153 and :168.

runCode runs for every VM.ExecuteCall (through callRequest and poll, module.go:107-109). That includes cy exec RPCs (cmd/cy/rpc.go:161-168), hook/init on every client connection (pkg/cy/client.go:139, with an empty SourcePath there), shell/attach, register/set, and config loading. In the long-running server each call leaves len(SourcePath)+1 bytes allocated.

runCodeUnsafe in the same file frees its sourcePtr (:79), and wrapFile uses defer C.free (:275-276).

Reproduction

A small program using this package (macOS arm64, Go 1.27) creates a VM with janet.New and calls ExecuteCall N times with a 48-character SourcePath (UpdateEnv: false). Under MallocStackLogging=1 leaks --atExit:

N=100:  107 leaks for 6640 total leaked bytes    (100 x 64-byte blocks from _cgo_..._Cfunc__Cmalloc)
N=1000: 1007 leaks for 64240 total leaked bytes  (1000 x 64-byte blocks from _cgo_..._Cfunc__Cmalloc)

The other 7 blocks are present for any N: 6 x 32 bytes from VM setup and one 48-byte xpc_date_t that macOS reports for every Go program. With the fix below, N=1000 reports only those 7 blocks, and go test ./pkg/janet/ passes.

Suggested fix

sourcePtr := C.CString(call.SourcePath)
defer C.free(unsafe.Pointer(sourcePtr))

If you could credit me as a reporter for my contributions to security advisory I will be thankful.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions