java_lang_System.cpp revision abf945fb9ce99d8c2769ac5b2691b2732fa59887
1/*
2 * Copyright (C) 2008 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#define LOG_TAG "System"
18
19#include "JNIHelp.h"
20#include "ScopedUtfChars.h"
21
22#include <stdlib.h>
23#include <string.h>
24
25static jstring System_getEnvByName(JNIEnv* env, jclass, jstring javaName) {
26    ScopedUtfChars name(env, javaName);
27    if (name.c_str() == NULL) {
28        return NULL;
29    }
30    return env->NewStringUTF(getenv(name.c_str()));
31}
32
33// Pointer to complete environment.
34extern char** environ;
35
36static jstring System_getEnvByIndex(JNIEnv* env, jclass, jint index) {
37    return env->NewStringUTF(environ[index]);
38}
39
40// Sets a field via JNI. Used for the standard streams, which are read-only otherwise.
41static void System_setFieldImpl(JNIEnv* env, jclass clazz,
42        jstring javaName, jstring javaSignature, jobject object) {
43    ScopedUtfChars name(env, javaName);
44    if (name.c_str() == NULL) {
45        return;
46    }
47    ScopedUtfChars signature(env, javaSignature);
48    if (signature.c_str() == NULL) {
49        return;
50    }
51    jfieldID fieldID = env->GetStaticFieldID(clazz, name.c_str(), signature.c_str());
52    env->SetStaticObjectField(clazz, fieldID, object);
53}
54
55static JNINativeMethod gMethods[] = {
56    { "getEnvByIndex", "(I)Ljava/lang/String;",                                     (void*) System_getEnvByIndex },
57    { "getEnvByName",  "(Ljava/lang/String;)Ljava/lang/String;",                    (void*) System_getEnvByName },
58    { "setFieldImpl",  "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Object;)V", (void*) System_setFieldImpl },
59};
60int register_java_lang_System(JNIEnv* env) {
61    return jniRegisterNativeMethods(env, "java/lang/System", gMethods, NELEM(gMethods));
62}
63