1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * https://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19 package org.apache.bcel.verifier.structurals;
20
21 import java.util.HashMap;
22 import java.util.HashSet;
23 import java.util.Map;
24 import java.util.Set;
25
26 import org.apache.bcel.generic.CodeExceptionGen;
27 import org.apache.bcel.generic.InstructionHandle;
28 import org.apache.bcel.generic.MethodGen;
29
30 /**
31 * This class allows easy access to ExceptionHandler objects.
32 */
33 public class ExceptionHandlers {
34
35 /**
36 * Empty array.
37 */
38 private static final ExceptionHandler[] EMPTY_ARRAY = {};
39
40 /**
41 * The ExceptionHandler instances. Key: InstructionHandle objects, Values: HashSet<ExceptionHandler> instances.
42 */
43 private final Map<InstructionHandle, Set<ExceptionHandler>> exceptionHandlers;
44
45 /**
46 * Constructs a new ExceptionHandlers instance.
47 */
48 public ExceptionHandlers(final MethodGen mg) {
49 exceptionHandlers = new HashMap<>();
50 final CodeExceptionGen[] cegs = mg.getExceptionHandlers();
51 for (final CodeExceptionGen ceg : cegs) {
52 final ExceptionHandler eh = new ExceptionHandler(ceg.getCatchType(), ceg.getHandlerPC());
53 for (InstructionHandle ih = ceg.getStartPC(); ih != ceg.getEndPC().getNext(); ih = ih.getNext()) {
54 exceptionHandlers.computeIfAbsent(ih, k -> new HashSet<>()).add(eh);
55 }
56 }
57 }
58
59 /**
60 * Returns all the ExceptionHandler instances representing exception handlers that protect the instruction ih.
61 */
62 public ExceptionHandler[] getExceptionHandlers(final InstructionHandle ih) {
63 final Set<ExceptionHandler> hsSet = exceptionHandlers.get(ih);
64 if (hsSet == null) {
65 return EMPTY_ARRAY;
66 }
67 return hsSet.toArray(ExceptionHandler.EMPTY_ARRAY);
68 }
69
70 }