Search in sources :

Example 6 with ProxyLanguage

use of com.oracle.truffle.api.test.polyglot.ProxyLanguage in project graal by oracle.

the class RelativeSourceInspectDebugTest method testNonExistingSourcePath.

@Test
public void testNonExistingSourcePath() throws Exception {
    TestDebugNoContentLanguage language = new TestDebugNoContentLanguage("relative/path", true, true);
    ProxyLanguage.setDelegate(language);
    Source source = Source.create(ProxyLanguage.ID, "relative source1\nVarA");
    InspectorTester tester = InspectorTester.start(true, false, false);
    tester.sendMessage("{\"id\":1,\"method\":\"Runtime.enable\"}");
    assertEquals("{\"result\":{},\"id\":1}", tester.getMessages(true).trim());
    tester.sendMessage("{\"id\":2,\"method\":\"Debugger.enable\"}");
    assertEquals("{\"result\":{},\"id\":2}", tester.getMessages(true).trim());
    tester.sendMessage("{\"id\":3,\"method\":\"Runtime.runIfWaitingForDebugger\"}");
    String resolvedPath = new File("relative/path").toPath().toAbsolutePath().toUri().toString();
    // @formatter:off   The default formatting makes unnecessarily big indents and illogical line breaks
    // CheckStyle: stop line length check
    assertTrue(tester.compareReceivedMessages("{\"result\":{},\"id\":3}\n" + "{\"method\":\"Runtime.executionContextCreated\",\"params\":{\"context\":{\"origin\":\"\",\"name\":\"test\",\"id\":1}}}\n"));
    tester.eval(source);
    assertTrue(tester.compareReceivedMessages("{\"method\":\"Debugger.scriptParsed\",\"params\":{\"endLine\":3,\"scriptId\":\"0\",\"endColumn\":0,\"startColumn\":0,\"startLine\":0,\"length\":168,\"executionContextId\":1,\"url\":\"" + resolvedPath + "\",\"hash\":\"ea519706da04092af2f9afd9f84696c2fe44bc91\"}}\n"));
    // Suspend at the beginning of the script:
    assertTrue(tester.compareReceivedMessages("{\"method\":\"Debugger.paused\",\"params\":{\"reason\":\"other\",\"hitBreakpoints\":[]," + "\"callFrames\":[{\"callFrameId\":\"0\",\"functionName\":\"relative\"," + "\"scopeChain\":[{\"name\":\"relative\",\"type\":\"local\",\"object\":{\"description\":\"relative\",\"type\":\"object\",\"objectId\":\"1\"}}]," + "\"this\":null," + "\"functionLocation\":{\"scriptId\":\"0\",\"columnNumber\":0,\"lineNumber\":0}," + "\"location\":{\"scriptId\":\"0\",\"columnNumber\":0,\"lineNumber\":0}," + "\"url\":\"" + resolvedPath + "\"}]}}\n"));
    tester.sendMessage("{\"id\":1,\"method\":\"Debugger.resume\"}");
    assertTrue(tester.compareReceivedMessages("{\"result\":{},\"id\":1}\n" + "{\"method\":\"Debugger.resumed\"}\n"));
    // @formatter:on
    // CheckStyle: resume line length check
    language = null;
    // Reset the delegate so that we can GC the tested Engine
    ProxyLanguage.setDelegate(new ProxyLanguage());
    tester.finish();
}
Also used : TestDebugNoContentLanguage(com.oracle.truffle.api.debug.test.TestDebugNoContentLanguage) File(java.io.File) Source(org.graalvm.polyglot.Source) ProxyLanguage(com.oracle.truffle.api.test.polyglot.ProxyLanguage) Test(org.junit.Test)

Example 7 with ProxyLanguage

use of com.oracle.truffle.api.test.polyglot.ProxyLanguage in project graal by oracle.

the class ContextInterruptStandaloneTest method testCancelDuringHostSleep.

@Test
public void testCancelDuringHostSleep() throws ExecutionException, InterruptedException {
    CountDownLatch beforeSleep = new CountDownLatch(1);
    enterContext = false;
    setupEnv(Context.newBuilder(ProxyLanguage.ID).allowHostClassLookup((s) -> true).allowHostAccess(HostAccess.ALL), new ProxyLanguage() {

        @Override
        protected CallTarget parse(TruffleLanguage.ParsingRequest request) throws Exception {
            return new RootNode(languageInstance) {

                @Child
                InteropLibrary library = InteropLibrary.getFactory().createDispatched(1);

                @Override
                public Object execute(VirtualFrame frame) {
                    callHostSleep();
                    return 0;
                }

                @CompilerDirectives.TruffleBoundary
                private void callHostSleep() {
                    Object javaThread = LanguageContext.get(this).getEnv().lookupHostSymbol("java.lang.Thread");
                    beforeSleep.countDown();
                    try {
                        library.invokeMember(javaThread, "sleep", 10000);
                    } catch (UnsupportedMessageException | ArityException | UnknownIdentifierException | UnsupportedTypeException e) {
                        throw new AssertionError(e);
                    }
                }
            }.getCallTarget();
        }

        @Override
        protected boolean isThreadAccessAllowed(Thread thread, boolean singleThreaded) {
            return true;
        }
    });
    ExecutorService executorService = Executors.newFixedThreadPool(1);
    try {
        Future<?> future = executorService.submit(() -> {
            try {
                context.eval(ProxyLanguage.ID, "");
                Assert.fail();
            } catch (PolyglotException pe) {
                if (!pe.isCancelled() || pe.isInterrupted()) {
                    throw pe;
                }
            }
        });
        beforeSleep.await();
        context.close(true);
        future.get();
    } finally {
        executorService.shutdownNow();
        executorService.awaitTermination(100, TimeUnit.SECONDS);
    }
}
Also used : RootNode(com.oracle.truffle.api.nodes.RootNode) CallTarget(com.oracle.truffle.api.CallTarget) CountDownLatch(java.util.concurrent.CountDownLatch) PolyglotException(org.graalvm.polyglot.PolyglotException) ArityException(com.oracle.truffle.api.interop.ArityException) PolyglotException(org.graalvm.polyglot.PolyglotException) UnsupportedTypeException(com.oracle.truffle.api.interop.UnsupportedTypeException) TimeoutException(java.util.concurrent.TimeoutException) ArityException(com.oracle.truffle.api.interop.ArityException) UnknownIdentifierException(com.oracle.truffle.api.interop.UnknownIdentifierException) UnsupportedMessageException(com.oracle.truffle.api.interop.UnsupportedMessageException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ProxyLanguage(com.oracle.truffle.api.test.polyglot.ProxyLanguage) VirtualFrame(com.oracle.truffle.api.frame.VirtualFrame) UnsupportedMessageException(com.oracle.truffle.api.interop.UnsupportedMessageException) UnknownIdentifierException(com.oracle.truffle.api.interop.UnknownIdentifierException) InteropLibrary(com.oracle.truffle.api.interop.InteropLibrary) ExecutorService(java.util.concurrent.ExecutorService) UnsupportedTypeException(com.oracle.truffle.api.interop.UnsupportedTypeException) TruffleLanguage(com.oracle.truffle.api.TruffleLanguage) Test(org.junit.Test) AbstractPolyglotTest(com.oracle.truffle.api.test.polyglot.AbstractPolyglotTest)

Example 8 with ProxyLanguage

use of com.oracle.truffle.api.test.polyglot.ProxyLanguage in project graal by oracle.

the class ContextInterruptStandaloneTest method testCancelFromHostCall.

private void testCancelFromHostCall(boolean nestedContextEntered) {
    setupEnv(Context.newBuilder(ProxyLanguage.ID).allowHostClassLookup((s) -> true).allowHostAccess(HostAccess.ALL), new ProxyLanguage() {

        @Override
        protected CallTarget parse(TruffleLanguage.ParsingRequest request) throws Exception {
            return new RootNode(languageInstance) {

                @Child
                InteropLibrary library = InteropLibrary.getFactory().createDispatched(1);

                @Override
                public Object execute(VirtualFrame frame) {
                    Object thisTestClass = ProxyLanguage.LanguageContext.get(this).getEnv().lookupHostSymbol(ContextInterruptStandaloneTest.class.getName());
                    try {
                        library.invokeMember(thisTestClass, "callStaticContextCancel", nestedContextEntered);
                    } catch (UnsupportedMessageException | ArityException | UnknownIdentifierException | UnsupportedTypeException e) {
                        throw new AssertionError(e);
                    }
                    return 0;
                }
            }.getCallTarget();
        }
    });
    try {
        staticContext = context;
        context.eval(ProxyLanguage.ID, "");
        Assert.fail();
    } catch (PolyglotException pe) {
        if (!pe.isCancelled()) {
            throw pe;
        }
    } finally {
        staticContext = null;
    }
}
Also used : RootNode(com.oracle.truffle.api.nodes.RootNode) CallTarget(com.oracle.truffle.api.CallTarget) PolyglotException(org.graalvm.polyglot.PolyglotException) ArityException(com.oracle.truffle.api.interop.ArityException) PolyglotException(org.graalvm.polyglot.PolyglotException) UnsupportedTypeException(com.oracle.truffle.api.interop.UnsupportedTypeException) TimeoutException(java.util.concurrent.TimeoutException) ArityException(com.oracle.truffle.api.interop.ArityException) UnknownIdentifierException(com.oracle.truffle.api.interop.UnknownIdentifierException) UnsupportedMessageException(com.oracle.truffle.api.interop.UnsupportedMessageException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ProxyLanguage(com.oracle.truffle.api.test.polyglot.ProxyLanguage) VirtualFrame(com.oracle.truffle.api.frame.VirtualFrame) UnsupportedMessageException(com.oracle.truffle.api.interop.UnsupportedMessageException) UnknownIdentifierException(com.oracle.truffle.api.interop.UnknownIdentifierException) InteropLibrary(com.oracle.truffle.api.interop.InteropLibrary) UnsupportedTypeException(com.oracle.truffle.api.interop.UnsupportedTypeException) TruffleLanguage(com.oracle.truffle.api.TruffleLanguage)

Example 9 with ProxyLanguage

use of com.oracle.truffle.api.test.polyglot.ProxyLanguage in project graal by oracle.

the class ContextInterruptCloseCancelOrExitTest method testExitWhileClosing.

@Test
public void testExitWhileClosing() throws ExecutionException, InterruptedException, IOException {
    enterContext = false;
    AtomicReference<Runnable> runOnNaturalContextExit = new AtomicReference<>();
    ProxyLanguage proxyLanguage = new ProxyLanguage() {

        @Override
        protected boolean isThreadAccessAllowed(Thread thread, boolean singleThreaded) {
            return true;
        }

        @Override
        protected void exitContext(LanguageContext ctx, ExitMode exitMode, int exitCode) {
            if (exitMode == ExitMode.NATURAL && runOnNaturalContextExit.get() != null) {
                runOnNaturalContextExit.get().run();
            }
        }
    };
    setupEnv(Context.newBuilder().allowCreateThread(true), proxyLanguage);
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    try {
        CountDownLatch exitLatch = new CountDownLatch(1);
        Source source = Source.newBuilder(InstrumentationTestLanguage.ID, "ROOT(DEFINE(foo,CONSTANT(42),LOOP(infinity,STATEMENT)),SPAWN(foo))", "InfiniteLoop").build();
        attachListener(exitLatch::countDown, instrumentEnv);
        Future<?> future = executorService.submit(() -> {
            context.eval(source);
        });
        exitLatch.await();
        future.get();
        runOnNaturalContextExit.set(() -> {
            // No effect calling context exit during closing
            context.eval(InstrumentationTestLanguage.ID, "EXIT(1)");
            context.close(true);
        });
        context.close();
        assertContextState("CLOSED_CANCELLED");
    } finally {
        executorService.shutdownNow();
        executorService.awaitTermination(100, TimeUnit.SECONDS);
    }
}
Also used : ExecutorService(java.util.concurrent.ExecutorService) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) Source(org.graalvm.polyglot.Source) ProxyLanguage(com.oracle.truffle.api.test.polyglot.ProxyLanguage) Test(org.junit.Test) AbstractPolyglotTest(com.oracle.truffle.api.test.polyglot.AbstractPolyglotTest)

Example 10 with ProxyLanguage

use of com.oracle.truffle.api.test.polyglot.ProxyLanguage in project graal by oracle.

the class ContextInterruptCloseCancelOrExitTest method testInterruptPolyglotThreadWhileClosing.

@Test
public void testInterruptPolyglotThreadWhileClosing() throws ExecutionException, InterruptedException, IOException {
    enterContext = false;
    AtomicReference<Runnable> runOnNaturalContextExit = new AtomicReference<>();
    ProxyLanguage proxyLanguage = new ProxyLanguage() {

        @Override
        protected boolean isThreadAccessAllowed(Thread thread, boolean singleThreaded) {
            return true;
        }

        @Override
        protected void exitContext(LanguageContext ctx, ExitMode exitMode, int exitCode) {
            if (exitMode == ExitMode.NATURAL && runOnNaturalContextExit.get() != null) {
                runOnNaturalContextExit.get().run();
            }
        }
    };
    setupEnv(Context.newBuilder().allowCreateThread(true), proxyLanguage);
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    try {
        CountDownLatch interruptLatch = new CountDownLatch(1);
        Source source = Source.newBuilder(InstrumentationTestLanguage.ID, "ROOT(DEFINE(foo,CONSTANT(42),LOOP(infinity,STATEMENT)),SPAWN(foo))", "InfiniteLoop").build();
        attachListener(interruptLatch::countDown, instrumentEnv);
        Future<?> future = executorService.submit(() -> {
            context.eval(source);
        });
        interruptLatch.await();
        future.get();
        AtomicReference<Future<?>> interruptFutureReference = new AtomicReference<>();
        runOnNaturalContextExit.set(() -> {
            /*
                 * When inner context is closed we know that the parent context is being closed.
                 * Parent context is entered in the current thread, so we must interrupt in a
                 * different thread.
                 */
            Future<?> interruptFuture = executorService.submit(() -> {
                try {
                    context.interrupt(Duration.ofSeconds(5));
                } catch (TimeoutException te) {
                    throw new AssertionError(te);
                }
            });
            interruptFutureReference.set(interruptFuture);
            boolean interruptedExceptionSwallowed = false;
            try {
                /*
                     * The parent context is entered in the current thread, so the interrupt will
                     * try to interrupt it. Therefore, we have to ignore the InterruptedException in
                     * order for the close operation to be able to successfully continue. We cannot
                     * wait for the interrupt future here though, because it waits also for the
                     * current entered thread.
                     */
                interruptFuture.get();
            } catch (ExecutionException e) {
                throw new AssertionError(e);
            } catch (InterruptedException ie) {
                interruptedExceptionSwallowed = true;
            }
            Assert.assertTrue(interruptedExceptionSwallowed);
            Assert.assertFalse(interruptFuture.isDone());
        });
        context.close();
        assertContextState("CLOSED");
        Assert.assertNotNull(interruptFutureReference.get());
        interruptFutureReference.get().get();
    } finally {
        executorService.shutdownNow();
        executorService.awaitTermination(100, TimeUnit.SECONDS);
    }
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) Source(org.graalvm.polyglot.Source) ProxyLanguage(com.oracle.truffle.api.test.polyglot.ProxyLanguage) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.Test) AbstractPolyglotTest(com.oracle.truffle.api.test.polyglot.AbstractPolyglotTest)

Aggregations

ProxyLanguage (com.oracle.truffle.api.test.polyglot.ProxyLanguage)64 Test (org.junit.Test)47 CallTarget (com.oracle.truffle.api.CallTarget)32 AbstractPolyglotTest (com.oracle.truffle.api.test.polyglot.AbstractPolyglotTest)28 PolyglotException (org.graalvm.polyglot.PolyglotException)26 RootNode (com.oracle.truffle.api.nodes.RootNode)21 Source (org.graalvm.polyglot.Source)21 VirtualFrame (com.oracle.truffle.api.frame.VirtualFrame)20 UnsupportedMessageException (com.oracle.truffle.api.interop.UnsupportedMessageException)20 Context (org.graalvm.polyglot.Context)17 TruffleContext (com.oracle.truffle.api.TruffleContext)16 Before (org.junit.Before)16 TruffleLanguage (com.oracle.truffle.api.TruffleLanguage)14 TruffleObject (com.oracle.truffle.api.interop.TruffleObject)13 CountDownLatch (java.util.concurrent.CountDownLatch)11 InteropLibrary (com.oracle.truffle.api.interop.InteropLibrary)10 ArrayList (java.util.ArrayList)10 ExecutionException (java.util.concurrent.ExecutionException)10 TruffleBoundary (com.oracle.truffle.api.CompilerDirectives.TruffleBoundary)9 ExecutorService (java.util.concurrent.ExecutorService)9