1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements.  See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License.  You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  */
18 package org.apache.bcel.verifier.structurals;
19 
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  * @version $Id$
34  */
35 public class ExceptionHandlers{
36     /**
37      * The ExceptionHandler instances.
38      * Key: InstructionHandle objects, Values: HashSet<ExceptionHandler> instances.
39      */
40     private final Map<InstructionHandle, Set<ExceptionHandler>> exceptionhandlers;
41 
42     /**
43      * Constructor. Creates a new ExceptionHandlers instance.
44      */
ExceptionHandlers(final MethodGen mg)45     public ExceptionHandlers(final MethodGen mg) {
46         exceptionhandlers = new HashMap<>();
47         final CodeExceptionGen[] cegs = mg.getExceptionHandlers();
48         for (final CodeExceptionGen ceg : cegs) {
49             final ExceptionHandler eh = new ExceptionHandler(ceg.getCatchType(), ceg.getHandlerPC());
50             for (InstructionHandle ih=ceg.getStartPC(); ih != ceg.getEndPC().getNext(); ih=ih.getNext()) {
51                 Set<ExceptionHandler> hs;
52                 hs = exceptionhandlers.get(ih);
53                 if (hs == null) {
54                     hs = new HashSet<>();
55                     exceptionhandlers.put(ih, hs);
56                 }
57                 hs.add(eh);
58             }
59         }
60     }
61 
62     /**
63      * Returns all the ExceptionHandler instances representing exception
64      * handlers that protect the instruction ih.
65      */
getExceptionHandlers(final InstructionHandle ih)66     public ExceptionHandler[] getExceptionHandlers(final InstructionHandle ih) {
67         final Set<ExceptionHandler> hsSet = exceptionhandlers.get(ih);
68         if (hsSet == null) {
69             return new ExceptionHandler[0];
70         }
71         return hsSet.toArray(new ExceptionHandler[hsSet.size()]);
72     }
73 
74 }
75