1/*
2 * Copyright (C) 2007 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 android.ddm;
18
19import org.apache.harmony.dalvik.ddmc.Chunk;
20import org.apache.harmony.dalvik.ddmc.ChunkHandler;
21import org.apache.harmony.dalvik.ddmc.DdmServer;
22import android.util.Log;
23import android.os.Debug;
24import android.os.UserHandle;
25import dalvik.system.VMRuntime;
26
27import java.nio.ByteBuffer;
28
29/**
30 * Handle "hello" messages and feature discovery.
31 */
32public class DdmHandleHello extends ChunkHandler {
33
34    public static final int CHUNK_HELO = type("HELO");
35    public static final int CHUNK_WAIT = type("WAIT");
36    public static final int CHUNK_FEAT = type("FEAT");
37
38    private static DdmHandleHello mInstance = new DdmHandleHello();
39
40    private static final String[] FRAMEWORK_FEATURES = new String[] {
41        "opengl-tracing",
42        "view-hierarchy",
43    };
44
45    /* singleton, do not instantiate */
46    private DdmHandleHello() {}
47
48    /**
49     * Register for the messages we're interested in.
50     */
51    public static void register() {
52        DdmServer.registerHandler(CHUNK_HELO, mInstance);
53        DdmServer.registerHandler(CHUNK_FEAT, mInstance);
54    }
55
56    /**
57     * Called when the DDM server connects.  The handler is allowed to
58     * send messages to the server.
59     */
60    public void connected() {
61        if (false)
62            Log.v("ddm-hello", "Connected!");
63
64        if (false) {
65            /* test spontaneous transmission */
66            byte[] data = new byte[] { 0, 1, 2, 3, 4, -4, -3, -2, -1, 127 };
67            Chunk testChunk =
68                new Chunk(ChunkHandler.type("TEST"), data, 1, data.length-2);
69            DdmServer.sendChunk(testChunk);
70        }
71    }
72
73    /**
74     * Called when the DDM server disconnects.  Can be used to disable
75     * periodic transmissions or clean up saved state.
76     */
77    public void disconnected() {
78        if (false)
79            Log.v("ddm-hello", "Disconnected!");
80    }
81
82    /**
83     * Handle a chunk of data.
84     */
85    public Chunk handleChunk(Chunk request) {
86        if (false)
87            Log.v("ddm-heap", "Handling " + name(request.type) + " chunk");
88        int type = request.type;
89
90        if (type == CHUNK_HELO) {
91            return handleHELO(request);
92        } else if (type == CHUNK_FEAT) {
93            return handleFEAT(request);
94        } else {
95            throw new RuntimeException("Unknown packet "
96                + ChunkHandler.name(type));
97        }
98    }
99
100    /*
101     * Handle introductory packet. This is called during JNI_CreateJavaVM
102     * before frameworks native methods are registered, so be careful not
103     * to call any APIs that depend on frameworks native code.
104     */
105    private Chunk handleHELO(Chunk request) {
106        if (false)
107            return createFailChunk(123, "This is a test");
108
109        /*
110         * Process the request.
111         */
112        ByteBuffer in = wrapChunk(request);
113
114        int serverProtoVers = in.getInt();
115        if (false)
116            Log.v("ddm-hello", "Server version is " + serverProtoVers);
117
118        /*
119         * Create a response.
120         */
121        String vmName = System.getProperty("java.vm.name", "?");
122        String vmVersion = System.getProperty("java.vm.version", "?");
123        String vmIdent = vmName + " v" + vmVersion;
124
125        //String appName = android.app.ActivityThread.currentPackageName();
126        //if (appName == null)
127        //    appName = "unknown";
128        String appName = DdmHandleAppName.getAppName();
129
130        VMRuntime vmRuntime = VMRuntime.getRuntime();
131        String instructionSetDescription =
132            vmRuntime.is64Bit() ? "64-bit" : "32-bit";
133        String vmInstructionSet = vmRuntime.vmInstructionSet();
134        if (vmInstructionSet != null && vmInstructionSet.length() > 0) {
135          instructionSetDescription += " (" + vmInstructionSet + ")";
136        }
137        String vmFlags = "CheckJNI="
138            + (vmRuntime.isCheckJniEnabled() ? "true" : "false");
139        boolean isNativeDebuggable = vmRuntime.isNativeDebuggable();
140
141        ByteBuffer out = ByteBuffer.allocate(28
142                            + vmIdent.length() * 2
143                            + appName.length() * 2
144                            + instructionSetDescription.length() * 2
145                            + vmFlags.length() * 2
146                            + 1);
147        out.order(ChunkHandler.CHUNK_ORDER);
148        out.putInt(DdmServer.CLIENT_PROTOCOL_VERSION);
149        out.putInt(android.os.Process.myPid());
150        out.putInt(vmIdent.length());
151        out.putInt(appName.length());
152        putString(out, vmIdent);
153        putString(out, appName);
154        out.putInt(UserHandle.myUserId());
155        out.putInt(instructionSetDescription.length());
156        putString(out, instructionSetDescription);
157        out.putInt(vmFlags.length());
158        putString(out, vmFlags);
159        out.put((byte)(isNativeDebuggable ? 1 : 0));
160
161        Chunk reply = new Chunk(CHUNK_HELO, out);
162
163        /*
164         * Take the opportunity to inform DDMS if we are waiting for a
165         * debugger to attach.
166         */
167        if (Debug.waitingForDebugger())
168            sendWAIT(0);
169
170        return reply;
171    }
172
173    /*
174     * Handle request for list of supported features.
175     */
176    private Chunk handleFEAT(Chunk request) {
177        // TODO: query the VM to ensure that support for these features
178        // is actually compiled in
179        final String[] vmFeatures = Debug.getVmFeatureList();
180
181        if (false)
182            Log.v("ddm-heap", "Got feature list request");
183
184        int size = 4 + 4 * (vmFeatures.length + FRAMEWORK_FEATURES.length);
185        for (int i = vmFeatures.length-1; i >= 0; i--)
186            size += vmFeatures[i].length() * 2;
187        for (int i = FRAMEWORK_FEATURES.length-1; i>= 0; i--)
188            size += FRAMEWORK_FEATURES[i].length() * 2;
189
190        ByteBuffer out = ByteBuffer.allocate(size);
191        out.order(ChunkHandler.CHUNK_ORDER);
192        out.putInt(vmFeatures.length + FRAMEWORK_FEATURES.length);
193        for (int i = vmFeatures.length-1; i >= 0; i--) {
194            out.putInt(vmFeatures[i].length());
195            putString(out, vmFeatures[i]);
196        }
197        for (int i = FRAMEWORK_FEATURES.length-1; i >= 0; i--) {
198            out.putInt(FRAMEWORK_FEATURES[i].length());
199            putString(out, FRAMEWORK_FEATURES[i]);
200        }
201
202        return new Chunk(CHUNK_FEAT, out);
203    }
204
205    /**
206     * Send up a WAIT chunk.  The only currently defined value for "reason"
207     * is zero, which means "waiting for a debugger".
208     */
209    public static void sendWAIT(int reason) {
210        byte[] data = new byte[] { (byte) reason };
211        Chunk waitChunk = new Chunk(CHUNK_WAIT, data, 0, 1);
212        DdmServer.sendChunk(waitChunk);
213    }
214}
215
216