1 /*
 2  * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
 3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 4  *
 5  * This code is free software; you can redistribute it and/or modify it
 6  * under the terms of the GNU General Public License version 2 only, as
 7  * published by the Free Software Foundation.
 8  *
 9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  */
23 
24 import java.lang.classfile.Attributes;
25 import java.lang.classfile.ClassFile;
26 import java.lang.classfile.CodeModel;
27 import java.lang.classfile.MethodModel;
28 import java.lang.classfile.attribute.CodeAttribute;
29 import java.lang.invoke.MethodHandles;
30 import jdk.incubator.code.Reflect;
31 import jdk.incubator.code.Op;
32 import jdk.incubator.code.bytecode.BytecodeGenerator;
33 import jdk.incubator.code.dialect.core.CoreOp;
34 import org.junit.jupiter.api.Assertions;
35 import org.junit.jupiter.api.Test;
36 
37 /*
38  * @test
39  * @modules jdk.incubator.code
40  * @enablePreview
41  * @run junit TestNestedTryCatch
42  */
43 public class TestNestedTryCatch {
44 
45     static void nop() {}
46 
47     @Reflect
48     static void f() {
49         try {
50             try {
51                 nop();
52             } catch (Exception _) {
53                 return;
54             }
55         } catch (Exception _) {
56             return;
57         }
58     }
59 
60     @Test
61     public void testInnerHandlerStartIsInsideRegion() throws Exception {
62         CoreOp.FuncOp f = Op.ofMethod(TestNestedTryCatch.class.getDeclaredMethod("f")).get();
63         byte[] classdata = BytecodeGenerator.generateClassData(MethodHandles.lookup(), f);
64         CodeModel code = ClassFile.of().parse(classdata).methods().getFirst().code().orElseThrow();
65         // inner exception handler starts with astore_0 and the astore_0 instruction must be inside of the outer try region
66         // the only non-intrusive test is to look for empty region as a sign of the exception region missplacement
67         code.exceptionHandlers().forEach(ec ->
68                 Assertions.assertNotSame(ec.tryStart(), ec.tryEnd(),
69                         () -> "Empty exception region in:\n" + code.toDebugString()));
70     }
71 }