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