001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 *  Unless required by applicable law or agreed to in writing, software
012 *  distributed under the License is distributed on an "AS IS" BASIS,
013 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 *  See the License for the specific language governing permissions and
015 *  limitations under the License.
016 *
017 */
018package org.apache.bcel.verifier.structurals;
019
020import java.util.HashMap;
021import java.util.HashSet;
022import java.util.Map;
023import java.util.Set;
024
025import org.apache.bcel.generic.CodeExceptionGen;
026import org.apache.bcel.generic.InstructionHandle;
027import org.apache.bcel.generic.MethodGen;
028
029/**
030 * This class allows easy access to ExceptionHandler objects.
031 */
032public class ExceptionHandlers {
033
034    /**
035     * Empty array.
036     */
037    private static final ExceptionHandler[] EMPTY_ARRAY = {};
038
039    /**
040     * The ExceptionHandler instances. Key: InstructionHandle objects, Values: HashSet<ExceptionHandler> instances.
041     */
042    private final Map<InstructionHandle, Set<ExceptionHandler>> exceptionHandlers;
043
044    /**
045     * Constructor. Creates a new ExceptionHandlers instance.
046     */
047    public ExceptionHandlers(final MethodGen mg) {
048        exceptionHandlers = new HashMap<>();
049        final CodeExceptionGen[] cegs = mg.getExceptionHandlers();
050        for (final CodeExceptionGen ceg : cegs) {
051            final ExceptionHandler eh = new ExceptionHandler(ceg.getCatchType(), ceg.getHandlerPC());
052            for (InstructionHandle ih = ceg.getStartPC(); ih != ceg.getEndPC().getNext(); ih = ih.getNext()) {
053                exceptionHandlers.computeIfAbsent(ih, k -> new HashSet<>()).add(eh);
054                exceptionHandlers.computeIfAbsent(ih, k -> new HashSet<>()).add(eh);
055            }
056        }
057    }
058
059    /**
060     * Returns all the ExceptionHandler instances representing exception handlers that protect the instruction ih.
061     */
062    public ExceptionHandler[] getExceptionHandlers(final InstructionHandle ih) {
063        final Set<ExceptionHandler> hsSet = exceptionHandlers.get(ih);
064        if (hsSet == null) {
065            return EMPTY_ARRAY;
066        }
067        return hsSet.toArray(ExceptionHandler.EMPTY_ARRAY);
068    }
069
070}