-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterface_gen.go
More file actions
2614 lines (2334 loc) · 82.1 KB
/
interface_gen.go
File metadata and controls
2614 lines (2334 loc) · 82.1 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
package codegen
import (
"fmt"
"strings"
"github.com/AndroidGoLab/binder/binder"
"github.com/AndroidGoLab/binder/tools/pkg/parser"
)
// GenerateInterface generates Go source for an AIDL interface declaration.
// The output includes:
// - A Go interface type with all methods
// - A client-side proxy struct
// - A constructor for the proxy
// - Proxy method implementations that serialize/deserialize via parcels
// - Transaction code constants
// - A descriptor constant
func GenerateInterface(
decl *parser.InterfaceDecl,
pkg string,
qualifiedName string,
options ...GenOption,
) ([]byte, error) {
opts := applyGenOptions(options)
f := NewGoFile(pkg)
typeRef := opts.newTypeRefResolver(f)
// Reserve all parameter names so that import aliases cannot shadow them.
// This must happen before any type resolution triggers ensureImport.
if typeRef != nil {
typeRef.ReserveNames(collectParamNames(decl.Methods))
}
f.AddImport("github.com/AndroidGoLab/binder/binder", "")
// The stub's OnTransaction method always references context.Context and
// *parcel.Parcel, so these imports are needed even for method-less interfaces.
f.AddImport("context", "")
f.AddImport("github.com/AndroidGoLab/binder/parcel", "")
interfaceName := AIDLToGoName(decl.IntfName)
proxyName := deriveProxyName(interfaceName)
descriptorConst := "Descriptor" + interfaceName
f.P("// Code generated by aidlgen. DO NOT EDIT.")
f.P("")
// Descriptor constant.
f.P("const %s = %q", descriptorConst, qualifiedName)
f.P("")
// Transaction code constants.
writeTransactionCodes(f, decl.Methods, interfaceName)
// Interface type.
writeInterfaceType(f, decl, interfaceName, typeRef)
// Constants declared inside the interface.
if len(decl.Constants) > 0 {
if err := GenerateConstants(decl.Constants, f, interfaceName); err != nil {
return nil, fmt.Errorf("generating interface constants: %w", err)
}
f.P("")
}
// Proxy struct.
writeProxyStruct(f, interfaceName, proxyName)
// Proxy methods.
for i, m := range decl.Methods {
writeProxyMethod(f, interfaceName, proxyName, descriptorConst, m, i, decl.Oneway, opts, typeRef)
}
// Stub type (server-side transaction dispatcher).
stubName := deriveStubName(interfaceName)
writeStubType(f, interfaceName, stubName, descriptorConst, decl, opts, typeRef)
// Server-side helper: constructor returning a full interface
// implementation backed by a StubBinder for binder registration.
writeStubConstructor(f, interfaceName, stubName, decl, typeRef)
return f.Bytes()
}
// collectParamNames returns the deduplicated set of Go identifier names
// that will appear as method parameters in the generated interface file.
// These names must be reserved so that import aliases do not shadow them.
func collectParamNames(methods []*parser.MethodDecl) []string {
seen := make(map[string]bool)
for _, m := range methods {
regularParams, _ := classifyParams(m.Params)
nameMap := disambiguateParams(regularParams)
for _, p := range regularParams {
seen[nameMap[p]] = true
}
}
names := make([]string, 0, len(seen))
for name := range seen {
names = append(names, name)
}
return names
}
// deriveProxyName derives a proxy struct name from an interface name.
// IFoo -> FooProxy, Foo -> FooProxy.
func deriveProxyName(interfaceName string) string {
base := interfaceName
if strings.HasPrefix(interfaceName, "I") && len(interfaceName) > 1 {
base = interfaceName[1:]
}
return base + "Proxy"
}
// deriveStubName derives a stub struct name from an interface name.
// IFoo -> FooStub, Foo -> FooStub.
func deriveStubName(interfaceName string) string {
base := interfaceName
if strings.HasPrefix(interfaceName, "I") && len(interfaceName) > 1 {
base = interfaceName[1:]
}
return base + "Stub"
}
// writeStubType writes the server-side stub struct, interface compliance
// assertion, and OnTransaction dispatcher method. The stub unmarshals
// incoming binder transactions and dispatches them to a typed Go
// interface implementation.
func writeStubType(
f *GoFile,
interfaceName string,
stubName string,
descriptorConst string,
decl *parser.InterfaceDecl,
opts GenOptions,
typeRef *TypeRefResolver,
) {
f.AddImport("fmt", "")
// Stub struct.
f.P("// %s dispatches incoming binder transactions", stubName)
f.P("// to a typed %s implementation.", interfaceName)
f.P("type %s struct {", stubName)
f.P("\tImpl %s", interfaceName)
f.P("\tTransport binder.VersionAwareTransport")
f.P("}")
f.P("")
// Interface compliance assertion.
f.P("var _ binder.TransactionReceiver = (*%s)(nil)", stubName)
f.P("")
// Descriptor returns the AIDL interface descriptor.
// The binder driver calls INTERFACE_TRANSACTION to verify the
// remote binder's class before delivering transactions.
f.P("func (s *%s) Descriptor() string {", stubName)
f.P("\treturn %s", descriptorConst)
f.P("}")
f.P("")
// OnTransaction method. The parcel parameter is named _data (with
// underscore) to avoid colliding with import aliases such as
// "data" for android.hardware.radio.data.
f.P("func (s *%s) OnTransaction(", stubName)
f.P("\tctx context.Context,")
f.P("\tcode binder.TransactionCode,")
f.P("\t_data *parcel.Parcel,")
f.P(") (*parcel.Parcel, error) {")
// ReadInterfaceToken validates that the caller is addressing the
// correct interface. This must happen before dispatching to any
// method case, and also for interfaces with no methods (marker
// interfaces) so that malformed transactions are rejected early.
f.P("\tif _, _err := _data.ReadInterfaceToken(); _err != nil {")
f.P("\t\treturn nil, _err")
f.P("\t}")
f.P("")
f.P("\tswitch code {")
// Track transaction codes to skip duplicate cases. Two AIDL methods
// can resolve to the same transaction code when one overrides another
// across AIDL versions; only the first occurrence is generated.
usedCodes := map[int]bool{}
counter := 0
for _, m := range decl.Methods {
code := counter
if m.TransactionID != 0 {
code = m.TransactionID - 1
}
if usedCodes[code] {
counter = code + 1
continue
}
usedCodes[code] = true
counter = code + 1
writeStubCase(f, interfaceName, descriptorConst, m, decl.Oneway, opts, typeRef)
}
f.P("\tdefault:")
f.P("\t\treturn nil, fmt.Errorf(\"unknown transaction code %%d\", code)")
f.P("\t}")
f.P("}")
f.P("")
}
// writeStubConstructor generates a server-side constructor that creates a
// StubBinder from a user-provided implementation. It generates:
// - An IXxxServer interface (like IXxx but without AsBinder)
// - A private wrapper type satisfying IXxx by delegating methods to
// the server impl and providing AsBinder via an embedded StubBinder
// - A NewXxxStub(impl) constructor returning *binder.StubBinder
func writeStubConstructor(
f *GoFile,
interfaceName string,
stubName string,
decl *parser.InterfaceDecl,
typeRef *TypeRefResolver,
) {
serverIntfName := interfaceName + "Server"
wrapperName := unexport(stubName) + "Wrapper"
// Server interface: same as the full interface minus AsBinder().
f.P("// %s is the server-side interface that user implementations", serverIntfName)
f.P("// provide to New%s. It contains only the business methods,", stubName)
f.P("// without AsBinder (which is provided by the stub itself).")
f.P("type %s interface {", serverIntfName)
for _, m := range decl.Methods {
f.P("\t%s", methodSignature(m, typeRef))
}
f.P("}")
f.P("")
// Private wrapper: satisfies the full interface by embedding the
// server impl and holding a *binder.StubBinder.
f.P("type %s struct {", wrapperName)
f.P("\timpl %s", serverIntfName)
f.P("\tstubBinder *binder.StubBinder")
f.P("}")
f.P("")
f.P("func (w *%s) AsBinder() binder.IBinder {", wrapperName)
f.P("\treturn w.stubBinder")
f.P("}")
f.P("")
// Delegate each method to the impl.
for _, m := range decl.Methods {
goName := AIDLToGoName(m.MethodName)
hasReturn := m.ReturnType != nil && m.ReturnType.Name != "void"
regular, _ := classifyParams(m.Params)
wrapNameMap := disambiguateParams(regular)
// Method signature.
f.P("func (w *%s) %s(", wrapperName, goName)
f.P("\tctx context.Context,")
for _, param := range regular {
goType := resolveTypeRef(typeRef, param.Type)
f.P("\t%s %s,", wrapNameMap[param], goType)
}
if hasReturn {
goRetType := resolveTypeRef(typeRef, m.ReturnType)
f.P(") (%s, error) {", goRetType)
} else {
f.P(") error {")
}
// Build call args.
var args []string
args = append(args, "ctx")
for _, param := range regular {
args = append(args, wrapNameMap[param])
}
f.P("\treturn w.impl.%s(%s)", goName, strings.Join(args, ", "))
f.P("}")
f.P("")
}
// Interface compliance assertion for the wrapper.
f.P("var _ %s = (*%s)(nil)", interfaceName, wrapperName)
f.P("")
// Constructor: NewXxxStub(impl) IXxx.
f.P("// New%s creates a server-side %s wrapping the given", stubName, interfaceName)
f.P("// server implementation. The returned value satisfies %s", interfaceName)
f.P("// and can be passed to proxy methods; its AsBinder() returns a")
f.P("// *binder.StubBinder that is auto-registered with the binder")
f.P("// driver on first use.")
f.P("func New%s(", stubName)
f.P("\timpl %s,", serverIntfName)
f.P(") %s {", interfaceName)
f.P("\twrapper := &%s{impl: impl}", wrapperName)
f.P("\tstub := &%s{Impl: wrapper}", stubName)
f.P("\twrapper.stubBinder = binder.NewStubBinder(stub)")
f.P("\treturn wrapper")
f.P("}")
f.P("")
}
// unexport returns the identifier with the first letter lowercased.
func unexport(s string) string {
if s == "" {
return s
}
return strings.ToLower(s[:1]) + s[1:]
}
// writeStubCase writes a single case in the OnTransaction switch for a method.
func writeStubCase(
f *GoFile,
interfaceName string,
descriptorConst string,
m *parser.MethodDecl,
interfaceOneway bool,
opts GenOptions,
typeRef *TypeRefResolver,
) {
goName := AIDLToGoName(m.MethodName)
constName := "Transaction" + interfaceName + goName
isOneway := m.Oneway || interfaceOneway
hasReturn := m.ReturnType != nil && m.ReturnType.Name != "void"
f.P("\tcase %s:", constName)
// Read parameters from data parcel. Track whether _err has been
// declared in this case scope so we can use = vs := correctly.
regularParams, _ := classifyParams(m.Params)
allNameMap := disambiguateParams(m.Params)
paramVarNames := make([]string, 0, len(regularParams))
errDeclared := false
for _, param := range m.Params {
if param.Direction == parser.DirectionOut {
// Out-only params are not read from data; declare a zero
// value to pass to the implementation.
varName := "_arg_" + allNameMap[param]
goType := resolveTypeRef(typeRef, param.Type)
f.P("\t\tvar %s %s", varName, goType)
paramVarNames = append(paramVarNames, varName)
continue
}
_, isIdentity := identityParamNames[param.ParamName]
if isIdentity && identityFieldForParam(param) != "" {
// Identity params are still on the wire but discarded by the stub.
writeStubDiscardParam(f, param, opts, typeRef)
continue
}
varName := "_arg_" + allNameMap[param]
paramVarNames = append(paramVarNames, varName)
declared := writeStubReadParam(f, param, varName, opts, typeRef, errDeclared)
errDeclared = errDeclared || declared
}
// Build the call expression.
var callArgs []string
callArgs = append(callArgs, "ctx")
paramIdx := 0
for _, param := range m.Params {
// Skip identity params that were discarded (not added to
// paramVarNames). DirectionOut identity params ARE in
// paramVarNames (handled at the top of the read loop), so
// only skip when the param was actually discarded.
if param.Direction != parser.DirectionOut && identityFieldForParam(param) != "" {
continue
}
if paramIdx < len(paramVarNames) {
callArgs = append(callArgs, paramVarNames[paramIdx])
paramIdx++
}
}
// When there's a return value, _result is always new, so := works.
// When there's no return value and _err was already declared by
// param reads, use = to avoid "no new variables" error.
switch {
case hasReturn:
f.P("\t\t_result, _err := s.Impl.%s(%s)", goName, strings.Join(callArgs, ", "))
case errDeclared:
f.P("\t\t_err = s.Impl.%s(%s)", goName, strings.Join(callArgs, ", "))
default:
f.P("\t\t_err := s.Impl.%s(%s)", goName, strings.Join(callArgs, ", "))
}
if isOneway {
// Oneway methods have no reply; return the error so the
// stub dispatch layer can log or handle it locally.
f.P("\t\treturn nil, _err")
} else {
// Write the reply parcel.
f.P("\t\t_reply := parcel.New()")
f.P("\t\tif _err != nil {")
f.P("\t\t\tbinder.WriteStatus(_reply, _err)")
f.P("\t\t\treturn _reply, nil")
f.P("\t\t}")
f.P("\t\tbinder.WriteStatus(_reply, nil)")
if hasReturn {
writeStubWriteReturn(f, m.ReturnType, opts, typeRef)
}
// Write out/inout params back to the reply parcel so the
// proxy can read the modified values.
for _, param := range m.Params {
if param.Direction == parser.DirectionOut || param.Direction == parser.DirectionInOut {
outVarName := "_arg_" + allNameMap[param]
writeStubOutParam(f, param, outVarName, opts, typeRef)
}
}
f.P("\t\treturn _reply, nil")
}
}
// writeStubOutParam writes a single out/inout parameter value to the
// reply parcel in a stub OnTransaction case.
func writeStubOutParam(
f *GoFile,
param *parser.ParamDecl,
varName string,
opts GenOptions,
typeRef *TypeRefResolver,
) {
if param.Type.IsArray || param.Type.Name == "List" {
writeStubWriteOutArray(f, param.Type, varName, opts, typeRef)
return
}
if param.Type.Name == "Map" {
writeStubWriteOutMap(f, param.Type, varName, opts, typeRef)
return
}
info := marshalForTypeWithCycleCheck(param.Type, opts, typeRef)
if info.WriteExpr == "" {
return
}
writeExpr := strings.ReplaceAll(info.WriteExpr, "_data", "_reply")
if strings.Contains(info.WriteExpr, ".MarshalParcel") {
f.P("\t\t_reply.WriteInt32(1)")
marshalExpr := fmt.Sprintf(writeExpr, varName)
f.P("\t\tif _err := %s; _err != nil {", marshalExpr)
f.P("\t\t\treturn nil, _err")
f.P("\t\t}")
return
}
if info.IsInterface {
f.P("\t\tbinder.WriteBinderToParcel(ctx, _reply, %s.AsBinder(), s.Transport)", varName)
return
}
if info.IsIBinder {
f.P("\t\tbinder.WriteBinderToParcel(ctx, _reply, %s, s.Transport)", varName)
return
}
formatted := fmt.Sprintf(writeExpr, varName)
f.P("\t\t%s", formatted)
}
// writeStubWriteOutArray writes an array out-param to the reply parcel.
func writeStubWriteOutArray(
f *GoFile,
ts *parser.TypeSpecifier,
varName string,
opts GenOptions,
typeRef *TypeRefResolver,
) {
elemType := elementTypeSpec(ts)
if elemType.Name == "byte" {
f.P("\t\t_reply.WriteByteArray(%s)", varName)
return
}
elemInfo := marshalForTypeWithCycleCheck(elemType, opts, typeRef)
f.P("\t\tif %s == nil {", varName)
f.P("\t\t\t_reply.WriteInt32(-1)")
f.P("\t\t} else {")
f.P("\t\t\t_reply.WriteInt32(int32(len(%s)))", varName)
if elemInfo.WriteExpr != "" {
f.P("\t\t\tfor _, _item := range %s {", varName)
writeExpr := fmt.Sprintf(elemInfo.WriteExpr, "_item")
writeExpr = strings.ReplaceAll(writeExpr, "_data", "_reply")
switch {
case strings.Contains(elemInfo.WriteExpr, ".MarshalParcel"):
f.P("\t\t\t\t_reply.WriteInt32(1)")
f.P("\t\t\t\tif _err := %s; _err != nil {", writeExpr)
f.P("\t\t\t\t\treturn nil, _err")
f.P("\t\t\t\t}")
case elemInfo.IsInterface:
f.P("\t\t\t\tbinder.WriteBinderToParcel(ctx, _reply, _item.AsBinder(), s.Transport)")
case elemInfo.IsIBinder:
f.P("\t\t\t\tbinder.WriteBinderToParcel(ctx, _reply, _item, s.Transport)")
default:
f.P("\t\t\t\t%s", writeExpr)
}
f.P("\t\t\t}")
}
f.P("\t\t}")
}
// writeStubWriteOutMap writes a Map out-param to the reply parcel in a
// stub OnTransaction case. Uses stub-appropriate error returns (nil, _err).
func writeStubWriteOutMap(
f *GoFile,
ts *parser.TypeSpecifier,
varName string,
opts GenOptions,
typeRef *TypeRefResolver,
) {
keyType := mapKeyTypeSpec(ts)
valType := mapValTypeSpec(ts)
keyInfo := marshalForTypeWithCycleCheck(keyType, opts, typeRef)
valInfo := marshalForTypeWithCycleCheck(valType, opts, typeRef)
f.P("\t\tif %s == nil {", varName)
f.P("\t\t\t_reply.WriteInt32(-1)")
f.P("\t\t} else {")
f.P("\t\t\t_reply.WriteInt32(int32(len(%s)))", varName)
if keyInfo.WriteExpr != "" && valInfo.WriteExpr != "" {
f.P("\t\t\tfor _k, _v := range %s {", varName)
keyVar := mapRangeVarWithAssertion("_k", keyType, ts, 0, typeRef)
valVar := mapRangeVarWithAssertion("_v", valType, ts, 1, typeRef)
writeKeyExpr := fmt.Sprintf(keyInfo.WriteExpr, keyVar)
writeKeyExpr = strings.ReplaceAll(writeKeyExpr, "_data", "_reply")
writeValExpr := fmt.Sprintf(valInfo.WriteExpr, valVar)
writeValExpr = strings.ReplaceAll(writeValExpr, "_data", "_reply")
stubErrReturn := "return nil, _err"
writeMapElemExpr(f, keyInfo, writeKeyExpr, stubErrReturn, "\t\t\t\t", "_reply", "s.Transport", keyVar)
writeMapElemExpr(f, valInfo, writeValExpr, stubErrReturn, "\t\t\t\t", "_reply", "s.Transport", valVar)
f.P("\t\t\t}")
}
f.P("\t\t}")
}
// writeStubDiscardParam generates code to read (and discard) an identity
// parameter from the data parcel. The wire format includes these fields
// even though the stub does not pass them to the implementation.
func writeStubDiscardParam(
f *GoFile,
param *parser.ParamDecl,
opts GenOptions,
typeRef *TypeRefResolver,
) {
info := marshalForTypeWithCycleCheck(param.Type, opts, typeRef)
readExpr := stubDataReadExpr(info.ReadExpr)
if readExpr == "" {
return
}
if strings.Contains(info.ReadExpr, ".UnmarshalParcel") {
// Parcelable identity param (unusual, but handle gracefully).
return
}
f.P("\t\tif _, _err := %s; _err != nil {", readExpr)
f.P("\t\t\treturn nil, _err")
f.P("\t\t}")
}
// writeStubReadParam generates code to read a single parameter from the
// data parcel into a local variable. errDeclared indicates whether _err
// has already been declared in the enclosing scope. Returns true if this
// call declares _err (via := with a read expression).
func writeStubReadParam(
f *GoFile,
param *parser.ParamDecl,
varName string,
opts GenOptions,
typeRef *TypeRefResolver,
errDeclared bool,
) bool {
if param.Type.IsArray || param.Type.Name == "List" {
writeStubReadArrayParam(f, param.Type, varName, opts, typeRef)
return false
}
if param.Type.Name == "Map" {
writeStubReadMapParam(f, param.Type, varName, opts, typeRef)
return false
}
info := marshalForTypeWithCycleCheck(param.Type, opts, typeRef)
readExpr := stubDataReadExpr(info.ReadExpr)
if readExpr == "" {
goType := resolveTypeRef(typeRef, param.Type)
f.P("\t\tvar %s %s", varName, goType)
return false
}
isNullable := hasAnnotation(param.Type.Annots, "nullable")
if strings.Contains(info.ReadExpr, ".UnmarshalParcel") {
goType := resolveTypeRef(typeRef, param.Type)
// Parcelable: read null indicator, then unmarshal.
// Use a block scope to avoid _nullInd redeclaration across
// multiple parcelable params.
f.P("\t\tvar %s %s", varName, goType)
f.P("\t\t{")
f.P("\t\t\t_nullInd, _err := _data.ReadInt32()")
f.P("\t\t\tif _err != nil {")
f.P("\t\t\t\treturn nil, _err")
f.P("\t\t\t}")
f.P("\t\t\tif _nullInd != 0 {")
if isNullable && len(goType) > 0 && goType[0] == '*' {
// @nullable parcelable: allocate the struct before
// unmarshaling to avoid nil pointer dereference. When
// _nullInd == 0 the variable stays nil, which is correct.
baseType := goType[1:]
f.P("\t\t\t\t%s = new(%s)", varName, baseType)
}
f.P("\t\t\t\tif _err = %s.UnmarshalParcel(_data); _err != nil {", varName)
f.P("\t\t\t\t\treturn nil, _err")
f.P("\t\t\t\t}")
f.P("\t\t\t}")
f.P("\t\t}")
// _err was declared inside a block scope, so it does not affect
// the outer scope.
return false
}
if info.IsInterface {
// Read the binder handle and wrap it in a typed proxy.
// Stubs don't have a transport or identity, so pass nil/zero.
goType := resolveTypeRef(typeRef, param.Type)
// Go interfaces are inherently nullable (nil-able), so strip
// the pointer from @nullable interface types like *IFoo.
goType = strings.TrimPrefix(goType, "*")
proxyConstructor := interfaceProxyConstructor(typeRef, param.Type)
f.P("\t\tvar %s %s", varName, goType)
f.P("\t\t{")
f.P("\t\t\t_%sHandle, _err := _data.ReadStrongBinder()", param.ParamName)
f.P("\t\t\tif _err != nil {")
f.P("\t\t\t\treturn nil, _err")
f.P("\t\t\t}")
f.P("\t\t\t%s = %s(binder.NewProxyBinder(s.Transport, binder.CallerIdentity{}, _%sHandle))", varName, proxyConstructor, param.ParamName)
f.P("\t\t}")
// _err was declared inside a block scope, so it does not affect
// the outer scope.
return false
}
if info.IsIBinder {
// Read a raw binder handle and wrap it in a ProxyBinder.
// Stubs don't have a transport or identity, so pass nil/zero.
goType := resolveTypeRef(typeRef, param.Type)
f.P("\t\tvar %s %s", varName, goType)
f.P("\t\t{")
f.P("\t\t\t_%sHandle, _err := _data.ReadStrongBinder()", param.ParamName)
f.P("\t\t\tif _err != nil {")
f.P("\t\t\t\treturn nil, _err")
f.P("\t\t\t}")
f.P("\t\t\t%s = binder.NewProxyBinder(s.Transport, binder.CallerIdentity{}, _%sHandle)", varName, param.ParamName)
f.P("\t\t}")
// _err was declared inside a block scope, so it does not affect
// the outer scope.
return false
}
if info.NeedsCast {
goType := resolveTypeRef(typeRef, param.Type)
rawVar := "_raw_" + sanitizeGoIdent(param.ParamName)
// rawVar is always new, so := works regardless of errDeclared.
f.P("\t\t%s, _err := %s", rawVar, readExpr)
f.P("\t\tif _err != nil {")
f.P("\t\t\treturn nil, _err")
f.P("\t\t}")
if isNullable && len(goType) > 0 && goType[0] == '*' {
baseType := goType[1:]
f.P("\t\t_%s := %s(%s)", sanitizeGoIdent(param.ParamName), baseType, rawVar)
f.P("\t\t%s := &_%s", varName, sanitizeGoIdent(param.ParamName))
} else {
f.P("\t\t%s := %s(%s)", varName, goType, rawVar)
}
return true
}
goType := resolveTypeRef(typeRef, param.Type)
if isNullable && len(goType) > 0 && goType[0] == '*' {
// Nullable non-cast type: read value, then take its address
// to match the pointer-typed interface parameter.
rawVar := "_raw_" + sanitizeGoIdent(param.ParamName)
f.P("\t\t%s, _err := %s", rawVar, readExpr)
f.P("\t\tif _err != nil {")
f.P("\t\t\treturn nil, _err")
f.P("\t\t}")
f.P("\t\t%s := &%s", varName, rawVar)
return true
}
f.P("\t\t%s, _err := %s", varName, readExpr)
f.P("\t\tif _err != nil {")
f.P("\t\t\treturn nil, _err")
f.P("\t\t}")
// varName is always new, so := always works.
return true
}
// writeStubReadArrayParam generates code to read an array or List parameter
// from the data parcel into a local variable inside a stub OnTransaction case.
// All intermediate errors are declared in a block scope so they do not
// affect the outer _err variable.
func writeStubReadArrayParam(
f *GoFile,
ts *parser.TypeSpecifier,
varName string,
opts GenOptions,
typeRef *TypeRefResolver,
) {
goType := resolveTypeRef(typeRef, ts)
elemType := elementTypeSpec(ts)
// Compact byte[] uses ReadByteArray instead of per-element reads.
if elemType.Name == "byte" {
f.P("\t\tvar %s %s", varName, goType)
f.P("\t\t{")
f.P("\t\t\t_bytes, _err := _data.ReadByteArray()")
f.P("\t\t\tif _err != nil {")
f.P("\t\t\t\treturn nil, _err")
f.P("\t\t\t}")
f.P("\t\t\t%s = _bytes", varName)
f.P("\t\t}")
return
}
elemInfo := marshalForTypeWithCycleCheck(elemType, opts, typeRef)
elemReadExpr := stubDataReadExpr(elemInfo.ReadExpr)
f.P("\t\tvar %s %s", varName, goType)
f.P("\t\t{")
f.P("\t\t\t_count, _err := _data.ReadInt32()")
f.P("\t\t\tif _err != nil {")
f.P("\t\t\t\treturn nil, _err")
f.P("\t\t\t}")
f.P("\t\t\tif _count > 1000000 {")
f.P("\t\t\t\treturn nil, fmt.Errorf(\"array count too large: %%d\", _count)")
f.P("\t\t\t}")
f.P("\t\t\tif _count >= 0 {")
f.P("\t\t\t\t%s = make(%s, _count)", varName, goType)
if elemReadExpr != "" {
f.P("\t\t\t\tfor _i := int32(0); _i < _count; _i++ {")
switch {
case strings.Contains(elemInfo.ReadExpr, ".UnmarshalParcel"):
// Parcelable element: read null indicator, then unmarshal.
f.P("\t\t\t\t\tif _, _err = _data.ReadInt32(); _err != nil {")
f.P("\t\t\t\t\t\treturn nil, _err")
f.P("\t\t\t\t\t}")
f.P("\t\t\t\t\tif _err = %s[_i].UnmarshalParcel(_data); _err != nil {", varName)
f.P("\t\t\t\t\t\treturn nil, _err")
f.P("\t\t\t\t\t}")
case elemInfo.IsInterface:
proxyConstructor := interfaceProxyConstructor(typeRef, elemType)
f.P("\t\t\t\t\t_handle, _err := %s", elemReadExpr)
f.P("\t\t\t\t\tif _err != nil {")
f.P("\t\t\t\t\t\treturn nil, _err")
f.P("\t\t\t\t\t}")
f.P("\t\t\t\t\t%s[_i] = %s(binder.NewProxyBinder(s.Transport, binder.CallerIdentity{}, _handle))", varName, proxyConstructor)
case elemInfo.IsIBinder:
f.P("\t\t\t\t\t_handle, _err := %s", elemReadExpr)
f.P("\t\t\t\t\tif _err != nil {")
f.P("\t\t\t\t\t\treturn nil, _err")
f.P("\t\t\t\t\t}")
f.P("\t\t\t\t\t%s[_i] = binder.NewProxyBinder(s.Transport, binder.CallerIdentity{}, _handle)", varName)
case elemInfo.NeedsCast:
elemGoType := resolveTypeRef(typeRef, elemType)
f.P("\t\t\t\t\t_raw, _err := %s", elemReadExpr)
f.P("\t\t\t\t\tif _err != nil {")
f.P("\t\t\t\t\t\treturn nil, _err")
f.P("\t\t\t\t\t}")
f.P("\t\t\t\t\t%s[_i] = %s(_raw)", varName, elemGoType)
default:
f.P("\t\t\t\t\t%s[_i], _err = %s", varName, elemReadExpr)
f.P("\t\t\t\t\tif _err != nil {")
f.P("\t\t\t\t\t\treturn nil, _err")
f.P("\t\t\t\t\t}")
}
f.P("\t\t\t\t}")
}
f.P("\t\t\t}")
f.P("\t\t}")
}
// writeStubReadMapParam generates code to read a Map parameter from the
// data parcel into a local variable inside a stub OnTransaction case.
func writeStubReadMapParam(
f *GoFile,
ts *parser.TypeSpecifier,
varName string,
opts GenOptions,
typeRef *TypeRefResolver,
) {
goType := resolveTypeRef(typeRef, ts)
keyType := mapKeyTypeSpec(ts)
valType := mapValTypeSpec(ts)
keyInfo := marshalForTypeWithCycleCheck(keyType, opts, typeRef)
valInfo := marshalForTypeWithCycleCheck(valType, opts, typeRef)
keyReadExpr := stubDataReadExpr(keyInfo.ReadExpr)
valReadExpr := stubDataReadExpr(valInfo.ReadExpr)
f.P("\t\tvar %s %s", varName, goType)
f.P("\t\t{")
f.P("\t\t\t_mapCount, _err := _data.ReadInt32()")
f.P("\t\t\tif _err != nil {")
f.P("\t\t\t\treturn nil, _err")
f.P("\t\t\t}")
f.P("\t\t\tif _mapCount >= 0 {")
f.P("\t\t\t\t%s = make(%s, _mapCount)", varName, goType)
valIsList := valType.IsArray || valType.Name == "List"
keyIsList := keyType.IsArray || keyType.Name == "List"
if (keyReadExpr != "" || keyIsList) && (valReadExpr != "" || valIsList) {
f.P("\t\t\t\tfor _mi := int32(0); _mi < _mapCount; _mi++ {")
if keyIsList {
writeMapReadArrayElem(f, keyType, "_mk", "\t\t\t\t\t", opts, typeRef, "_data", "return nil, _err")
} else {
writeStubMapReadElem(f, keyInfo, keyReadExpr, keyType, "_mk", "\t\t\t\t\t", typeRef, "k")
}
if valIsList {
writeMapReadArrayElem(f, valType, "_mv", "\t\t\t\t\t", opts, typeRef, "_data", "return nil, _err")
} else {
writeStubMapReadElem(f, valInfo, valReadExpr, valType, "_mv", "\t\t\t\t\t", typeRef, "v")
}
f.P("\t\t\t\t\t%s[_mk] = _mv", varName)
f.P("\t\t\t\t}")
}
f.P("\t\t\t}")
f.P("\t\t}")
}
// writeStubMapReadElem writes the code to read a single map element (key or
// value) into a local variable within a stub's OnTransaction handler.
// Unlike the proxy-side writeMapReadElem, error returns use (nil, _err)
// since stubs return (*parcel.Parcel, error).
// rawPrefix disambiguates the intermediate _raw variable when both key and
// value use NeedsCast (e.g., "k" produces _rawK, "v" produces _rawV).
func writeStubMapReadElem(
f *GoFile,
info MarshalInfo,
readExpr string,
ts *parser.TypeSpecifier,
varName string,
indent string,
typeRef *TypeRefResolver,
rawPrefix string,
) {
switch {
case strings.Contains(info.ReadExpr, ".UnmarshalParcel"):
goType := resolveTypeRef(typeRef, ts)
f.P("%svar %s %s", indent, varName, goType)
f.P("%sif _, _err = _data.ReadInt32(); _err != nil {", indent)
f.P("%s\treturn nil, _err", indent)
f.P("%s}", indent)
f.P("%sif _err = %s.UnmarshalParcel(_data); _err != nil {", indent, varName)
f.P("%s\treturn nil, _err", indent)
f.P("%s}", indent)
case info.NeedsCast:
goType := resolveTypeRef(typeRef, ts)
rawVar := fmt.Sprintf("_raw%s", strings.ToUpper(rawPrefix[:1])+rawPrefix[1:])
f.P("%s%s, _err := %s", indent, rawVar, readExpr)
f.P("%sif _err != nil {", indent)
f.P("%s\treturn nil, _err", indent)
f.P("%s}", indent)
f.P("%s%s := %s(%s)", indent, varName, goType, rawVar)
default:
f.P("%s%s, _err := %s", indent, varName, readExpr)
f.P("%sif _err != nil {", indent)
f.P("%s\treturn nil, _err", indent)
f.P("%s}", indent)
}
}
// writeStubWriteReturn generates code to write a return value to the
// reply parcel.
func writeStubWriteReturn(
f *GoFile,
retType *parser.TypeSpecifier,
opts GenOptions,
typeRef *TypeRefResolver,
) {
if retType.IsArray || retType.Name == "List" {
elemType := elementTypeSpec(retType)
// AIDL uses compact writeByteArray for byte[], not per-element.
if elemType.Name == "byte" {
f.P("\t\t_reply.WriteByteArray(_result)")
return
}
elemInfo := marshalForTypeWithCycleCheck(elemType, opts, typeRef)
f.P("\t\tif _result == nil {")
f.P("\t\t\t_reply.WriteInt32(-1)")
f.P("\t\t} else {")
f.P("\t\t\t_reply.WriteInt32(int32(len(_result)))")
if elemInfo.WriteExpr != "" {
f.P("\t\t\tfor _, _item := range _result {")
writeExpr := fmt.Sprintf(elemInfo.WriteExpr, "_item")
writeExpr = strings.ReplaceAll(writeExpr, "_data", "_reply")
switch {
case strings.Contains(elemInfo.WriteExpr, ".MarshalParcel"):
f.P("\t\t\t\t_reply.WriteInt32(1)")
f.P("\t\t\t\tif _err := %s; _err != nil {", writeExpr)
f.P("\t\t\t\t\treturn nil, _err")
f.P("\t\t\t\t}")
case elemInfo.IsInterface:
f.P("\t\t\t\tbinder.WriteBinderToParcel(ctx, _reply, _item.AsBinder(), s.Transport)")
case elemInfo.IsIBinder:
f.P("\t\t\t\tbinder.WriteBinderToParcel(ctx, _reply, _item, s.Transport)")
default:
f.P("\t\t\t\t%s", writeExpr)
}
f.P("\t\t\t}")
}
f.P("\t\t}")
return
}
if retType.Name == "Map" {
keyType := mapKeyTypeSpec(retType)
valType := mapValTypeSpec(retType)
keyInfo := marshalForTypeWithCycleCheck(keyType, opts, typeRef)
valInfo := marshalForTypeWithCycleCheck(valType, opts, typeRef)
f.P("\t\tif _result == nil {")
f.P("\t\t\t_reply.WriteInt32(-1)")
f.P("\t\t} else {")
f.P("\t\t\t_reply.WriteInt32(int32(len(_result)))")
valIsList := valType.IsArray || valType.Name == "List"
keyIsList := keyType.IsArray || keyType.Name == "List"
if keyInfo.WriteExpr != "" || keyIsList || valInfo.WriteExpr != "" || valIsList {
f.P("\t\t\tfor _k, _v := range _result {")
keyVar := mapRangeVarWithAssertion("_k", keyType, retType, 0, typeRef)
valVar := mapRangeVarWithAssertion("_v", valType, retType, 1, typeRef)
stubErrReturn := "return nil, _err"
if keyIsList {
writeMapWriteArrayElem(f, keyType, keyVar, "\t\t\t\t", opts, typeRef, "_reply", stubErrReturn)
} else {
writeKeyExpr := fmt.Sprintf(keyInfo.WriteExpr, keyVar)
writeKeyExpr = strings.ReplaceAll(writeKeyExpr, "_data", "_reply")
writeMapElemExpr(f, keyInfo, writeKeyExpr, stubErrReturn, "\t\t\t\t", "_reply", "s.Transport", keyVar)
}
if valIsList {
writeMapWriteArrayElem(f, valType, valVar, "\t\t\t\t", opts, typeRef, "_reply", stubErrReturn)
} else {
writeValExpr := fmt.Sprintf(valInfo.WriteExpr, valVar)
writeValExpr = strings.ReplaceAll(writeValExpr, "_data", "_reply")
writeMapElemExpr(f, valInfo, writeValExpr, stubErrReturn, "\t\t\t\t", "_reply", "s.Transport", valVar)
}
f.P("\t\t\t}")
}
f.P("\t\t}")
return
}
info := marshalForTypeWithCycleCheck(retType, opts, typeRef)
writeExpr := stubReplyWriteExpr(info.WriteExpr)
if writeExpr == "" {
f.P("\t\t_ = _result")
return
}
if strings.Contains(info.WriteExpr, ".MarshalParcel") {
// Parcelable return: write non-null indicator + marshal.
f.P("\t\t_reply.WriteInt32(1)")
marshalExpr := strings.ReplaceAll(info.WriteExpr, "_data", "_reply")
marshalExpr = fmt.Sprintf(marshalExpr, "_result")
f.P("\t\tif _err := %s; _err != nil {", marshalExpr)
f.P("\t\t\treturn nil, _err")
f.P("\t\t}")