Skip to content

Commit 7146996

Browse files
committed
Fix SandboxSecurityManager when multithreaded
1 parent e149118 commit 7146996

File tree

1 file changed

+28
-5
lines changed

1 file changed

+28
-5
lines changed

compiler/src/dotty/tools/dotc/util/Sandbox.scala

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,8 @@ object Sandbox {
1212
final val timeout = 3000 // TODO add a flag to allow custom timeouts
1313

1414
def runInSecuredThread[T](thunk: => T): T = {
15-
// Implementation assumes single threaded
16-
val oldSecurityManager = System.getSecurityManager
1715
try {
18-
val securityManager = new SandboxSecurityManager
19-
System.setSecurityManager(securityManager)
16+
val securityManager: SandboxSecurityManager = SandboxSecurityManager.init()
2017
class SandboxThread extends Thread {
2118
var result: scala.util.Try[T] =
2219
scala.util.Failure(new Exception("Sandbox failed with a fatal error"))
@@ -35,7 +32,33 @@ object Sandbox {
3532
throw new InvocationTargetException(new QuoteError(s"Failed to evaluate inlined quote. Caused by timeout ($timeout ms)."))
3633
} else thread.result.fold[T](throw _, identity)
3734
} finally {
38-
System.setSecurityManager(oldSecurityManager)
35+
SandboxSecurityManager.stop()
36+
}
37+
}
38+
39+
object SandboxSecurityManager {
40+
@volatile private[this] var running: Int = 0
41+
42+
private[Sandbox] def init(): SandboxSecurityManager = synchronized {
43+
running += 1
44+
System.getSecurityManager match {
45+
case securityManager: SandboxSecurityManager =>
46+
assert(running > 1)
47+
securityManager
48+
case securityManager =>
49+
assert(running == 1)
50+
assert(securityManager == null)
51+
val sandboxSecurityManager = new SandboxSecurityManager
52+
System.setSecurityManager(sandboxSecurityManager)
53+
sandboxSecurityManager
54+
}
55+
}
56+
57+
private[Sandbox] def stop(): Unit = synchronized {
58+
running -= 1
59+
assert(System.getSecurityManager.isInstanceOf[SandboxSecurityManager])
60+
if (running == 0)
61+
System.setSecurityManager(null)
3962
}
4063
}
4164

0 commit comments

Comments
 (0)