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
17package com.android.tools.layoutlib.create;
18
19import org.objectweb.asm.ClassVisitor;
20import org.objectweb.asm.FieldVisitor;
21import org.objectweb.asm.MethodVisitor;
22import org.objectweb.asm.Opcodes;
23
24import 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 */
32public 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     */
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
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
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 (CONSTRUCTOR.equals(name) || CLASS_INIT.equals(name)) {
102            // We don't currently support generating delegates for constructors.
103            throw new UnsupportedOperationException(
104                String.format(
105                    "Delegate doesn't support overriding constructor %1$s:%2$s(%3$s)",  //$NON-NLS-1$
106                    mClassName, name, desc));
107        }
108
109        if (isNative) {
110            // Remove native flag
111            access = access & ~Opcodes.ACC_NATIVE;
112            MethodVisitor mwDelegate = super.visitMethod(access, name, desc, signature, exceptions);
113
114            DelegateMethodAdapter a = new DelegateMethodAdapter(
115                    mLog, null, mwDelegate, mClassName, name, desc, isStaticMethod,
116                    mIsStaticInnerClass);
117
118            // A native has no code to visit, so we need to generate it directly.
119            a.generateDelegateCode();
120
121            return mwDelegate;
122        }
123
124        // Given a non-native SomeClass.MethodName(), we want to generate 2 methods:
125        // - A copy of the original method named SomeClass.MethodName_Original().
126        //   The content is the original method as-is from the reader.
127        // - A brand new implementation of SomeClass.MethodName() which calls to a
128        //   non-existing method named SomeClass_Delegate.MethodName().
129        //   The implementation of this 'delegate' method is done in layoutlib_bridge.
130
131        int accessDelegate = access;
132        access = access & ~Opcodes.ACC_PRIVATE;  // If private, make it package protected.
133
134        MethodVisitor mwOriginal = super.visitMethod(access, name + ORIGINAL_SUFFIX,
135                                                     desc, signature, exceptions);
136        MethodVisitor mwDelegate = super.visitMethod(accessDelegate, name,
137                                                     desc, signature, exceptions);
138
139        return new DelegateMethodAdapter(
140                mLog, mwOriginal, mwDelegate, mClassName, name, desc, isStaticMethod,
141                mIsStaticInnerClass);
142    }
143}
144