1 // Copyright 2016 The Bazel Authors. All rights reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 package com.google.devtools.build.android.desugar; 15 16 import java.io.IOException; 17 import java.io.InputStream; 18 import javax.annotation.Nullable; 19 import org.objectweb.asm.ClassReader; 20 21 class ClassReaderFactory { 22 private final IndexedInputs indexedInputs; 23 private final CoreLibraryRewriter rewriter; 24 25 public ClassReaderFactory(IndexedInputs indexedInputs, CoreLibraryRewriter rewriter) { 26 this.rewriter = rewriter; 27 this.indexedInputs = indexedInputs; 28 } 29 30 /** 31 * Returns a reader for the given/internal/Class$Name if the class is defined in the wrapped input 32 * and {@code null} otherwise. For simplicity this method turns checked into runtime exceptions 33 * under the assumption that all classes have already been read once when this method is called. 34 */ 35 @Nullable 36 public ClassReader readIfKnown(String internalClassName) { 37 String filename = rewriter.unprefix(internalClassName) + ".class"; 38 InputFileProvider inputFileProvider = indexedInputs.getInputFileProvider(filename); 39 40 if (inputFileProvider != null) { 41 try (InputStream bytecode = inputFileProvider.getInputStream(filename)) { 42 // ClassReader doesn't take ownership and instead eagerly reads the stream's contents 43 return rewriter.reader(bytecode); 44 } catch (IOException e) { 45 // We should've already read through all files in the Jar once at this point, so we don't 46 // expect failures reading some files a second time. 47 throw new IllegalStateException("Couldn't load " + internalClassName, e); 48 } 49 } 50 51 return null; 52 } 53 54 /** 55 * Returns {@code true} if the given given/internal/Class$Name is defined in the wrapped input. 56 */ 57 public boolean isKnown(String internalClassName) { 58 String filename = rewriter.unprefix(internalClassName) + ".class"; 59 return indexedInputs.getInputFileProvider(filename) != null; 60 } 61 } 62