-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_java_proxy.cpp
More file actions
462 lines (376 loc) · 15.3 KB
/
Copy pathgenerate_java_proxy.cpp
File metadata and controls
462 lines (376 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
// Copyright (c) 2026 Samsung Electronics Co., Ltd. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
#include "cc_service.h"
#include "generate_java_proxy.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <android-base/stringprintf.h>
#include "aidl_to_common.h"
#include "aidl_to_java.h"
#include "code_writer.h"
#include "logging.h"
#include "os.h"
using android::base::StringPrintf;
namespace android {
namespace aidl {
namespace java {
static string TAG = "GenerateProxyService";
static string INTERNAL_PACKAGE = "com.islet.binder.service";
static string GetProxyServiceFilePath(const string path, const Options& options, const string class_name) {
string result = path;
// add the filename
result += class_name;
if (options.TargetLanguage() == Options::Language::JAVA) {
result += ".java";
} else if (options.IsCppOutput()) {
result += ".cpp";
} else if (options.TargetLanguage() == Options::Language::RUST) {
result += ".rs";
} else {
AIDL_FATAL("Unknown target language");
return "";
}
AIDL_WARN(TAG)
<< "GetProxyServiceFilePath result: " << result;
return result;
}
void GenerateImports(CodeWriter& out, const AidlDefinedType& defined_type) {
const AidlInterface* iface = defined_type.AsInterface();
const string pkg = defined_type.GetPackage();
out << R"(
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import java.lang.IllegalStateException;
import com.islet.binder.service.Reader;
import com.islet.binder.service.Logger;
import com.islet.binder.service.VmManager;
import com.islet.binder.service.IRealmService;
)";
out << "import "+ pkg + "." + iface->GetName() + ";\n\n";
}
static shared_ptr<ClassElement> GenerateMemberVariables(const string class_name, const string iface_name) {
string member_variables = "private static final String TAG = \"" + class_name + "\";";
member_variables += R"(
private Logger mLogger;
private VmManager mVmManager;
)";
member_variables += "private " + iface_name + " mTargetService = null;\n";
return std::make_shared<LiteralClassElement>(member_variables);
}
static shared_ptr<ClassElement> GenerateOnCreateMethod() {
string method = R"(
@Override
public void onCreate() {
mLogger = new Logger(this, TAG, "service2.txt");
mVmManager = new VmManager(getApplication(), mLogger);
mLogger.write("Entering onCreate();");
// Set VM service callback to receive notifications
mVmManager.setVmServiceCallback(this);
mVmManager.vmRun();
// we cannot call mVmManager.getVMService().onCreate() here as the service is not connected yet
mLogger.write("Returning onCreate();");
}
)";
return std::make_shared<LiteralClassElement>(method);
}
static shared_ptr<ClassElement> GenerateOnBindMethod() {
string method = R"(
@Override
public IBinder onBind(Intent intent) {
mLogger.write("Entering onBind();");
// we cannot call mVmManager.getVMService().onBind() here as the service is not connected yet
mLogger.write("Returning onBind();");
return mBinder;
}
)";
return std::make_shared<LiteralClassElement>(method);
}
static shared_ptr<ClassElement> GenerateOnUnBindMethod() {
string method = R"(
@Override
public boolean onUnbind(Intent intent) {
mLogger.write("Entering onUnbind();");
mLogger.write("Returning onUnbind();");
return false; // return true if you want onRebind() to be called later
}
)";
return std::make_shared<LiteralClassElement>(method);
}
static shared_ptr<ClassElement> GenerateOnDestroyMethod() {
string method = R"(
@Override
public void onDestroy() {
mLogger.write("Entering onDestroy();");
mVmManager.vmStop();
mLogger.write("Returning onDestroy();");
}
)";
return std::make_shared<LiteralClassElement>(method);
}
static shared_ptr<ClassElement> GenerateVmServiceCallbackMethods(const string iface_name) {
string methods = R"(
// VmServiceCallback implementation
@Override
public void onVmServiceReady(IRealmService vmService) {
mLogger.write("onVmServiceReady is called, please wait for binding the target service..");
// You can perform additional initialization work here when VM service is ready.
// For example: call specific VM service methods, set up states, etc.
try {
// Call onBindForTargetService to get the target service binder
IBinder targetBinder = vmService.onBindForTargetService();
if (targetBinder != null) {
)";
methods += " mTargetService = " + iface_name + ".Stub.asInterface(targetBinder);\n";
methods += R"(
mLogger.write("Target service binder successfully obtained and converted.");
} else {
mLogger.write("Failed to obtain target service binder - binder is null.");
}
} catch (Exception e) {
mLogger.write("Error in onVmServiceReady: " + e.getMessage());
}
}
@Override
public void onVmServiceError(String errorMessage) {
mLogger.write("VM service error occurred: " + errorMessage);
// You can implement error handling logic here when VM service connection fails.
// For example: retry logic, notify user, fallback behavior, etc.
mLogger.write("Handling VM service connection error...");
}
)";
return std::make_shared<LiteralClassElement>(methods);
}
static string GetJavaFormatSpecifier(const std::unique_ptr<AidlArgument>& arg) {
string type = arg->GetType().GetName();
if (type == "int" || type == "long" || type == "short") return "%d";
if (type == "float" || type == "double") return "%f";
if (type == "String") return "%s";
return "%s"; // fallback
}
static string GenerateProxyCallback(const AidlInterface* cb_iface, const string& cb_arg_name, const string& type) {
string ret = "";
CodeWriterPtr writer = CodeWriter::ForString(&ret);
CodeWriter& code = *writer;
code << type + " proxy_" + cb_arg_name + " = new " + type + ".Stub() {\n";
code.Indent();
for (const auto& m : cb_iface->GetMethods()) {
string m_arguments = "";
code << "@Override\n";
code << "public void " + m->GetName() + "(";
const auto& args = m->GetArguments();
for (size_t i = 0; i < args.size(); ++i) {
const auto& arg = args[i];
m_arguments += arg->GetName();
code << JavaSignatureOf(arg->GetType()) + " " + arg->GetName();
if (i != args.size() - 1) {
code << ", ";
m_arguments += ", ";
}
}
code << ") throws IllegalStateException, RemoteException {\n";
code.Indent();
code << "mLogger.write(\"" + m->GetName() + "() called from realm world\");\n";
code << cb_arg_name + "." + m->GetName() + "(" + m_arguments + ");\n";
code.Dedent();
code << "}\n";
}
code.Dedent();
code << "};\n";
return ret;
}
struct ArgProcessingResult {
string proxy_args_str;
string log_args_str;
string proxy_callback_code;
};
static shared_ptr<Method> CreateMethodSkeleton(const AidlMethod& method) {
auto aidl_method = std::make_shared<Method>();
aidl_method->modifiers = PUBLIC | OVERRIDE;
aidl_method->returnType = JavaSignatureOf(method.GetType());
aidl_method->name = method.GetName();
aidl_method->statements = std::make_shared<StatementBlock>();
aidl_method->exceptions.push_back("IllegalStateException, RemoteException");
for (const auto& arg : method.GetArguments()) {
aidl_method->parameters.push_back(
std::make_shared<Variable>(JavaSignatureOf(arg->GetType()), arg->GetName()));
}
return aidl_method;
}
static ArgProcessingResult ProcessArguments(const std::vector<std::unique_ptr<AidlArgument>>& args) {
ArgProcessingResult result;
for (size_t i = 0; i < args.size(); ++i) {
const auto& arg = args[i];
string arg_name = arg->GetName();
result.log_args_str += arg_name;
const AidlDefinedType* def = arg->GetType().GetDefinedType();
if (def) {
const AidlInterface* cb_iface = def->AsInterface();
if (cb_iface) {
result.proxy_callback_code = GenerateProxyCallback(cb_iface, arg_name, JavaSignatureOf(arg->GetType()));
arg_name.insert(0, "proxy_");
}
}
result.proxy_args_str += arg_name;
if (i != args.size() - 1) {
result.proxy_args_str += ", ";
result.log_args_str += ", ";
}
}
return result;
}
static string GenerateMethodLoggingCode(const AidlMethod& method, const string& log_args_str) {
string full_method_name = "mBinder." + method.GetName();
string start_log_str = "mLogger.write(String.format(\"Entering %s(";
const auto& args = method.GetArguments();
for (size_t i = 0; i < args.size(); ++i) {
start_log_str += GetJavaFormatSpecifier(args[i]);
if (i != args.size() - 1) {
start_log_str += ", ";
}
}
if (args.empty()) {
start_log_str += ")\", \"" + full_method_name + "\"));\n";
} else {
start_log_str += ")\", \"" + full_method_name + "\", " + log_args_str + "));\n";
}
return start_log_str;
}
static string GenerateVmServiceCallCode(const AidlMethod& method, const string& proxy_args_str) {
string method_name = method.GetName();
string return_type = JavaSignatureOf(method.GetType());
bool is_void = (method.GetType().GetName() == "void");
string callback_str;
callback_str += "if (mTargetService != null) {\n";
if (is_void) {
callback_str += StringPrintf(" mTargetService.%s(%s);\n", method_name.c_str(), proxy_args_str.c_str());
} else {
callback_str += StringPrintf(" %s ret = mTargetService.%s(%s);\n", return_type.c_str(), method_name.c_str(), proxy_args_str.c_str());
callback_str += " mLogger.write(\"" + method_name + "() returning: \" + ret);\n";
callback_str += " return ret;\n";
}
callback_str += "} else {\n";
callback_str += " mLogger.write(\"Target service is not available yet\");\n";
callback_str += " throw new IllegalStateException(\"Target service is not available\");\n";
callback_str += "}\n";
return callback_str;
}
static shared_ptr<ClassElement> GenerateAIDLMethod(const AidlMethod& method) {
auto aidl_method = CreateMethodSkeleton(method);
const auto& args = method.GetArguments();
ArgProcessingResult arg_result = ProcessArguments(args);
string proxy_callback_code = arg_result.proxy_callback_code;
string logging_code = GenerateMethodLoggingCode(method, arg_result.log_args_str);
string vm_service_call_code = GenerateVmServiceCallCode(method, arg_result.proxy_args_str);
std::ostringstream statement;
statement << logging_code;
statement << proxy_callback_code;
statement << vm_service_call_code;
string full_method_name = "mBinder." + method.GetName();
if (method.GetType().GetName() == "void") {
statement << "mLogger.write(\"" << full_method_name << "()\");\n";
}
aidl_method->statements->Add(std::make_shared<LiteralStatement>(statement.str()));
return aidl_method;
}
static void GenerateStubInstance(const AidlInterface* iface,
std::shared_ptr<Class> default_class) {
string binder_instance = "\nprivate final " + iface->GetName() + ".Stub mBinder = new " + iface->GetName() + ".Stub() {\n";
default_class->elements.emplace_back(std::make_shared<LiteralClassElement>(binder_instance));
for (const auto& m : iface->GetMethods()) {
if (m->IsUserDefined()) {
default_class->elements.emplace_back(GenerateAIDLMethod(*m));
} else {
AIDL_ERROR(TAG.c_str()) << "method is not user-defined";
}
}
default_class->elements.emplace_back(std::make_shared<LiteralClassElement>("};\n"));
}
static void GenerateClass(CodeWriter& out, const AidlDefinedType& defined_type,
const Options& options) {
const string class_name = defined_type.GetCCServiceClassName();
const AidlInterface* iface = defined_type.AsInterface();
auto default_class = std::make_shared<Class>();
AIDL_WARN(TAG.c_str()) << "GenerateClass start. OutputDir: " << options.OutputDir();
if (iface == nullptr) {
AIDL_ERROR(TAG.c_str()) << "interface is null";
return;
}
default_class->modifiers = PUBLIC;
default_class->what = Class::CLASS;
default_class->type = defined_type.GetCCServiceFQCN();
default_class->extends = "Service";
default_class->interfaces.push_back("VmManager.VmServiceCallback");
default_class->elements.emplace_back(GenerateMemberVariables(class_name, iface->GetName()));
GenerateStubInstance(iface, default_class);
default_class->elements.emplace_back(GenerateOnCreateMethod());
default_class->elements.emplace_back(GenerateOnBindMethod());
default_class->elements.emplace_back(GenerateOnUnBindMethod());
default_class->elements.emplace_back(GenerateOnDestroyMethod());
default_class->elements.emplace_back(GenerateVmServiceCallbackMethods(iface->GetName()));
AIDL_WARN(TAG.c_str()) << "GenerateClass->Write start";
default_class->Write(&out);
AIDL_WARN(TAG.c_str()) << "GenerateProxyService: GenerateClass->Write done";
}
void GenerateAndroidManifest(const Options& options,
const AidlDefinedType& defined_type, const IoDelegate& io_delegate) {
string output_file_name = options.OutputFile();
string output_file_path = get_output_path(options, output_file_name);
string class_name = defined_type.GetCCServiceClassName();
output_file_name = output_file_path + "AndroidManifest.xml";
CodeWriterPtr code_writer = io_delegate.GetCodeWriter(output_file_name);
auto& out = *code_writer;
out << R"(<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
)";
out << " package=\"" + defined_type.GetCCServicePackage() + "\">\n";
out << R"(
<uses-permission android:name="android.permission.MANAGE_VIRTUAL_MACHINE" />
<uses-permission android:name="android.permission.USE_CUSTOM_VIRTUAL_MACHINE" />
<uses-feature android:name="android.software.virtualization_framework" android:required="true" />
<application>
)";
out << " <service android:name=\"." + class_name + "\"";
out << R"(
android:enabled="true"
android:exported="true">
<intent-filter>
)";
out << " <action android:name=\"" + defined_type.GetCCServiceFQCN() + "\" />";
out << R"(
</intent-filter>
</service>
</application>
</manifest>)";
AIDL_FATAL_IF(!code_writer->Close(), defined_type) << "I/O Error!";
AIDL_WARN("GenerateAndroidManifest is done");
}
void GenerateProxyService(const Options& options,
const AidlDefinedType& defined_type, const IoDelegate& io_delegate) {
const string class_name = defined_type.GetCCServiceClassName();
string output_file_name = options.OutputFile();
string output_file_path = get_output_path(options, output_file_name);
if (output_file_path.empty() && output_file_name.empty()) {
AIDL_ERROR(TAG.c_str()) << "output file & output directory are empty";
return;
}
output_file_name = GetProxyServiceFilePath(output_file_path, options, class_name);
CodeWriterPtr code_writer = io_delegate.GetCodeWriter(output_file_name);
/* write header */ {
auto& out = *code_writer;
GenerateAutoGenHeader(out, options);
if (const auto pkg = defined_type.GetCCServicePackage(); !pkg.empty()) {
out << "package " << pkg << ";\n";
}
GenerateImports(out, defined_type);
}
GenerateClass(*code_writer, defined_type, options);
AIDL_FATAL_IF(!code_writer->Close(), defined_type) << "I/O Error!";
AIDL_WARN("GenerateProxyService is done");
}
} // namespace java
} // namespace aidl
} // namespace android