Skip to content

Commit

Permalink
nim-lang#13806 - first call sysctl with a null buffer to get the leng…
Browse files Browse the repository at this point in the history
…th, then alloc buffer and call again
  • Loading branch information
euantorano committed Mar 30, 2020
1 parent 0ac9c7b commit ad4d1d2
Showing 1 changed file with 16 additions and 16 deletions.
32 changes: 16 additions & 16 deletions lib/pure/os.nim
Original file line number Diff line number Diff line change
Expand Up @@ -2787,23 +2787,23 @@ when not weirdTarget and (defined(freebsd) or defined(dragonfly)):
const KERN_PROC_PATHNAME = 9

proc getApplFreebsd(): string =
var pathLength = csize_t(MAX_PATH)
result = newString(pathLength)
var pathLength: csize = 0
var req = [CTL_KERN.cint, KERN_PROC.cint, KERN_PROC_PATHNAME.cint, -1.cint]
while true:
let res = sysctl(addr req[0], 4, cast[pointer](addr result[0]),
addr pathLength, nil, 0)
if res < 0:
let err = osLastError()
if err.int32 == ENOMEM:
result = newString(pathLength)
else:
result.setLen(0) # error!
break
else:
# trim the trailing null byte, as the result is a string not a cstring
result.setLen(pathLength-1)
break

# first call to get the required length
var res = sysctl(addr req[0], 4, nil, addr pathLength, nil, 0)

if res < 0:
return ""

result = newString(pathLength)
res = sysctl(addr req[0], 4, cast[pointer](addr result[0]), addr pathLength, nil, 0)

if res < 0:
result = ""

let realLen = len(cstring(result))
setLen(result, realLen)

when not weirdTarget and (defined(linux) or defined(solaris) or defined(bsd) or defined(aix)):
proc getApplAux(procPath: string): string =
Expand Down

0 comments on commit ad4d1d2

Please sign in to comment.