1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.tools.layoutlib.create;
18 
19 import org.objectweb.asm.ClassVisitor;
20 import org.objectweb.asm.FieldVisitor;
21 import org.objectweb.asm.MethodVisitor;
22 import org.objectweb.asm.Opcodes;
23 
24 import java.util.Set;
25 
26 /**
27  * A {@link DelegateClassAdapter} can transform some methods from a class into
28  * delegates that defer the call to an associated delegate class.
29  * <p/>
30  * This is used to override specific methods and or all native methods in classes.
31  */
32 public class DelegateClassAdapter extends ClassVisitor {
33 
34     /** Suffix added to original methods. */
35     private static final String ORIGINAL_SUFFIX = "_Original";
36     private static final String CONSTRUCTOR = "<init>";
37     private static final String CLASS_INIT = "<clinit>";
38 
39     public static final String ALL_NATIVES = "<<all_natives>>";
40 
41     private final String mClassName;
42     private final Set<String> mDelegateMethods;
43     private final Log mLog;
44     private boolean mIsStaticInnerClass;
45 
46     /**
47      * Creates a new {@link DelegateClassAdapter} that can transform some methods
48      * from a class into delegates that defer the call to an associated delegate class.
49      * <p/>
50      * This is used to override specific methods and or all native methods in classes.
51      *
52      * @param log The logger object. Must not be null.
53      * @param cv the class visitor to which this adapter must delegate calls.
54      * @param className The internal class name of the class to visit,
55      *          e.g. <code>com/android/SomeClass$InnerClass</code>.
56      * @param delegateMethods The set of method names to modify and/or the
57      *          special constant {@link #ALL_NATIVES} to convert all native methods.
58      */
DelegateClassAdapter(Log log, ClassVisitor cv, String className, Set<String> delegateMethods)59     public DelegateClassAdapter(Log log,
60             ClassVisitor cv,
61             String className,
62             Set<String> delegateMethods) {
63         super(Main.ASM_VERSION, cv);
64         mLog = log;
65         mClassName = className;
66         mDelegateMethods = delegateMethods;
67         // If this is an inner class, by default, we assume it's static. If it's not we will detect
68         // by looking at the fields (see visitField)
69         mIsStaticInnerClass = className.contains("$");
70     }
71 
72     //----------------------------------
73     // Methods from the ClassAdapter
74 
75     @Override
visitField(int access, String name, String desc, String signature, Object value)76     public FieldVisitor visitField(int access, String name, String desc, String signature,
77             Object value) {
78         if (mIsStaticInnerClass && "this$0".equals(name)) {
79             // Having a "this$0" field, proves that this class is not a static inner class.
80             mIsStaticInnerClass = false;
81         }
82 
83         return super.visitField(access, name, desc, signature, value);
84     }
85 
86     @Override
visitMethod(int access, String name, String desc, String signature, String[] exceptions)87     public MethodVisitor visitMethod(int access, String name, String desc,
88             String signature, String[] exceptions) {
89 
90         boolean isStaticMethod = (access & Opcodes.ACC_STATIC) != 0;
91         boolean isNative = (access & Opcodes.ACC_NATIVE) != 0;
92 
93         boolean useDelegate = (isNative && mDelegateMethods.contains(ALL_NATIVES)) ||
94                               mDelegateMethods.contains(name);
95 
96         if (!useDelegate) {
97             // Not creating a delegate for this method, pass it as-is from the reader to the writer.
98             return super.visitMethod(access, name, desc, signature, exceptions);
99         }
100 
101         if (CLASS_INIT.equals(name)) {
102             access = access & ~Opcodes.ACC_PRIVATE;  // make the replacement method package protected.
103 
104             // writer for moving the original code to a 'SomeClass.staticInit_Original' method
105             MethodVisitor renamedMethodWriter = super.visitMethod(access,
106                     "staticInit" + ORIGINAL_SUFFIX,
107                     desc, signature, exceptions);
108             // writer for writing the SomeClass.clinit method with a single call to
109             // SomeClass_Delegate.staticInit
110             MethodVisitor originalMethodWriter = super.visitMethod(access, name,
111                     desc, signature, exceptions);
112 
113             return new StaticInitMethodAdapter(mLog, renamedMethodWriter,
114                     originalMethodWriter, mClassName);
115 
116         }
117 
118         if (isNative) {
119             // Remove native flag
120             access = access & ~Opcodes.ACC_NATIVE;
121             MethodVisitor mwDelegate = super.visitMethod(access, name, desc, signature, exceptions);
122 
123             DelegateMethodAdapter a = new DelegateMethodAdapter(
124                     mLog, null, mwDelegate, mClassName, name, desc, isStaticMethod,
125                     mIsStaticInnerClass);
126 
127             // A native has no code to visit, so we need to generate it directly.
128             a.generateDelegateCode();
129 
130             return mwDelegate;
131         }
132 
133         if (CONSTRUCTOR.equals(name)) {
134             MethodVisitor mwOriginal = super.visitMethod(access, name,
135                     desc, signature, exceptions);
136             return new AfterConstructorMethodAdapter(mLog, mwOriginal, mClassName);
137         }
138         else {
139             // Given a non-native SomeClass.MethodName(), we want to generate 2 methods:
140             // - A copy of the original method named SomeClass.MethodName_Original().
141             //   The content is the original method as-is from the reader.
142             // - A brand new implementation of SomeClass.MethodName() which calls to a
143             //   non-existing method named SomeClass_Delegate.MethodName().
144             //   The implementation of this 'delegate' method is done in layoutlib_bridge.
145 
146             int accessDelegate = access;
147             access = access & ~Opcodes.ACC_PRIVATE;  // If private, make it package protected.
148 
149             MethodVisitor mwOriginal = super.visitMethod(access, name + ORIGINAL_SUFFIX,
150                     desc, signature, exceptions);
151             MethodVisitor mwDelegate = super.visitMethod(accessDelegate, name,
152                     desc, signature, exceptions);
153 
154             return new DelegateMethodAdapter(
155                     mLog, mwOriginal, mwDelegate, mClassName, name, desc, isStaticMethod,
156                     mIsStaticInnerClass);
157         }
158     }
159 }
160