-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_cpp.cpp
More file actions
1634 lines (1436 loc) · 68.5 KB
/
generate_cpp.cpp
File metadata and controls
1634 lines (1436 loc) · 68.5 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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2015, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "generate_cpp.h"
#include "aidl.h"
#include <algorithm>
#include <cctype>
#include <cstring>
#include <memory>
#include <random>
#include <set>
#include <string>
#include <android-base/format.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
#include "aidl_language.h"
#include "aidl_to_cpp.h"
#include "ast_cpp.h"
#include "code_writer.h"
#include "logging.h"
#include "os.h"
using android::base::Join;
using android::base::StringPrintf;
using std::set;
using std::string;
using std::unique_ptr;
using std::vector;
namespace android {
namespace aidl {
namespace cpp {
namespace internals {
namespace {
const char kAndroidStatusVarName[] = "_aidl_ret_status";
const char kCodeVarName[] = "_aidl_code";
const char kFlagsVarName[] = "_aidl_flags";
const char kDataVarName[] = "_aidl_data";
const char kErrorLabel[] = "_aidl_error";
const char kImplVarName[] = "_aidl_impl";
const char kParcelVarName[] = "_aidl_parcel";
const char kReplyVarName[] = "_aidl_reply";
const char kReturnVarName[] = "_aidl_return";
const char kStatusVarName[] = "_aidl_status";
const char kTraceVarName[] = "_aidl_trace";
const char kAndroidParcelLiteral[] = "::android::Parcel";
const char kAndroidStatusLiteral[] = "::android::status_t";
const char kAndroidStatusOk[] = "::android::OK";
const char kAndroidStatusBadValue[] = "::android::BAD_VALUE";
const char kBinderStatusLiteral[] = "::android::binder::Status";
const char kIBinderHeader[] = "binder/IBinder.h";
const char kIInterfaceHeader[] = "binder/IInterface.h";
const char kParcelHeader[] = "binder/Parcel.h";
const char kStabilityHeader[] = "binder/Stability.h";
const char kStatusHeader[] = "binder/Status.h";
const char kString16Header[] = "utils/String16.h";
const char kTraceHeader[] = "utils/Trace.h";
const char kStrongPointerHeader[] = "utils/StrongPointer.h";
const char kAndroidBaseMacrosHeader[] = "android-base/macros.h";
unique_ptr<AstNode> BreakOnStatusNotOk() {
IfStatement* ret = new IfStatement(new Comparison(
new LiteralExpression(kAndroidStatusVarName), "!=",
new LiteralExpression(kAndroidStatusOk)));
ret->OnTrue()->AddLiteral("break");
return unique_ptr<AstNode>(ret);
}
unique_ptr<AstNode> GotoErrorOnBadStatus() {
IfStatement* ret = new IfStatement(new Comparison(
new LiteralExpression(kAndroidStatusVarName), "!=",
new LiteralExpression(kAndroidStatusOk)));
ret->OnTrue()->AddLiteral(StringPrintf("goto %s", kErrorLabel));
return unique_ptr<AstNode>(ret);
}
unique_ptr<AstNode> ReturnOnStatusNotOk() {
IfStatement* ret = new IfStatement(new Comparison(new LiteralExpression(kAndroidStatusVarName),
"!=", new LiteralExpression(kAndroidStatusOk)));
ret->OnTrue()->AddLiteral(StringPrintf("return %s", kAndroidStatusVarName));
return unique_ptr<AstNode>(ret);
}
ArgList BuildArgList(const AidlTypenames& typenames, const AidlMethod& method, bool for_declaration,
bool type_name_only = false) {
// Build up the argument list for the server method call.
vector<string> method_arguments;
for (const unique_ptr<AidlArgument>& a : method.GetArguments()) {
string literal;
// b/144943748: CppNameOf FileDescriptor is unique_fd. Don't pass it by
// const reference but by value to make it easier for the user to keep
// it beyond the scope of the call. unique_fd is a thin wrapper for an
// int (fd) so passing by value is not expensive.
const bool nonCopyable = IsNonCopyableType(a->GetType(), typenames);
if (for_declaration) {
// Method declarations need typenames, pointers to out params, and variable
// names that match the .aidl specification.
literal = CppNameOf(a->GetType(), typenames);
if (a->IsOut()) {
literal = literal + "*";
} else {
const auto definedType = typenames.TryGetDefinedType(a->GetType().GetName());
const bool isEnum = definedType && definedType->AsEnumDeclaration() != nullptr;
const bool isPrimitive = AidlTypenames::IsPrimitiveTypename(a->GetType().GetName());
// We pass in parameters that are not primitives by const reference.
// Arrays of primitives are not primitives.
if (!(isPrimitive || isEnum || nonCopyable) || a->GetType().IsArray()) {
literal = "const " + literal + "&";
}
}
if (!type_name_only) {
literal += " " + a->GetName();
}
} else {
std::string varName = BuildVarName(*a);
if (a->IsOut()) {
literal = "&" + varName;
} else if (nonCopyable) {
literal = "std::move(" + varName + ")";
} else {
literal = varName;
}
}
method_arguments.push_back(literal);
}
if (method.GetType().GetName() != "void") {
string literal;
if (for_declaration) {
literal = CppNameOf(method.GetType(), typenames) + "*";
if (!type_name_only) {
literal += " " + string(kReturnVarName);
}
} else {
literal = string{"&"} + kReturnVarName;
}
method_arguments.push_back(literal);
}
return ArgList(method_arguments);
}
unique_ptr<Declaration> BuildMethodDecl(const AidlMethod& method, const AidlTypenames& typenames,
bool for_interface) {
uint32_t modifiers = 0;
if (for_interface) {
modifiers |= MethodDecl::IS_VIRTUAL;
modifiers |= MethodDecl::IS_PURE_VIRTUAL;
} else {
modifiers |= MethodDecl::IS_OVERRIDE;
}
const string attribute = GetDeprecatedAttribute(method);
return unique_ptr<Declaration>{new MethodDecl{
kBinderStatusLiteral, method.GetName(),
BuildArgList(typenames, method, true /* for method decl */), modifiers, attribute}};
}
unique_ptr<Declaration> BuildMetaMethodDecl(const AidlMethod& method, const AidlTypenames&,
const Options& options, bool for_interface) {
AIDL_FATAL_IF(method.IsUserDefined(), method);
if (method.GetName() == kGetInterfaceVersion && options.Version()) {
std::ostringstream code;
if (for_interface) {
code << "virtual ";
}
code << "int32_t " << kGetInterfaceVersion << "()";
if (for_interface) {
code << " = 0;\n";
} else {
code << " override;\n";
}
return unique_ptr<Declaration>(new LiteralDecl(code.str()));
}
if (method.GetName() == kGetInterfaceHash && !options.Hash().empty()) {
std::ostringstream code;
if (for_interface) {
code << "virtual ";
}
code << "std::string " << kGetInterfaceHash << "()";
if (for_interface) {
code << " = 0;\n";
} else {
code << " override;\n";
}
return unique_ptr<Declaration>(new LiteralDecl(code.str()));
}
return nullptr;
}
std::vector<unique_ptr<Declaration>> NestInNamespaces(vector<unique_ptr<Declaration>> decls,
const vector<string>& package) {
auto it = package.crbegin(); // Iterate over the namespaces inner to outer
for (; it != package.crend(); ++it) {
vector<unique_ptr<Declaration>> inner;
inner.emplace_back(unique_ptr<Declaration>{new CppNamespace{*it, std::move(decls)}});
decls = std::move(inner);
}
return decls;
}
std::vector<unique_ptr<Declaration>> NestInNamespaces(unique_ptr<Declaration> decl,
const vector<string>& package) {
vector<unique_ptr<Declaration>> decls;
decls.push_back(std::move(decl));
return NestInNamespaces(std::move(decls), package);
}
unique_ptr<Declaration> DefineClientTransaction(const AidlTypenames& typenames,
const AidlInterface& interface,
const AidlMethod& method, const Options& options) {
const string i_name = ClassName(interface, ClassNames::INTERFACE);
const string bp_name = ClassName(interface, ClassNames::CLIENT);
unique_ptr<MethodImpl> ret{
new MethodImpl{kBinderStatusLiteral,
bp_name,
method.GetName(),
{},
ArgList{BuildArgList(typenames, method, true /* for method decl */)}}};
StatementBlock* b = ret->GetStatementBlock();
// Declare parcels to hold our query and the response.
b->AddLiteral(StringPrintf("%s %s", kAndroidParcelLiteral, kDataVarName));
if (interface.IsSensitiveData()) {
b->AddLiteral(StringPrintf("%s.markSensitive()", kDataVarName));
}
b->AddLiteral(StringPrintf("%s.markForBinder(remoteStrong())", kDataVarName));
// Even if we're oneway, the transact method still takes a parcel.
b->AddLiteral(StringPrintf("%s %s", kAndroidParcelLiteral, kReplyVarName));
// Declare the status_t variable we need for error handling.
b->AddLiteral(StringPrintf("%s %s = %s", kAndroidStatusLiteral,
kAndroidStatusVarName,
kAndroidStatusOk));
// We unconditionally return a Status object.
b->AddLiteral(StringPrintf("%s %s", kBinderStatusLiteral, kStatusVarName));
if (options.GenTraces()) {
b->AddLiteral(
StringPrintf("::android::ScopedTrace %s(ATRACE_TAG_AIDL, \"AIDL::cpp::%s::%s::cppClient\")",
kTraceVarName, interface.GetName().c_str(), method.GetName().c_str()));
}
if (options.GenLog()) {
b->AddLiteral(GenLogBeforeExecute(bp_name, method, false /* isServer */, false /* isNdk */),
false /* no semicolon */);
}
// Add the name of the interface we're hoping to call.
b->AddStatement(new Assignment(
kAndroidStatusVarName,
new MethodCall(StringPrintf("%s.writeInterfaceToken",
kDataVarName),
"getInterfaceDescriptor()")));
b->AddStatement(GotoErrorOnBadStatus());
for (const auto& a: method.GetArguments()) {
const string var_name = ((a->IsOut()) ? "*" : "") + a->GetName();
if (a->IsIn()) {
// Serialization looks roughly like:
// _aidl_ret_status = _aidl_data.WriteInt32(in_param_name);
// if (_aidl_ret_status != ::android::OK) { goto error; }
const string& method = ParcelWriteMethodOf(a->GetType(), typenames);
b->AddStatement(
new Assignment(kAndroidStatusVarName,
new MethodCall(StringPrintf("%s.%s", kDataVarName, method.c_str()),
ParcelWriteCastOf(a->GetType(), typenames, var_name))));
b->AddStatement(GotoErrorOnBadStatus());
} else if (a->IsOut() && a->GetType().IsArray()) {
// Special case, the length of the out array is written into the parcel.
// _aidl_ret_status = _aidl_data.writeVectorSize(&out_param_name);
// if (_aidl_ret_status != ::android::OK) { goto error; }
b->AddStatement(new Assignment(
kAndroidStatusVarName,
new MethodCall(StringPrintf("%s.writeVectorSize", kDataVarName), var_name)));
b->AddStatement(GotoErrorOnBadStatus());
}
}
// Invoke the transaction on the remote binder and confirm status.
string transaction_code = GetTransactionIdFor(interface, method);
vector<string> args = {transaction_code, kDataVarName,
StringPrintf("&%s", kReplyVarName)};
std::vector<std::string> flags;
if (method.IsOneway()) flags.push_back("::android::IBinder::FLAG_ONEWAY");
if (interface.IsSensitiveData()) flags.push_back("::android::IBinder::FLAG_CLEAR_BUF");
args.push_back(flags.empty() ? "0" : Join(flags, " | "));
b->AddStatement(new Assignment(
kAndroidStatusVarName,
new MethodCall("remote()->transact",
ArgList(args))));
// If the method is not implemented in the remote side, try to call the
// default implementation, if provided.
vector<string> arg_names;
for (const auto& a : method.GetArguments()) {
if (IsNonCopyableType(a->GetType(), typenames)) {
arg_names.emplace_back(StringPrintf("std::move(%s)", a->GetName().c_str()));
} else {
arg_names.emplace_back(a->GetName());
}
}
if (method.GetType().GetName() != "void") {
arg_names.emplace_back(kReturnVarName);
}
b->AddLiteral(StringPrintf("if (UNLIKELY(_aidl_ret_status == ::android::UNKNOWN_TRANSACTION && "
"%s::getDefaultImpl())) {\n"
" return %s::getDefaultImpl()->%s(%s);\n"
"}\n",
i_name.c_str(), i_name.c_str(), method.GetName().c_str(),
Join(arg_names, ", ").c_str()),
false /* no semicolon */);
b->AddStatement(GotoErrorOnBadStatus());
if (!method.IsOneway()) {
// Strip off the exception header and fail if we see a remote exception.
// _aidl_ret_status = _aidl_status.readFromParcel(_aidl_reply);
// if (_aidl_ret_status != ::android::OK) { goto error; }
// if (!_aidl_status.isOk()) { return _aidl_ret_status; }
b->AddStatement(new Assignment(
kAndroidStatusVarName,
StringPrintf("%s.readFromParcel(%s)", kStatusVarName, kReplyVarName)));
b->AddStatement(GotoErrorOnBadStatus());
IfStatement* exception_check = new IfStatement(
new LiteralExpression(StringPrintf("!%s.isOk()", kStatusVarName)));
b->AddStatement(exception_check);
exception_check->OnTrue()->AddLiteral(
StringPrintf("return %s", kStatusVarName));
}
// Type checking should guarantee that nothing below emits code until "return
// status" if we are a oneway method, so no more fear of accessing reply.
// If the method is expected to return something, read it first by convention.
if (method.GetType().GetName() != "void") {
const string& method_call = ParcelReadMethodOf(method.GetType(), typenames);
b->AddStatement(new Assignment(
kAndroidStatusVarName,
new MethodCall(StringPrintf("%s.%s", kReplyVarName, method_call.c_str()),
ParcelReadCastOf(method.GetType(), typenames, kReturnVarName))));
b->AddStatement(GotoErrorOnBadStatus());
}
for (const AidlArgument* a : method.GetOutArguments()) {
// Deserialization looks roughly like:
// _aidl_ret_status = _aidl_reply.ReadInt32(out_param_name);
// if (_aidl_status != ::android::OK) { goto _aidl_error; }
string method = ParcelReadMethodOf(a->GetType(), typenames);
b->AddStatement(
new Assignment(kAndroidStatusVarName,
new MethodCall(StringPrintf("%s.%s", kReplyVarName, method.c_str()),
ParcelReadCastOf(a->GetType(), typenames, a->GetName()))));
b->AddStatement(GotoErrorOnBadStatus());
}
// If we've gotten to here, one of two things is true:
// 1) We've read some bad status_t
// 2) We've only read status_t == OK and there was no exception in the
// response.
// In both cases, we're free to set Status from the status_t and return.
b->AddLiteral(StringPrintf("%s:\n", kErrorLabel), false /* no semicolon */);
b->AddLiteral(
StringPrintf("%s.setFromStatusT(%s)", kStatusVarName,
kAndroidStatusVarName));
if (options.GenLog()) {
b->AddLiteral(GenLogAfterExecute(bp_name, interface, method, kStatusVarName, kReturnVarName,
false /* isServer */, false /* isNdk */),
false /* no semicolon */);
}
b->AddLiteral(StringPrintf("return %s", kStatusVarName));
return unique_ptr<Declaration>(ret.release());
}
unique_ptr<Declaration> DefineClientMetaTransaction(const AidlTypenames& /* typenames */,
const AidlInterface& interface,
const AidlMethod& method,
const Options& options) {
AIDL_FATAL_IF(method.IsUserDefined(), method);
if (method.GetName() == kGetInterfaceVersion && options.Version() > 0) {
const string iface = ClassName(interface, ClassNames::INTERFACE);
const string proxy = ClassName(interface, ClassNames::CLIENT);
// Note: race condition can happen here, but no locking is required
// because 1) writing an interger is atomic and 2) this transaction
// will always return the same value, i.e., competing threads will
// give write the same value to cached_version_.
std::ostringstream code;
code << "int32_t " << proxy << "::" << kGetInterfaceVersion << "() {\n"
<< " if (cached_version_ == -1) {\n"
<< " ::android::Parcel data;\n"
<< " ::android::Parcel reply;\n"
<< " data.writeInterfaceToken(getInterfaceDescriptor());\n"
<< " ::android::status_t err = remote()->transact(" << GetTransactionIdFor(interface, method)
<< ", data, &reply);\n"
<< " if (err == ::android::OK) {\n"
<< " ::android::binder::Status _aidl_status;\n"
<< " err = _aidl_status.readFromParcel(reply);\n"
<< " if (err == ::android::OK && _aidl_status.isOk()) {\n"
<< " cached_version_ = reply.readInt32();\n"
<< " }\n"
<< " }\n"
<< " }\n"
<< " return cached_version_;\n"
<< "}\n";
return unique_ptr<Declaration>(new LiteralDecl(code.str()));
}
if (method.GetName() == kGetInterfaceHash && !options.Hash().empty()) {
const string iface = ClassName(interface, ClassNames::INTERFACE);
const string proxy = ClassName(interface, ClassNames::CLIENT);
std::ostringstream code;
code << "std::string " << proxy << "::" << kGetInterfaceHash << "() {\n"
<< " std::lock_guard<std::mutex> lockGuard(cached_hash_mutex_);\n"
<< " if (cached_hash_ == \"-1\") {\n"
<< " ::android::Parcel data;\n"
<< " ::android::Parcel reply;\n"
<< " data.writeInterfaceToken(getInterfaceDescriptor());\n"
<< " ::android::status_t err = remote()->transact(" << GetTransactionIdFor(interface, method)
<< ", data, &reply);\n"
<< " if (err == ::android::OK) {\n"
<< " ::android::binder::Status _aidl_status;\n"
<< " err = _aidl_status.readFromParcel(reply);\n"
<< " if (err == ::android::OK && _aidl_status.isOk()) {\n"
<< " reply.readUtf8FromUtf16(&cached_hash_);\n"
<< " }\n"
<< " }\n"
<< " }\n"
<< " return cached_hash_;\n"
<< "}\n";
return unique_ptr<Declaration>(new LiteralDecl(code.str()));
}
return nullptr;
}
} // namespace
unique_ptr<Document> BuildClientSource(const AidlTypenames& typenames,
const AidlInterface& interface, const Options& options) {
vector<string> include_list = {
HeaderFile(interface, ClassNames::CLIENT, false),
HeaderFile(interface, ClassNames::SERVER, false), // for TRANSACTION_* consts
kParcelHeader,
kAndroidBaseMacrosHeader
};
if (options.GenLog()) {
include_list.emplace_back("chrono");
include_list.emplace_back("functional");
}
vector<unique_ptr<Declaration>> file_decls;
// The constructor just passes the IBinder instance up to the super
// class.
const string i_name = ClassName(interface, ClassNames::INTERFACE);
const string bp_name = ClassName(interface, ClassNames::CLIENT);
file_decls.push_back(unique_ptr<Declaration>{new ConstructorImpl{
bp_name,
ArgList{StringPrintf("const ::android::sp<::android::IBinder>& %s", kImplVarName)},
{"BpInterface<" + i_name + ">(" + kImplVarName + ")"}}});
if (options.GenLog()) {
string code;
CodeWriterPtr writer = CodeWriter::ForString(&code);
(*writer) << "std::function<void(const " + bp_name + "::TransactionLog&)> " << bp_name
<< "::logFunc;\n";
writer->Close();
file_decls.push_back(unique_ptr<Declaration>(new LiteralDecl(code)));
}
// Clients define a method per transaction.
for (const auto& method : interface.GetMethods()) {
unique_ptr<Declaration> m;
if (method->IsUserDefined()) {
m = DefineClientTransaction(typenames, interface, *method, options);
} else {
m = DefineClientMetaTransaction(typenames, interface, *method, options);
}
if (!m) { return nullptr; }
file_decls.push_back(std::move(m));
}
return unique_ptr<Document>{new CppSource{
include_list,
NestInNamespaces(std::move(file_decls), interface.GetSplitPackage())}};
}
namespace {
void BuildConstantDefinitions(const AidlDefinedType& type, const AidlTypenames& typenames,
const std::vector<std::string>& type_params,
const std::string& class_name,
vector<unique_ptr<Declaration>>& decls) {
for (const auto& constant : type.GetConstantDeclarations()) {
const AidlConstantValue& value = constant->GetValue();
if (value.GetType() != AidlConstantValue::Type::STRING) continue;
std::string cppType = CppNameOf(constant->GetType(), typenames);
unique_ptr<MethodImpl> getter(
new MethodImpl("const " + cppType + "&", class_name, constant->GetName(), type_params, {}));
getter->GetStatementBlock()->AddLiteral(
StringPrintf("static const %s value(%s)", cppType.c_str(),
constant->ValueString(ConstantValueDecorator).c_str()));
getter->GetStatementBlock()->AddLiteral("return value");
decls.push_back(std::move(getter));
}
}
void BuildConstantDeclarations(const AidlDefinedType& type, const AidlTypenames& typenames,
unique_ptr<ClassDecl>& cls, set<string>& includes) {
std::vector<std::unique_ptr<Declaration>> string_constants;
unique_ptr<Enum> byte_constant_enum{new Enum{"", "int8_t", false}};
unique_ptr<Enum> int_constant_enum{new Enum{"", "int32_t", false}};
unique_ptr<Enum> long_constant_enum{new Enum{"", "int64_t", false}};
for (const auto& constant : type.GetConstantDeclarations()) {
const AidlTypeSpecifier& type = constant->GetType();
const AidlConstantValue& value = constant->GetValue();
const string attribute = GetDeprecatedAttribute(*constant);
if (type.Signature() == "String") {
std::string cppType = CppNameOf(constant->GetType(), typenames);
unique_ptr<Declaration> getter(new MethodDecl("const " + cppType + "&", constant->GetName(),
{}, MethodDecl::IS_STATIC, attribute));
string_constants.push_back(std::move(getter));
} else if (type.Signature() == "byte") {
byte_constant_enum->AddValue(constant->GetName(),
constant->ValueString(ConstantValueDecorator), attribute);
} else if (type.Signature() == "int") {
int_constant_enum->AddValue(constant->GetName(),
constant->ValueString(ConstantValueDecorator), attribute);
} else if (type.Signature() == "long") {
long_constant_enum->AddValue(constant->GetName(),
constant->ValueString(ConstantValueDecorator), attribute);
} else {
AIDL_FATAL(value) << "Unrecognized constant type: " << type.Signature();
}
}
if (byte_constant_enum->HasValues()) {
cls->AddPublic(std::move(byte_constant_enum));
}
if (int_constant_enum->HasValues()) {
cls->AddPublic(std::move(int_constant_enum));
}
if (long_constant_enum->HasValues()) {
cls->AddPublic(std::move(long_constant_enum));
}
if (!string_constants.empty()) {
includes.insert(kString16Header);
for (auto& string_constant : string_constants) {
cls->AddPublic(std::move(string_constant));
}
}
}
bool HandleServerTransaction(const AidlTypenames& typenames, const AidlInterface& interface,
const AidlMethod& method, const Options& options, StatementBlock* b) {
// Declare all the parameters now. In the common case, we expect no errors
// in serialization.
for (const unique_ptr<AidlArgument>& a : method.GetArguments()) {
b->AddLiteral(StringPrintf("%s %s", CppNameOf(a->GetType(), typenames).c_str(),
BuildVarName(*a).c_str()));
}
// Declare a variable to hold the return value.
if (method.GetType().GetName() != "void") {
string type = CppNameOf(method.GetType(), typenames);
b->AddLiteral(StringPrintf("%s %s", type.c_str(), kReturnVarName));
}
// Check that the client is calling the correct interface.
IfStatement* interface_check = new IfStatement(
new MethodCall(StringPrintf("%s.checkInterface",
kDataVarName), "this"),
true /* invert the check */);
b->AddStatement(interface_check);
interface_check->OnTrue()->AddStatement(
new Assignment(kAndroidStatusVarName, "::android::BAD_TYPE"));
interface_check->OnTrue()->AddLiteral("break");
if (options.GenTraces()) {
b->AddLiteral(
StringPrintf("::android::ScopedTrace %s(ATRACE_TAG_AIDL, \"AIDL::cpp::%s::%s::cppServer\")",
kTraceVarName, interface.GetName().c_str(), method.GetName().c_str()));
}
// Deserialize each "in" parameter to the transaction.
for (const auto& a: method.GetArguments()) {
// Deserialization looks roughly like:
// _aidl_ret_status = _aidl_data.ReadInt32(&in_param_name);
// if (_aidl_ret_status != ::android::OK) { break; }
const string& var_name = "&" + BuildVarName(*a);
if (a->IsIn()) {
const string& readMethod = ParcelReadMethodOf(a->GetType(), typenames);
b->AddStatement(
new Assignment{kAndroidStatusVarName,
new MethodCall{string(kDataVarName) + "." + readMethod,
ParcelReadCastOf(a->GetType(), typenames, var_name)}});
b->AddStatement(BreakOnStatusNotOk());
} else if (a->IsOut() && a->GetType().IsArray()) {
// Special case, the length of the out array is written into the parcel.
// _aidl_ret_status = _aidl_data.resizeOutVector(&out_param_name);
// if (_aidl_ret_status != ::android::OK) { break; }
b->AddStatement(
new Assignment{kAndroidStatusVarName,
new MethodCall{string(kDataVarName) + ".resizeOutVector", var_name}});
b->AddStatement(BreakOnStatusNotOk());
}
}
const string bn_name = ClassName(interface, ClassNames::SERVER);
if (options.GenLog()) {
b->AddLiteral(GenLogBeforeExecute(bn_name, method, true /* isServer */, false /* isNdk */),
false);
}
// Call the actual method. This is implemented by the subclass.
vector<unique_ptr<AstNode>> status_args;
status_args.emplace_back(new MethodCall(
method.GetName(), BuildArgList(typenames, method, false /* not for method decl */)));
b->AddStatement(new Statement(new MethodCall(
StringPrintf("%s %s", kBinderStatusLiteral, kStatusVarName),
ArgList(std::move(status_args)))));
if (options.GenLog()) {
b->AddLiteral(GenLogAfterExecute(bn_name, interface, method, kStatusVarName, kReturnVarName,
true /* isServer */, false /* isNdk */),
false);
}
// Write exceptions during transaction handling to parcel.
if (!method.IsOneway()) {
b->AddStatement(new Assignment(
kAndroidStatusVarName,
StringPrintf("%s.writeToParcel(%s)", kStatusVarName, kReplyVarName)));
b->AddStatement(BreakOnStatusNotOk());
IfStatement* exception_check = new IfStatement(
new LiteralExpression(StringPrintf("!%s.isOk()", kStatusVarName)));
b->AddStatement(exception_check);
exception_check->OnTrue()->AddLiteral("break");
}
// If we have a return value, write it first.
if (method.GetType().GetName() != "void") {
string writeMethod =
string(kReplyVarName) + "->" + ParcelWriteMethodOf(method.GetType(), typenames);
b->AddStatement(new Assignment(
kAndroidStatusVarName,
new MethodCall(writeMethod,
ParcelWriteCastOf(method.GetType(), typenames, kReturnVarName))));
b->AddStatement(BreakOnStatusNotOk());
}
// Write each out parameter to the reply parcel.
for (const AidlArgument* a : method.GetOutArguments()) {
// Serialization looks roughly like:
// _aidl_ret_status = data.WriteInt32(out_param_name);
// if (_aidl_ret_status != ::android::OK) { break; }
const string& writeMethod = ParcelWriteMethodOf(a->GetType(), typenames);
b->AddStatement(new Assignment(
kAndroidStatusVarName,
new MethodCall(string(kReplyVarName) + "->" + writeMethod,
ParcelWriteCastOf(a->GetType(), typenames, BuildVarName(*a)))));
b->AddStatement(BreakOnStatusNotOk());
}
return true;
}
bool HandleServerMetaTransaction(const AidlTypenames&, const AidlInterface& interface,
const AidlMethod& method, const Options& options,
StatementBlock* b) {
AIDL_FATAL_IF(method.IsUserDefined(), method);
if (method.GetName() == kGetInterfaceVersion && options.Version() > 0) {
std::ostringstream code;
code << "_aidl_data.checkInterface(this);\n"
<< "_aidl_reply->writeNoException();\n"
<< "_aidl_reply->writeInt32(" << ClassName(interface, ClassNames::INTERFACE)
<< "::VERSION)";
b->AddLiteral(code.str());
return true;
}
if (method.GetName() == kGetInterfaceHash && !options.Hash().empty()) {
std::ostringstream code;
code << "_aidl_data.checkInterface(this);\n"
<< "_aidl_reply->writeNoException();\n"
<< "_aidl_reply->writeUtf8AsUtf16(" << ClassName(interface, ClassNames::INTERFACE)
<< "::HASH)";
b->AddLiteral(code.str());
return true;
}
return false;
}
} // namespace
unique_ptr<Document> BuildServerSource(const AidlTypenames& typenames,
const AidlInterface& interface, const Options& options) {
const string bn_name = ClassName(interface, ClassNames::SERVER);
vector<string> include_list{
HeaderFile(interface, ClassNames::SERVER, false),
kParcelHeader,
kStabilityHeader,
};
if (options.GenLog()) {
include_list.emplace_back("chrono");
include_list.emplace_back("functional");
}
unique_ptr<ConstructorImpl> constructor{new ConstructorImpl{bn_name, ArgList{}, {}}};
if (interface.IsVintfStability()) {
constructor->GetStatementBlock()->AddLiteral("::android::internal::Stability::markVintf(this)");
} else {
constructor->GetStatementBlock()->AddLiteral(
"::android::internal::Stability::markCompilationUnit(this)");
}
unique_ptr<MethodImpl> on_transact{
new MethodImpl{kAndroidStatusLiteral,
bn_name,
"onTransact",
{},
ArgList{{StringPrintf("uint32_t %s", kCodeVarName),
StringPrintf("const %s& %s", kAndroidParcelLiteral, kDataVarName),
StringPrintf("%s* %s", kAndroidParcelLiteral, kReplyVarName),
StringPrintf("uint32_t %s", kFlagsVarName)}}}};
// Declare the status_t variable
on_transact->GetStatementBlock()->AddLiteral(
StringPrintf("%s %s = %s", kAndroidStatusLiteral, kAndroidStatusVarName,
kAndroidStatusOk));
// Add the all important switch statement, but retain a pointer to it.
SwitchStatement* s = new SwitchStatement{kCodeVarName};
on_transact->GetStatementBlock()->AddStatement(s);
// The switch statement has a case statement for each transaction code.
for (const auto& method : interface.GetMethods()) {
StatementBlock* b = s->AddCase(GetTransactionIdFor(interface, *method));
if (!b) { return nullptr; }
bool success = false;
if (method->IsUserDefined()) {
success = HandleServerTransaction(typenames, interface, *method, options, b);
} else {
success = HandleServerMetaTransaction(typenames, interface, *method, options, b);
}
if (!success) {
return nullptr;
}
}
// The switch statement has a default case which defers to the super class.
// The superclass handles a few pre-defined transactions.
StatementBlock* b = s->AddCase("");
b->AddLiteral(StringPrintf(
"%s = ::android::BBinder::onTransact(%s, %s, "
"%s, %s)", kAndroidStatusVarName, kCodeVarName,
kDataVarName, kReplyVarName, kFlagsVarName));
// If we saw a null reference, we can map that to an appropriate exception.
IfStatement* null_check = new IfStatement(
new LiteralExpression(string(kAndroidStatusVarName) +
" == ::android::UNEXPECTED_NULL"));
on_transact->GetStatementBlock()->AddStatement(null_check);
null_check->OnTrue()->AddStatement(new Assignment(
kAndroidStatusVarName,
StringPrintf("%s::fromExceptionCode(%s::EX_NULL_POINTER)"
".writeToParcel(%s)",
kBinderStatusLiteral, kBinderStatusLiteral,
kReplyVarName)));
// Finally, the server's onTransact method just returns a status code.
on_transact->GetStatementBlock()->AddLiteral(
StringPrintf("return %s", kAndroidStatusVarName));
vector<unique_ptr<Declaration>> decls;
decls.push_back(std::move(constructor));
bool deprecated = interface.IsDeprecated() ||
std::any_of(interface.GetMethods().begin(), interface.GetMethods().end(),
[](const auto& m) { return m->IsDeprecated(); });
if (deprecated) {
decls.emplace_back(
new LiteralDecl("#pragma clang diagnostic push\n"
"#pragma clang diagnostic ignored \"-Wdeprecated\"\n"));
}
decls.push_back(std::move(on_transact));
if (deprecated) {
decls.emplace_back(new LiteralDecl("#pragma clang diagnostic pop\n"));
}
if (options.Version() > 0) {
std::ostringstream code;
code << "int32_t " << bn_name << "::" << kGetInterfaceVersion << "() {\n"
<< " return " << ClassName(interface, ClassNames::INTERFACE) << "::VERSION;\n"
<< "}\n";
decls.emplace_back(new LiteralDecl(code.str()));
}
if (!options.Hash().empty()) {
std::ostringstream code;
code << "std::string " << bn_name << "::" << kGetInterfaceHash << "() {\n"
<< " return " << ClassName(interface, ClassNames::INTERFACE) << "::HASH;\n"
<< "}\n";
decls.emplace_back(new LiteralDecl(code.str()));
}
if (options.GenLog()) {
string code;
CodeWriterPtr writer = CodeWriter::ForString(&code);
(*writer) << "std::function<void(const " + bn_name + "::TransactionLog&)> " << bn_name
<< "::logFunc;\n";
writer->Close();
decls.push_back(unique_ptr<Declaration>(new LiteralDecl(code)));
}
return unique_ptr<Document>{
new CppSource{include_list, NestInNamespaces(std::move(decls), interface.GetSplitPackage())}};
}
unique_ptr<Document> BuildInterfaceSource(const AidlTypenames& typenames,
const AidlInterface& interface,
[[maybe_unused]] const Options& options) {
vector<string> include_list{
HeaderFile(interface, ClassNames::RAW, false),
HeaderFile(interface, ClassNames::CLIENT, false),
};
vector<unique_ptr<Declaration>> decls;
unique_ptr<MacroDecl> meta_if{
new MacroDecl{"DO_NOT_DIRECTLY_USE_ME_IMPLEMENT_META_INTERFACE",
ArgList{vector<string>{ClassName(interface, ClassNames::BASE),
'"' + interface.GetDescriptor() + '"'}}}};
decls.push_back(std::move(meta_if));
BuildConstantDefinitions(interface, typenames, {}, ClassName(interface, ClassNames::INTERFACE),
decls);
return unique_ptr<Document>{new CppSource{
include_list,
NestInNamespaces(std::move(decls), interface.GetSplitPackage())}};
}
unique_ptr<Document> BuildClientHeader(const AidlTypenames& typenames,
const AidlInterface& interface, const Options& options) {
const string i_name = ClassName(interface, ClassNames::INTERFACE);
const string bp_name = ClassName(interface, ClassNames::CLIENT);
vector<string> includes = {kIBinderHeader, kIInterfaceHeader, "utils/Errors.h",
HeaderFile(interface, ClassNames::RAW, false)};
unique_ptr<ConstructorDecl> constructor{new ConstructorDecl{
bp_name,
ArgList{StringPrintf("const ::android::sp<::android::IBinder>& %s",
kImplVarName)},
ConstructorDecl::IS_EXPLICIT
}};
unique_ptr<ConstructorDecl> destructor{new ConstructorDecl{
"~" + bp_name,
ArgList{},
ConstructorDecl::IS_VIRTUAL | ConstructorDecl::IS_DEFAULT}};
vector<unique_ptr<Declaration>> publics;
vector<unique_ptr<Declaration>> privates;
publics.push_back(std::move(constructor));
publics.push_back(std::move(destructor));
for (const auto& method: interface.GetMethods()) {
if (method->IsUserDefined()) {
publics.push_back(BuildMethodDecl(*method, typenames, false));
} else {
publics.push_back(BuildMetaMethodDecl(*method, typenames, options, false));
}
}
if (options.GenLog()) {
includes.emplace_back("functional"); // for std::function
includes.emplace_back("android/binder_to_string.h");
publics.emplace_back(new LiteralDecl{kTransactionLogStruct});
publics.emplace_back(
new LiteralDecl{"static std::function<void(const TransactionLog&)> logFunc;\n"});
}
if (options.Version() > 0) {
privates.emplace_back(new LiteralDecl("int32_t cached_version_ = -1;\n"));
}
if (!options.Hash().empty()) {
privates.emplace_back(new LiteralDecl("std::string cached_hash_ = \"-1\";\n"));
privates.emplace_back(new LiteralDecl("std::mutex cached_hash_mutex_;\n"));
}
const string attribute = GetDeprecatedAttribute(interface);
unique_ptr<ClassDecl> bp_class{new ClassDecl{
bp_name,
"::android::BpInterface<" + i_name + ">",
{},
std::move(publics),
std::move(privates),
attribute,
}};
return unique_ptr<Document>{
new CppHeader{includes, NestInNamespaces(std::move(bp_class), interface.GetSplitPackage())}};
}
unique_ptr<Document> BuildServerHeader(const AidlTypenames& /* typenames */,
const AidlInterface& interface, const Options& options) {
const string i_name = ClassName(interface, ClassNames::INTERFACE);
const string bn_name = ClassName(interface, ClassNames::SERVER);
unique_ptr<ConstructorDecl> constructor{
new ConstructorDecl{bn_name, ArgList{}, ConstructorDecl::IS_EXPLICIT}};
unique_ptr<Declaration> on_transact{new MethodDecl{
kAndroidStatusLiteral, "onTransact",
ArgList{{StringPrintf("uint32_t %s", kCodeVarName),
StringPrintf("const %s& %s", kAndroidParcelLiteral,
kDataVarName),
StringPrintf("%s* %s", kAndroidParcelLiteral, kReplyVarName),
StringPrintf("uint32_t %s", kFlagsVarName)}},
MethodDecl::IS_OVERRIDE
}};
vector<string> includes = {"binder/IInterface.h", HeaderFile(interface, ClassNames::RAW, false)};
vector<unique_ptr<Declaration>> publics;
vector<unique_ptr<Declaration>> privates;
for (const auto& method : interface.GetMethods()) {
std::ostringstream code;
code << "static constexpr uint32_t TRANSACTION_" << method->GetName() << " = "
<< "::android::IBinder::FIRST_CALL_TRANSACTION + " << method->GetId() << ";\n";
publics.push_back(std::make_unique<LiteralDecl>(code.str()));
}
publics.push_back(std::move(constructor));
publics.push_back(std::move(on_transact));
if (options.Version() > 0) {
std::ostringstream code;
code << "int32_t " << kGetInterfaceVersion << "() final;\n";
publics.emplace_back(new LiteralDecl(code.str()));
}
if (!options.Hash().empty()) {
std::ostringstream code;
code << "std::string " << kGetInterfaceHash << "();\n";
publics.emplace_back(new LiteralDecl(code.str()));
}
if (options.GenLog()) {
includes.emplace_back("functional"); // for std::function
includes.emplace_back("android/binder_to_string.h");
publics.emplace_back(new LiteralDecl{kTransactionLogStruct});
publics.emplace_back(
new LiteralDecl{"static std::function<void(const TransactionLog&)> logFunc;\n"});
}
const string attribute = GetDeprecatedAttribute(interface);
unique_ptr<ClassDecl> bn_class{new ClassDecl{
bn_name,
"::android::BnInterface<" + i_name + ">",
{},
std::move(publics),
std::move(privates),
attribute,
}};
return unique_ptr<Document>{
new CppHeader{includes, NestInNamespaces(std::move(bn_class), interface.GetSplitPackage())}};
}
unique_ptr<Document> BuildInterfaceHeader(const AidlTypenames& typenames,
const AidlInterface& interface, const Options& options) {