android_util_EventLog.cpp revision 54b6cfa9a9e5b861a9930af873580d6dc20f773c
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
17#include <fcntl.h>
18
19#include "JNIHelp.h"
20#include "android_runtime/AndroidRuntime.h"
21#include "jni.h"
22#include "utils/logger.h"
23
24#define END_DELIMITER '\n'
25#define INT_BUFFER_SIZE (sizeof(jbyte)+sizeof(jint)+sizeof(END_DELIMITER))
26#define LONG_BUFFER_SIZE (sizeof(jbyte)+sizeof(jlong)+sizeof(END_DELIMITER))
27#define INITAL_BUFFER_CAPACITY 256
28
29#define MAX(a,b) ((a>b)?a:b)
30
31namespace android {
32
33static jclass gCollectionClass;
34static jmethodID gCollectionAddID;
35
36static jclass gEventClass;
37static jmethodID gEventInitID;
38
39static jclass gIntegerClass;
40static jfieldID gIntegerValueID;
41
42static jclass gListClass;
43static jfieldID gListItemsID;
44
45static jclass gLongClass;
46static jfieldID gLongValueID;
47
48static jclass gStringClass;
49
50struct ByteBuf {
51    size_t len;
52    size_t capacity;
53    uint8_t* buf;
54
55    ByteBuf(size_t initSize) {
56        buf = (uint8_t*)malloc(initSize);
57        len = 0;
58        capacity = initSize;
59    }
60
61    ~ByteBuf() {
62        free(buf);
63    }
64
65    bool ensureExtraCapacity(size_t extra) {
66        size_t spaceNeeded = len + extra;
67        if (spaceNeeded > capacity) {
68            size_t newCapacity = MAX(spaceNeeded, 2 * capacity);
69            void* newBuf = realloc(buf, newCapacity);
70            if (newBuf == NULL) {
71                return false;
72            }
73            capacity = newCapacity;
74            buf = (uint8_t*)newBuf;
75            return true;
76        } else {
77            return true;
78        }
79    }
80
81    void putIntEvent(jint value) {
82        bool succeeded = ensureExtraCapacity(INT_BUFFER_SIZE);
83        buf[len++] = EVENT_TYPE_INT;
84        memcpy(buf+len, &value, sizeof(jint));
85        len += sizeof(jint);
86    }
87
88    void putByte(uint8_t value) {
89        bool succeeded = ensureExtraCapacity(sizeof(uint8_t));
90        buf[len++] = value;
91    }
92
93    void putLongEvent(jlong value) {
94        bool succeeded = ensureExtraCapacity(LONG_BUFFER_SIZE);
95        buf[len++] = EVENT_TYPE_LONG;
96        memcpy(buf+len, &value, sizeof(jlong));
97        len += sizeof(jlong);
98    }
99
100
101    void putStringEvent(JNIEnv* env, jstring value) {
102        const char* strValue = env->GetStringUTFChars(value, NULL);
103        uint32_t strLen = strlen(strValue); //env->GetStringUTFLength(value);
104        bool succeeded = ensureExtraCapacity(1 + sizeof(uint32_t) + strLen);
105        buf[len++] = EVENT_TYPE_STRING;
106        memcpy(buf+len, &strLen, sizeof(uint32_t));
107        len += sizeof(uint32_t);
108        memcpy(buf+len, strValue, strLen);
109        env->ReleaseStringUTFChars(value, strValue);
110        len += strLen;
111    }
112
113    void putList(JNIEnv* env, jobject list) {
114        jobjectArray items = (jobjectArray) env->GetObjectField(list, gListItemsID);
115        if (items == NULL) {
116            jniThrowException(env, "java/lang/NullPointerException", NULL);
117            return;
118        }
119
120        jsize numItems = env->GetArrayLength(items);
121        putByte(EVENT_TYPE_LIST);
122        putByte(numItems);
123        // We'd like to call GetPrimitveArrayCritical() but that might
124        // not be safe since we're going to be doing some I/O
125        for (int i = 0; i < numItems; i++) {
126            jobject item = env->GetObjectArrayElement(items, i);
127            if (env->IsInstanceOf(item, gIntegerClass)) {
128                jint intVal = env->GetIntField(item, gIntegerValueID);
129                putIntEvent(intVal);
130            } else if (env->IsInstanceOf(item, gLongClass)) {
131                jlong longVal = env->GetLongField(item, gLongValueID);
132                putLongEvent(longVal);
133            } else if (env->IsInstanceOf(item, gStringClass)) {
134                putStringEvent(env, (jstring)item);
135            } else if (env->IsInstanceOf(item, gListClass)) {
136                putList(env, item);
137            } else {
138                jniThrowException(
139                        env,
140                        "java/lang/IllegalArgumentException",
141                        "Attempt to log an illegal item type.");
142                return;
143            }
144            env->DeleteLocalRef(item);
145        }
146
147        env->DeleteLocalRef(items);
148    }
149};
150
151/*
152 * In class android.util.EventLog:
153 *  static native int writeEvent(int tag, int value)
154 */
155static jint android_util_EventLog_writeEvent_Integer(JNIEnv* env, jobject clazz,
156                                                     jint tag, jint value)
157{
158    return android_btWriteLog(tag, EVENT_TYPE_INT, &value, sizeof(value));
159}
160
161/*
162 * In class android.util.EventLog:
163 *  static native int writeEvent(long tag, long value)
164 */
165static jint android_util_EventLog_writeEvent_Long(JNIEnv* env, jobject clazz,
166                                                  jint tag, jlong value)
167{
168    return android_btWriteLog(tag, EVENT_TYPE_LONG, &value, sizeof(value));
169}
170
171/*
172 * In class android.util.EventLog:
173 *  static native int writeEvent(long tag, List value)
174 */
175static jint android_util_EventLog_writeEvent_List(JNIEnv* env, jobject clazz,
176                                                  jint tag, jobject value) {
177    if (value == NULL) {
178        jclass clazz = env->FindClass("java/lang/IllegalArgumentException");
179        env->ThrowNew(clazz, "writeEvent needs a value.");
180        return -1;
181    }
182    ByteBuf byteBuf(INITAL_BUFFER_CAPACITY);
183    byteBuf.putList(env, value);
184    byteBuf.putByte((uint8_t)END_DELIMITER);
185    int numBytesPut = byteBuf.len;
186    int bytesWritten = android_bWriteLog(tag, byteBuf.buf, numBytesPut);
187    return bytesWritten;
188}
189
190/*
191 * In class android.util.EventLog:
192 *  static native int writeEvent(int tag, String value)
193 */
194static jint android_util_EventLog_writeEvent_String(JNIEnv* env, jobject clazz,
195                                                    jint tag, jstring value) {
196    if (value == NULL) {
197        jclass clazz = env->FindClass("java/lang/IllegalArgumentException");
198        env->ThrowNew(clazz, "logEvent needs a value.");
199        return -1;
200    }
201
202    ByteBuf byteBuf(INITAL_BUFFER_CAPACITY);
203    byteBuf.putStringEvent(env, value);
204    byteBuf.putByte((uint8_t)END_DELIMITER);
205    int numBytesPut = byteBuf.len;
206    int bytesWritten = android_bWriteLog(tag, byteBuf.buf, numBytesPut);
207    return bytesWritten;
208}
209
210/*
211 * In class android.util.EventLog:
212 *  static native void readEvents(int[] tags, Collection<Event> output)
213 */
214static void android_util_EventLog_readEvents(JNIEnv* env, jobject clazz,
215                                             jintArray tags,
216                                             jobject out) {
217    if (tags == NULL || out == NULL) {
218        jniThrowException(env, "java/lang/NullPointerException", NULL);
219        return;
220    }
221
222    int fd = open("/dev/" LOGGER_LOG_EVENTS, O_RDONLY | O_NONBLOCK);
223    if (fd < 0) {
224        jniThrowIOException(env, errno);
225        return;
226    }
227
228    jsize tagLength = env->GetArrayLength(tags);
229    jint *tagValues = env->GetIntArrayElements(tags, NULL);
230
231    uint8_t buf[LOGGER_ENTRY_MAX_LEN];
232    for (;;) {
233        int len = read(fd, buf, sizeof(buf));
234        if (len == 0 || (len < 0 && errno == EAGAIN)) {
235            break;
236        } else if (len < 0) {
237            // This calls env->ThrowNew(), which doesn't throw an exception
238            // now, but sets a flag to trigger an exception after we return.
239            jniThrowIOException(env, errno);
240            break;
241        } else if ((size_t) len < sizeof(logger_entry) + sizeof(int32_t)) {
242            jniThrowException(env, "java/io/IOException", "Event too short");
243            break;
244        }
245
246        logger_entry* entry = (logger_entry*) buf;
247        int32_t tag = * (int32_t*) (buf + sizeof(*entry));
248
249        int found = 0;
250        for (int i = 0; !found && i < tagLength; ++i) {
251            found = (tag == tagValues[i]);
252        }
253
254        if (found) {
255            jsize len = sizeof(*entry) + entry->len;
256            jbyteArray array = env->NewByteArray(len);
257            if (array == NULL) break;
258
259            jbyte *bytes = env->GetByteArrayElements(array, NULL);
260            memcpy(bytes, buf, len);
261            env->ReleaseByteArrayElements(array, bytes, 0);
262
263            jobject event = env->NewObject(gEventClass, gEventInitID, array);
264            if (event == NULL) break;
265
266            env->CallBooleanMethod(out, gCollectionAddID, event);
267            env->DeleteLocalRef(event);
268            env->DeleteLocalRef(array);
269        }
270    }
271
272    close(fd);
273    env->ReleaseIntArrayElements(tags, tagValues, 0);
274}
275
276
277/*
278 * JNI registration.
279 */
280static JNINativeMethod gRegisterMethods[] = {
281    /* name, signature, funcPtr */
282    { "writeEvent", "(II)I", (void*) android_util_EventLog_writeEvent_Integer },
283    { "writeEvent", "(IJ)I", (void*) android_util_EventLog_writeEvent_Long },
284    { "writeEvent",
285      "(ILjava/lang/String;)I",
286      (void*) android_util_EventLog_writeEvent_String
287    },
288    { "writeEvent",
289      "(ILandroid/util/EventLog$List;)I",
290      (void*) android_util_EventLog_writeEvent_List
291    },
292    { "readEvents",
293      "([ILjava/util/Collection;)V",
294      (void*) android_util_EventLog_readEvents
295    }
296};
297
298static struct { const char *name; jclass *clazz; } gClasses[] = {
299    { "android/util/EventLog$Event", &gEventClass },
300    { "android/util/EventLog$List", &gListClass },
301    { "java/lang/Integer", &gIntegerClass },
302    { "java/lang/Long", &gLongClass },
303    { "java/lang/String", &gStringClass },
304    { "java/util/Collection", &gCollectionClass },
305};
306
307static struct { jclass *c; const char *name, *ft; jfieldID *id; } gFields[] = {
308    { &gIntegerClass, "value", "I", &gIntegerValueID },
309    { &gListClass, "mItems", "[Ljava/lang/Object;", &gListItemsID },
310    { &gLongClass, "value", "J", &gLongValueID },
311};
312
313static struct { jclass *c; const char *name, *mt; jmethodID *id; } gMethods[] = {
314    { &gEventClass, "<init>", "([B)V", &gEventInitID },
315    { &gCollectionClass, "add", "(Ljava/lang/Object;)Z", &gCollectionAddID },
316};
317
318int register_android_util_EventLog(JNIEnv* env) {
319    for (int i = 0; i < NELEM(gClasses); ++i) {
320        jclass clazz = env->FindClass(gClasses[i].name);
321        if (clazz == NULL) {
322            LOGE("Can't find class: %s\n", gClasses[i].name);
323            return -1;
324        }
325        *gClasses[i].clazz = (jclass) env->NewGlobalRef(clazz);
326    }
327
328    for (int i = 0; i < NELEM(gFields); ++i) {
329        *gFields[i].id = env->GetFieldID(
330                *gFields[i].c, gFields[i].name, gFields[i].ft);
331        if (*gFields[i].id == NULL) {
332            LOGE("Can't find field: %s\n", gFields[i].name);
333            return -1;
334        }
335    }
336
337    for (int i = 0; i < NELEM(gMethods); ++i) {
338        *gMethods[i].id = env->GetMethodID(
339                *gMethods[i].c, gMethods[i].name, gMethods[i].mt);
340        if (*gMethods[i].id == NULL) {
341            LOGE("Can't find method: %s\n", gMethods[i].name);
342            return -1;
343        }
344    }
345
346    return AndroidRuntime::registerNativeMethods(
347            env,
348            "android/util/EventLog",
349            gRegisterMethods, NELEM(gRegisterMethods));
350}
351
352}; // namespace android
353
354