Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,14 @@ parameter and result types, not just their source-level shape. Use

- Hot code reloading works on Linux on arm64 with glibc; before, it was
limited to musl there and the HCR runtime did not compile.
- The new switch `--compileTime:restricted` limits what compiling a project
can do: compile-time code runs only the command lines given with
`--staticExecWhitelist:"<command line>"`, reads only below the project, `--path`,
nimble package and Nim `lib` directories, and cannot write files or change
the environment; configuration files of the project and its parent
directories are not read. The default, `--compileTime:normal`, is unchanged.
`{.passC.}`, `{.passL.}`, `{.compile.}`, `{.link.}` and `getEnv` are not
covered. See "Compiling code you have not read" in the compiler user guide.

- An import annotated with `{.cyclic.}` (`import b {.cyclic.}`) makes the
modules of an import cycle a group whose types and leading routines are
Expand Down
19 changes: 19 additions & 0 deletions compiler/commands.nim
Original file line number Diff line number Diff line change
Expand Up @@ -678,6 +678,14 @@ proc pathRelativeToConfig(arg: string, pass: TCmdLinePass, conf: ConfigRef): str
else:
result = arg

proc checkVmopsDangerConflict(conf: ConfigRef; info: TLineInfo) =
# vmopsDanger enables `execCmdEx` at compile time, which bypasses the
# `--staticExecWhitelist`
if vmopsDanger in conf.features and conf.compileTimeMode == ctmRestricted:
liMessage(conf, info, errGenerated,
"--experimental:vmopsDanger cannot be combined with --compileTime:restricted",
doAbort, instLoc())

proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
conf: ConfigRef) =
var key = ""
Expand Down Expand Up @@ -1087,6 +1095,16 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
if conf.backend == backendJs:
# for now, -r uses nodejs, so define nodejs
defineSymbol(conf.symbols, "nodejs")
of "compiletime":
expectArg(conf, switch, arg, pass, info)
case arg.normalize
of "normal": conf.compileTimeMode = ctmNormal
of "restricted": conf.compileTimeMode = ctmRestricted
else: localError(conf, info, "expected 'normal' or 'restricted' but found '$1'" % arg)
checkVmopsDangerConflict(conf, info)
of "staticexecwhitelist":
expectArg(conf, switch, arg, pass, info)
if arg notin conf.staticExecWhitelist: conf.staticExecWhitelist.add arg
of "maxloopiterationsvm":
expectArg(conf, switch, arg, pass, info)
var value: int = 10_000_000
Expand Down Expand Up @@ -1262,6 +1280,7 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo;
conf.features.incl parseEnum[Feature](arg)
except ValueError:
localError(conf, info, "unknown experimental feature")
checkVmopsDangerConflict(conf, info)
of "legacy":
try:
conf.legacyFeatures.incl parseEnum[LegacyFeature](arg)
Expand Down
11 changes: 11 additions & 0 deletions compiler/gorgeimpl.nim
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,18 @@ proc readOutput(p: Process): (string, int) =
result[0].setLen(result[0].len - "\n".len)
result[1] = p.waitForExit

proc checkCommandAllowed*(conf: ConfigRef; cmd: string; info: TLineInfo) =
## Under `--compileTime:restricted`, compile-time code runs only the command
## lines given with `--staticExecWhitelist`, compared as whole strings: allowing a
## program by name would allow its options that run other commands
## (`sh -c`, `git -c alias.x=!cmd`).
if compileTimeEffects(conf, skippedByCheck = false) == cteRestrict and
cmd notin conf.staticExecWhitelist:
globalError(conf, info, "command refused by --compileTime:restricted, " &
"it is not in --staticExecWhitelist: '" & cmd & "'")

proc opGorge*(cmd, input, cache: string, info: TLineInfo; conf: ConfigRef): (string, int) =
checkCommandAllowed(conf, cmd, info) # before the cache: a cached result is still a run
let workingDir = parentDir(toFullPath(conf, info))
result = ("", 0)
if cache.len > 0:
Expand Down
12 changes: 8 additions & 4 deletions compiler/nimconf.nim
Original file line number Diff line number Diff line change
Expand Up @@ -286,15 +286,19 @@ proc loadConfigs*(cfg: RelativeFile; cache: IdentCache; conf: ConfigRef; idgen:
if cfg == DefaultConfig:
runNimScriptIfExists(getUserConfigPath(DefaultConfigNims))

# `--compileTime:restricted` reads no configuration from the project or the
# directories above it: `nim.cfg` runs commands too (`gcc.exe`, `@putenv`).
# Only the system and user configuration and the command line are trusted.
let restricted = conf.compileTimeMode == ctmRestricted
let pd = if not conf.projectPath.isEmpty: conf.projectPath else: AbsoluteDir(getCurrentDir())
if optSkipParentConfigFiles notin conf.globalOptions:
if optSkipParentConfigFiles notin conf.globalOptions and not restricted:
for dir in parentDirs(pd.string, fromRoot=true, inclusive=false):
readConfigFile(AbsoluteDir(dir) / cfg)

if cfg == DefaultConfig:
runNimScriptIfExists(AbsoluteDir(dir) / DefaultConfigNims)

if optSkipProjConfigFile notin conf.globalOptions:
if optSkipProjConfigFile notin conf.globalOptions and not restricted:
readConfigFile(pd / cfg)
if cfg == DefaultConfig:
runNimScriptIfExists(pd / DefaultConfigNims)
Expand All @@ -319,10 +323,10 @@ proc loadConfigs*(cfg: RelativeFile; cache: IdentCache; conf: ConfigRef; idgen:
if not conf.ideActive and conf.cmd notin {cmdCheck, cmdDump}:
if conf.cmd == cmdNimscript:
runNimScriptIfExists(conf.projectFull, isMain = true)
else:
elif not restricted or scriptIsProj:
runNimScriptIfExists(scriptFile, isMain = true)
else:
if not scriptIsProj:
if not scriptIsProj and not restricted:
runNimScriptIfExists(scriptFile, isMain = true)
else:
# 'nimsuggest foo.nims' means to just auto-complete the NimScript file
Expand Down
27 changes: 27 additions & 0 deletions compiler/options.nim
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,19 @@ type
# gcRefc and the GCs that follow it use a write barrier,
# as far as usesWriteBarrier() is concerned

CompileTimeMode* = enum ## `--compileTime`
ctmNormal = "normal"
ctmRestricted = "restricted"

CompileTimeEffects* = enum
## What compile-time code may do to the world outside the compiler: run a
## program, or change files or the environment. See `compileTimeEffects`.
cteRun ## the call runs
cteSkip ## `nim check` and nimsuggest: the call does nothing, so that
## checking code never changes anything
cteRestrict ## `--compileTime:restricted`: a command runs only when it is
## on the `--staticExecWhitelist`; any other call is an error

IdeCmd* = enum
ideNone, ideSug, ideCon, ideDef, ideUse, ideDus, ideChk, ideChkFile, ideMod,
ideHighlight, ideOutline, ideKnown, ideMsg, ideProject, ideGlobalSymbols,
Expand Down Expand Up @@ -611,6 +624,8 @@ type
expandPosition*: TLineInfo

currentConfigDir*: string # used for passPP only; absolute dir
compileTimeMode*: CompileTimeMode
staticExecWhitelist*: seq[string] # exact command lines (`--staticExecWhitelist`)
clientProcessId*: int


Expand Down Expand Up @@ -879,6 +894,18 @@ proc icReuseSemLowering*(conf: ConfigRef): bool {.inline.} =
## doc/ic_backend_simplify.md §6b.
isDefined(conf, "icReuseSemLowering")

proc compileTimeEffects*(conf: ConfigRef; skippedByCheck = true): CompileTimeEffects =
## The one answer to "may compile-time code (macros, `static`, NimScript) run
## a program or change files or the environment?".
## `skippedByCheck` is false for the calls that `nim check` has always run
## (`putEnv`, `delEnv`, NimScript's `mkDir`); `nim check` keeps doing so.
if skippedByCheck and (defined(nimsuggest) or conf.cmd == cmdCheck):
cteSkip
elif conf.compileTimeMode == ctmRestricted:
cteRestrict
else:
cteRun

proc importantComments*(conf: ConfigRef): bool {.inline.} = conf.ideActive or conf.cmd in cmdDocLike
proc usesWriteBarrier*(conf: ConfigRef): bool {.inline.} = conf.selectedGC >= gcRefc
proc usesSso*(conf: ConfigRef): bool {.inline.} = conf.selectedStrings == stringSso
Expand Down
51 changes: 24 additions & 27 deletions compiler/scriptconfig.nim
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

import
ast, modules, idents, condsyms,
options, llstream, vm, vmdef, commands,
options, llstream, vm, vmdef, vmdeps, gorgeimpl, commands,
wordrecg, modulegraphs, lineinfos,
pathutils, pipelines

Expand Down Expand Up @@ -60,24 +60,28 @@ proc setupVM*(module: PSym; cache: IdentCache; scriptName: string;
template cbos(name, body) {.dirty.} =
cbexc(name, OSError, body)

template effect(name: string; skippedByCheck: bool; body) {.dirty.} =
## `body` changes files or the environment; see `compileTimeEffects`.
case compileTimeEffects(conf, skippedByCheck)
of cteSkip: discard
of cteRestrict: refuseCompileTimeEffect(conf, a.currentLineInfo, name)
of cteRun: body

# Idea: Treat link to file as a file, but ignore link to directory to prevent
# endless recursions out of the box.
cbos listFilesImpl:
listDirs(a, {pcFile, pcLinkToFile})
cbos listDirsImpl:
listDirs(a, {pcDir})
cbos removeDir:
if defined(nimsuggest) or graph.config.cmd == cmdCheck:
discard
else:
effect("removeDir", skippedByCheck = true):
os.removeDir(getString(a, 0), getBool(a, 1))
cbos removeFile:
if defined(nimsuggest) or graph.config.cmd == cmdCheck:
discard
else:
effect("removeFile", skippedByCheck = true):
os.removeFile getString(a, 0)
cbos createDir:
os.createDir getString(a, 0)
effect("createDir", skippedByCheck = false):
os.createDir getString(a, 0)

result.registerCallback "stdlib.system.getError",
proc (a: VmArgs) = setResult(a, errorMsg)
Expand All @@ -87,44 +91,37 @@ proc setupVM*(module: PSym; cache: IdentCache; scriptName: string;
cbos getCurrentDir:
setResult(a, os.getCurrentDir())
cbos moveFile:
if defined(nimsuggest) or graph.config.cmd == cmdCheck:
discard
else:
effect("moveFile", skippedByCheck = true):
os.moveFile(getString(a, 0), getString(a, 1))
cbos moveDir:
if defined(nimsuggest) or graph.config.cmd == cmdCheck:
discard
else:
effect("moveDir", skippedByCheck = true):
os.moveDir(getString(a, 0), getString(a, 1))
cbos copyFile:
if defined(nimsuggest) or graph.config.cmd == cmdCheck:
discard
else:
effect("copyFile", skippedByCheck = true):
os.copyFile(getString(a, 0), getString(a, 1))
cbos copyDir:
if defined(nimsuggest) or graph.config.cmd == cmdCheck:
discard
else:
effect("copyDir", skippedByCheck = true):
os.copyDir(getString(a, 0), getString(a, 1))
cbos getLastModificationTime:
setResult(a, getLastModificationTime(getString(a, 0)).toUnix)
cbos findExe:
setResult(a, os.findExe(getString(a, 0)))

cbos rawExec:
if defined(nimsuggest) or graph.config.cmd == cmdCheck:
discard
else:
if compileTimeEffects(conf) != cteSkip:
checkCommandAllowed(conf, getString(a, 0), a.currentLineInfo)
setResult(a, osproc.execCmd getString(a, 0))

cbconf getEnv:
setResult(a, os.getEnv(a.getString 0, a.getString 1))
cbconf existsEnv:
setResult(a, os.existsEnv(a.getString 0))
cbconf putEnv:
os.putEnv(a.getString 0, a.getString 1)
effect("putEnv", skippedByCheck = false):
os.putEnv(a.getString 0, a.getString 1)
cbconf delEnv:
os.delEnv(a.getString 0)
effect("delEnv", skippedByCheck = false):
os.delEnv(a.getString 0)
cbconf dirExists:
setResult(a, os.dirExists(a.getString 0))
cbconf fileExists:
Expand Down Expand Up @@ -183,12 +180,12 @@ proc setupVM*(module: PSym; cache: IdentCache; scriptName: string;
cbconf cppDefine:
options.cppDefine(conf, a.getString(0))
cbexc stdinReadLine, EOFError:
if defined(nimsuggest) or graph.config.cmd == cmdCheck:
if compileTimeEffects(conf) == cteSkip:
setResult(a, "")
else:
setResult(a, stdin.readLine())
cbexc stdinReadAll, EOFError:
if defined(nimsuggest) or graph.config.cmd == cmdCheck:
if compileTimeEffects(conf) == cteSkip:
setResult(a, "")
else:
setResult(a, stdin.readAll())
Expand Down
4 changes: 2 additions & 2 deletions compiler/vm.nim
Original file line number Diff line number Diff line change
Expand Up @@ -1979,8 +1979,8 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): Address =
putStr(ra, opSlurp(str(instr.regB), c.debug[pc], c.module, c.config))
of opcGorge:
let rb = instr.regB
if defined(nimsuggest) or c.config.cmd == cmdCheck:
discard "don't run staticExec for 'nim suggest'"
if compileTimeEffects(c.config) == cteSkip:
discard "don't run staticExec for 'nim check' and 'nim suggest'"
putStr(ra, "")
else:
when defined(nimcore):
Expand Down
51 changes: 50 additions & 1 deletion compiler/vmdeps.nim
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,67 @@
#

import ast, types, msgs, options, idents, lineinfos
from pathutils import AbsoluteFile
from pathutils import AbsoluteFile, AbsoluteDir, isEmpty

import std/[os, tables]
from std/strutils import split

when defined(nimPreviewSlimSystem):
import std/syncio

proc refuseCompileTimeEffect*(conf: ConfigRef; info: TLineInfo; op: string) =
## The error for a call that `compileTimeEffects` answers with `cteRestrict`.
globalError(conf, info, "'" & op & "' refused by --compileTime:restricted")

proc realPath(path: string): string =
## `path` made absolute with every symbolic link resolved, the way the OS
## resolves it. From the first part that does not exist on, the rest is
## appended as written: the OS cannot open such a path anyway.
## Note: on Windows `expandFilename` does not resolve links.
let parts = absolutePath(path).split({DirSep, AltSep})
result = parts[0] & DirSep # "/" or a drive like "C:\"
var exists = true
for i in 1..<parts.len:
let part = parts[i]
if part.len == 0 or part == ".": continue
let next = if part == "..": (if result.parentDir.len > 0: result.parentDir else: result)
else: result / part
if exists and (fileExists(next) or dirExists(next)):
result = expandFilename(next)
else:
exists = false
result = next

proc checkCompileTimeRead*(conf: ConfigRef; path: string; info: TLineInfo) =
## Under `--compileTime:restricted`, compile-time code reads only below the
## project directory, the `--path` and nimble package directories and Nim's
## `lib`; after symbolic links are resolved. Project configuration files are
## not read in this mode, so every root was given by the command line or the
## system or user configuration.
if compileTimeEffects(conf, skippedByCheck = false) != cteRestrict: return
var roots = @[conf.libpath]
if not conf.projectPath.isEmpty: roots.add conf.projectPath
roots.add conf.searchPaths
roots.add conf.lazyPaths
roots.add conf.nimblePaths
try:
let real = realPath(path)
for root in roots:
if dirExists(root.string) and real.isRelativeTo(realPath(root.string)):
return
except OSError:
globalError(conf, info, "read refused by --compileTime:restricted: '" & path &
"' cannot be resolved: " & getCurrentExceptionMsg())
globalError(conf, info, "read refused by --compileTime:restricted: '" & path &
"' is outside the project, --path, nimble package and Nim lib directories")

proc opSlurp*(file: string, info: TLineInfo, module: PSym; conf: ConfigRef): string =
try:
var filename = parentDir(toFullPath(conf, info)) / file
if not fileExists(filename):
filename = findFile(conf, file).string
if filename.len > 0: # else readFile fails with "cannot open file" below
checkCompileTimeRead(conf, filename, info)
result = readFile(filename)
# we produce a fake include statement for every slurped filename, so that
# the module dependencies are accurate:
Expand Down
Loading
Loading