1 /*
2 * Copyright (C) 2011 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 "ExecStrings"
18
19 #include "ExecStrings.h"
20
21 #include <stdlib.h>
22
23 #include <log/log.h>
24
25 #include <nativehelper/ScopedLocalRef.h>
26
ExecStrings(JNIEnv * env,jobjectArray java_string_array)27 ExecStrings::ExecStrings(JNIEnv* env, jobjectArray java_string_array)
28 : env_(env), java_array_(java_string_array), array_(NULL) {
29 if (java_array_ == NULL) {
30 return;
31 }
32
33 jsize length = env_->GetArrayLength(java_array_);
34 array_ = new char*[length + 1];
35 array_[length] = NULL;
36 for (jsize i = 0; i < length; ++i) {
37 ScopedLocalRef<jstring> java_string(env_, reinterpret_cast<jstring>(env_->GetObjectArrayElement(java_array_, i)));
38 // We need to pass these strings to const-unfriendly code.
39 char* string = const_cast<char*>(env_->GetStringUTFChars(java_string.get(), NULL));
40 array_[i] = string;
41 }
42 }
43
~ExecStrings()44 ExecStrings::~ExecStrings() {
45 if (array_ == NULL) {
46 return;
47 }
48
49 // Temporarily clear any pending exception so we can clean up.
50 jthrowable pending_exception = env_->ExceptionOccurred();
51 if (pending_exception != NULL) {
52 env_->ExceptionClear();
53 }
54
55 jsize length = env_->GetArrayLength(java_array_);
56 for (jsize i = 0; i < length; ++i) {
57 ScopedLocalRef<jstring> java_string(env_, reinterpret_cast<jstring>(env_->GetObjectArrayElement(java_array_, i)));
58 env_->ReleaseStringUTFChars(java_string.get(), array_[i]);
59 }
60 delete[] array_;
61
62 // Re-throw any pending exception.
63 if (pending_exception != NULL) {
64 if (env_->Throw(pending_exception) < 0) {
65 ALOGE("Error rethrowing exception!");
66 }
67 }
68 }
69
get()70 char** ExecStrings::get() {
71 return array_;
72 }
73