-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathremote.go
More file actions
686 lines (585 loc) · 21.1 KB
/
remote.go
File metadata and controls
686 lines (585 loc) · 21.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
//go:build linux
package main
import (
"context"
"encoding/binary"
"fmt"
"log"
"os"
"strconv"
"strings"
"sync"
"unicode/utf16"
"github.com/electricbubble/gadb"
"github.com/facebookincubator/go-belt/tool/logger"
"github.com/mark3labs/mcp-go/server"
"github.com/spf13/cobra"
"github.com/AndroidGoLab/binder/binder"
"github.com/AndroidGoLab/binder/binder/versionaware"
"github.com/AndroidGoLab/binder/interop/gadb/proxy"
"github.com/AndroidGoLab/binder/parcel"
"github.com/AndroidGoLab/binder/servicemanager"
)
// runRemoteMode creates a gadb proxy Session to the device, builds a
// remote-aware ServiceManager, and serves the same MCP tools as device
// mode over stdio.
func runRemoteMode(
cmd *cobra.Command,
_ []string,
) (_err error) {
ctx := cmd.Context()
logger.Tracef(ctx, "runRemoteMode")
defer func() { logger.Tracef(ctx, "/runRemoteMode: %v", _err) }()
serial, err := cmd.Flags().GetString("serial")
if err != nil {
return fmt.Errorf("reading --serial: %w", err)
}
// Auto-discover device serial when not specified.
if serial == "" {
serial, err = discoverDeviceSerial()
if err != nil {
return fmt.Errorf("auto-discovering device: %w", err)
}
logger.Debugf(ctx, "auto-discovered device serial: %s", serial)
}
// Detect the device's API level via adb getprop.
apiLevel, err := detectRemoteAPILevel(serial)
if err != nil {
return fmt.Errorf("detecting API level: %w", err)
}
logger.Debugf(ctx, "detected device API level: %d", apiLevel)
// Create the proxy session: cross-compile daemon, push, start, forward, connect.
logger.Debugf(ctx, "creating proxy session to device %s", serial)
session, err := proxy.NewSession(ctx, serial)
if err != nil {
return fmt.Errorf("creating proxy session: %w", err)
}
defer func() {
logger.Debugf(ctx, "closing proxy session")
if closeErr := session.Close(ctx); closeErr != nil {
logger.Warnf(ctx, "closing proxy session: %v", closeErr)
}
}()
rt := session.Transport()
// Resolve the version table by probing the device through the daemon.
// Multiple revisions may exist per API level with different transaction
// codes; probing determines which revision matches the device.
table, err := probeRemoteVersionTable(ctx, rt, apiLevel)
if err != nil {
return err
}
sm := newRemoteServiceManager(rt, table)
tools := &ToolSet{sm: sm}
mcpServer := server.NewMCPServer(
"binder-mcp",
"1.0.0",
server.WithToolCapabilities(false),
server.WithRecovery(),
)
tools.Register(mcpServer)
RegisterShellTools(mcpServer)
logger.Debugf(ctx, "serving MCP over stdio (remote mode)")
errLogger := log.New(os.Stderr, "binder-mcp: ", log.LstdFlags)
return server.ServeStdio(mcpServer, server.WithErrorLogger(errLogger))
}
// discoverDeviceSerial connects to the ADB server and returns the serial
// of the first connected device.
func discoverDeviceSerial() (string, error) {
client, err := gadb.NewClient()
if err != nil {
return "", fmt.Errorf("connecting to ADB server: %w", err)
}
devices, err := client.DeviceList()
if err != nil {
return "", fmt.Errorf("listing devices: %w", err)
}
if len(devices) == 0 {
return "", fmt.Errorf("no devices connected")
}
return devices[0].Serial(), nil
}
// detectRemoteAPILevel queries the device's ro.build.version.sdk property
// via adb shell to determine the Android API level.
func detectRemoteAPILevel(serial string) (int, error) {
client, err := gadb.NewClient()
if err != nil {
return 0, fmt.Errorf("connecting to ADB server: %w", err)
}
devices, err := client.DeviceList()
if err != nil {
return 0, fmt.Errorf("listing devices: %w", err)
}
for _, dev := range devices {
if dev.Serial() != serial {
continue
}
output, err := dev.RunShellCommand("getprop", "ro.build.version.sdk")
if err != nil {
return 0, fmt.Errorf("getprop ro.build.version.sdk: %w", err)
}
level, err := strconv.Atoi(strings.TrimSpace(output))
if err != nil {
return 0, fmt.Errorf("parsing API level %q: %w", output, err)
}
return level, nil
}
return 0, fmt.Errorf("device %q not found", serial)
}
// probeRemoteVersionTable determines the correct version table for the
// device by trying each candidate revision's listServices transaction code
// through the remote transport. The first revision that produces a valid
// reply (status OK + parseable count) wins.
func probeRemoteVersionTable(
ctx context.Context,
rt *proxy.RemoteTransport,
apiLevel int,
) (versionaware.VersionTable, error) {
// Deduplicate listServices codes across revisions: if two revisions
// share the same code, probing once suffices.
type candidate struct {
revision versionaware.Revision
compiled versionaware.CompiledTable
code binder.TransactionCode
}
var candidates []candidate
seenCodes := map[binder.TransactionCode]bool{}
for _, level := range []int{apiLevel, versionaware.DefaultAPILevel} {
for _, rev := range versionaware.Revisions[level] {
compiled, ok := versionaware.Tables[rev]
if !ok {
continue
}
code := compiled.Resolve(serviceManagerDescriptor, "listServices")
if code == 0 || seenCodes[code] {
continue
}
seenCodes[code] = true
candidates = append(candidates, candidate{rev, compiled, code})
}
}
for _, c := range candidates {
if probeListServices(ctx, rt, c.code) {
logger.Debugf(ctx, "matched revision %s (listServices code %d)", c.revision, c.code)
return c.compiled.ToVersionTable(), nil
}
logger.Debugf(ctx, "revision %s (listServices code %d) did not match", c.revision, c.code)
}
return nil, fmt.Errorf(
"no compiled version table matched device at API level %d (supported: %v)",
apiLevel, supportedLevels(),
)
}
// probeListServices sends a listServices transaction with the given code
// and returns true if the reply contains a valid status and service count.
func probeListServices(
ctx context.Context,
rt *proxy.RemoteTransport,
code binder.TransactionCode,
) bool {
data := parcel.New()
defer data.Recycle()
data.WriteInterfaceToken(serviceManagerDescriptor)
data.WriteInt32(dumpFlagPriorityAll)
reply, err := rt.Transact(ctx, serviceManagerDescriptor, uint32(code), 0, data)
if err != nil {
return false
}
defer reply.Recycle()
if err := binder.ReadStatus(reply); err != nil {
return false
}
count, err := reply.ReadInt32()
if err != nil {
return false
}
return count > 0
}
// supportedLevels returns the API levels that have compiled version tables.
func supportedLevels() []int {
levels := make([]int, 0, len(versionaware.Revisions))
for level := range versionaware.Revisions {
levels = append(levels, level)
}
return levels
}
const (
serviceManagerDescriptor = "android.os.IServiceManager"
// dumpFlagPriorityAll combines all priority flags, matching the
// device-mode ServiceManager constant.
dumpFlagPriorityAll = int32(1 | 2 | 4 | 8)
// maxRemoteServiceCount guards against corrupted reply parcels.
maxRemoteServiceCount = int32(10000)
)
// remoteServiceManager implements ServiceLookup by sending binder
// transactions through a RemoteTransport to the device-side daemon.
//
// Descriptor discovery is lazy: CheckService returns a remoteIBinder
// immediately, and the AIDL descriptor is resolved on demand (via the
// well-known map or INTERFACE_TRANSACTION probing). This keeps
// operations like list_services fast.
type remoteServiceManager struct {
rt *proxy.RemoteTransport
table versionaware.VersionTable
// descriptorCache maps service name → AIDL descriptor. Populated
// lazily and shared across all remoteIBinder instances.
mu sync.Mutex
descriptorCache map[servicemanager.ServiceName]string
}
func newRemoteServiceManager(
rt *proxy.RemoteTransport,
table versionaware.VersionTable,
) *remoteServiceManager {
return &remoteServiceManager{
rt: rt,
table: table,
descriptorCache: make(map[servicemanager.ServiceName]string),
}
}
func (rsm *remoteServiceManager) ListServices(
ctx context.Context,
) (_ []servicemanager.ServiceName, _err error) {
logger.Tracef(ctx, "remoteServiceManager.ListServices")
defer func() { logger.Tracef(ctx, "/remoteServiceManager.ListServices: %v", _err) }()
code := rsm.table.Resolve(serviceManagerDescriptor, "listServices")
if code == 0 {
return nil, fmt.Errorf("cannot resolve listServices transaction code")
}
data := parcel.New()
defer data.Recycle()
data.WriteInterfaceToken(serviceManagerDescriptor)
data.WriteInt32(dumpFlagPriorityAll)
reply, err := rsm.rt.Transact(ctx, serviceManagerDescriptor, uint32(code), 0, data)
if err != nil {
return nil, fmt.Errorf("listServices: %w", err)
}
defer reply.Recycle()
if err := binder.ReadStatus(reply); err != nil {
return nil, fmt.Errorf("listServices: %w", err)
}
count, err := reply.ReadInt32()
if err != nil {
return nil, fmt.Errorf("listServices: reading count: %w", err)
}
if count < 0 || count > maxRemoteServiceCount {
return nil, fmt.Errorf("listServices: invalid service count: %d", count)
}
services := make([]servicemanager.ServiceName, 0, count)
for i := int32(0); i < count; i++ {
name, err := reply.ReadString16()
if err != nil {
return nil, fmt.Errorf("listServices: reading service %d: %w", i, err)
}
services = append(services, servicemanager.ServiceName(name))
}
return services, nil
}
func (rsm *remoteServiceManager) CheckService(
ctx context.Context,
name servicemanager.ServiceName,
) (_ binder.IBinder, _err error) {
logger.Tracef(ctx, "remoteServiceManager.CheckService(%q)", name)
defer func() { logger.Tracef(ctx, "/remoteServiceManager.CheckService(%q): %v", name, _err) }()
// Verify the service is registered via CheckService RPC.
registered, err := rsm.isServiceRegistered(ctx, name)
if err != nil {
return nil, err
}
if !registered {
return nil, nil
}
// Return a lazy IBinder. Descriptor discovery happens on first
// Transact/ResolveCode call, not here. This keeps bulk operations
// like list_services (which call CheckService + IsAlive for each
// service) fast.
return &remoteIBinder{
rsm: rsm,
serviceName: name,
}, nil
}
// isServiceRegistered calls CheckService on the remote ServiceManager and
// returns true if a non-null binder handle was returned.
func (rsm *remoteServiceManager) isServiceRegistered(
ctx context.Context,
name servicemanager.ServiceName,
) (bool, error) {
code := rsm.table.Resolve(serviceManagerDescriptor, "checkService")
if code == 0 {
return false, fmt.Errorf("cannot resolve checkService transaction code")
}
data := parcel.New()
defer data.Recycle()
data.WriteInterfaceToken(serviceManagerDescriptor)
data.WriteString16(string(name))
reply, err := rsm.rt.Transact(ctx, serviceManagerDescriptor, uint32(code), 0, data)
if err != nil {
return false, fmt.Errorf("checkService(%q): %w", name, err)
}
defer reply.Recycle()
if err := binder.ReadStatus(reply); err != nil {
return false, fmt.Errorf("checkService(%q): %w", name, err)
}
_, ok, err := reply.ReadNullableStrongBinder()
if err != nil {
return false, fmt.Errorf("checkService(%q): reading binder: %w", name, err)
}
return ok, nil
}
// resolveDescriptor returns the cached AIDL descriptor for a service name,
// or discovers it via the well-known map and INTERFACE_TRANSACTION probing.
func (rsm *remoteServiceManager) resolveDescriptor(
ctx context.Context,
name servicemanager.ServiceName,
) (string, error) {
rsm.mu.Lock()
defer rsm.mu.Unlock()
if desc, ok := rsm.descriptorCache[name]; ok {
return desc, nil
}
desc, err := rsm.discoverDescriptor(ctx, name)
if err != nil {
return "", err
}
rsm.descriptorCache[name] = desc
return desc, nil
}
// discoverDescriptor finds the AIDL interface descriptor for a named service.
// Uses two strategies:
// 1. Well-known service name → descriptor map (instant).
// 2. INTERFACE_TRANSACTION probing for well-known descriptors only.
//
// Does not try all 1750+ descriptors from the version table — that would
// be prohibitively slow over the network.
func (rsm *remoteServiceManager) discoverDescriptor(
ctx context.Context,
name servicemanager.ServiceName,
) (string, error) {
// Strategy 1: well-known map.
if desc, ok := wellKnownDescriptors[string(name)]; ok {
logger.Debugf(ctx, "descriptor for %q: well-known %q", name, desc)
return desc, nil
}
// Strategy 2: probe INTERFACE_TRANSACTION for a subset of likely
// descriptors. The daemon caches resolved descriptors, so each probe
// is a single round-trip after the first scan.
for _, desc := range descriptorGuesses(string(name)) {
probed, err := probeInterfaceTransaction(ctx, rsm.rt, desc)
if err != nil {
continue
}
if probed == desc {
logger.Debugf(ctx, "descriptor for %q: probed %q", name, desc)
return desc, nil
}
}
return "", fmt.Errorf("cannot discover AIDL descriptor for service %q", name)
}
// probeInterfaceTransaction sends INTERFACE_TRANSACTION to the daemon for
// the given descriptor and returns the descriptor string from the reply.
func probeInterfaceTransaction(
ctx context.Context,
rt *proxy.RemoteTransport,
descriptor string,
) (string, error) {
data := parcel.New()
defer data.Recycle()
reply, err := rt.Transact(
ctx,
descriptor,
uint32(binder.InterfaceTransaction),
0,
data,
)
if err != nil {
return "", err
}
defer reply.Recycle()
return reply.ReadString16()
}
// descriptorGuesses generates a small set of likely AIDL descriptors for a
// service name based on Android naming conventions.
func descriptorGuesses(serviceName string) []string {
// Common patterns: "foo" → "android.os.IFooManager" etc.
// Only try a handful of plausible patterns.
base := strings.ReplaceAll(serviceName, "_", "")
upper := strings.ToUpper(base[:1]) + base[1:]
return []string{
"android.os.I" + upper + "Manager",
"android.os.I" + upper + "Service",
"android.os.I" + upper,
"android.app.I" + upper + "Manager",
"android.app.I" + upper + "Service",
"android.app.I" + upper,
}
}
// wellKnownDescriptors maps Android service names to their AIDL interface
// descriptors. Covers the most commonly used system services.
var wellKnownDescriptors = map[string]string{
"accessibility": "android.view.accessibility.IAccessibilityManager",
"account": "android.accounts.IAccountManager",
"activity": "android.app.IActivityManager",
"activity_task": "android.app.IActivityTaskManager",
"alarm": "android.app.IAlarmManager",
"appops": "android.app.IAppOpsService",
"audio": "android.media.IAudioService",
"autofill": "android.view.autofill.IAutoFillManager",
"battery": "android.os.IBatteryPropertiesRegistrar",
"batterystats": "com.android.internal.app.IBatteryStats",
"bluetooth_manager": "android.bluetooth.IBluetoothManager",
"camera": "android.hardware.ICameraService",
"clipboard": "android.content.IClipboard",
"connectivity": "android.net.IConnectivityManager",
"content": "android.content.IContentService",
"device_policy": "android.app.admin.IDevicePolicyManager",
"display": "android.hardware.display.IDisplayManager",
"dreams": "android.service.dreams.IDreamManager",
"dropbox": "com.android.internal.os.IDropBoxManagerService",
"input": "android.hardware.input.IInputManager",
"input_method": "com.android.internal.view.IInputMethodManager",
"iphonesubinfo": "com.android.internal.telephony.IPhoneSubInfo",
"isms": "com.android.internal.telephony.ISms",
"jobscheduler": "android.app.job.IJobScheduler",
"location": "android.location.ILocationManager",
"media.audio_policy": "android.media.IAudioPolicyService",
"media.camera": "android.hardware.ICameraService",
"media_session": "android.media.session.ISessionManager",
"mount": "android.os.storage.IStorageManager",
"netd": "android.os.INetworkManagementService",
"network_management": "android.os.INetworkManagementService",
"notification": "android.app.INotificationManager",
"package": "android.content.pm.IPackageManager",
"permission": "android.os.IPermissionController",
"phone": "com.android.internal.telephony.ITelephony",
"power": "android.os.IPowerManager",
"role": "android.app.role.IRoleManager",
"sensorservice": "android.gui.ISensorServer",
"statusbar": "com.android.internal.statusbar.IStatusBarService",
"telecom": "com.android.internal.telecom.ITelecomService",
"telephony.registry": "com.android.internal.telephony.ITelephonyRegistry",
"uimode": "android.app.IUiModeManager",
"usb": "android.hardware.usb.IUsbManager",
"user": "android.os.IUserManager",
"vibrator": "android.os.IVibratorService",
"vibrator_manager": "android.os.IVibratorManagerService",
"wallpaper": "android.app.IWallpaperManager",
"wifi": "android.net.wifi.IWifiManager",
"wifip2p": "android.net.wifi.p2p.IWifiP2pManager",
"window": "android.view.IWindowManager",
}
// remoteIBinder implements binder.IBinder by routing all transactions
// through the RemoteTransport using the service's AIDL descriptor.
//
// Descriptor discovery is lazy: the descriptor is resolved on the first
// call to Transact or ResolveCode, not at construction time. IsAlive
// returns true unconditionally since the service was just confirmed
// registered via CheckService.
type remoteIBinder struct {
rsm *remoteServiceManager
serviceName servicemanager.ServiceName
// descriptor is populated lazily by ensureDescriptor.
once sync.Once
descriptor string
descErr error
}
// ensureDescriptor triggers lazy descriptor resolution.
func (b *remoteIBinder) ensureDescriptor(ctx context.Context) error {
b.once.Do(func() {
b.descriptor, b.descErr = b.rsm.resolveDescriptor(ctx, b.serviceName)
})
return b.descErr
}
func (b *remoteIBinder) Transact(
ctx context.Context,
code binder.TransactionCode,
flags binder.TransactionFlags,
data *parcel.Parcel,
) (_ *parcel.Parcel, _err error) {
logger.Tracef(ctx, "remoteIBinder.Transact(svc=%s, code=%d)", b.serviceName, code)
defer func() { logger.Tracef(ctx, "/remoteIBinder.Transact: %v", _err) }()
// For regular AIDL calls the parcel starts with an interface token
// containing the descriptor. Use it when available — it may differ
// from the service's own descriptor (e.g., querying a sub-interface).
if token := peekInterfaceToken(data); token != "" {
return b.rsm.rt.Transact(ctx, token, uint32(code), uint32(flags), data)
}
// Meta-transactions (PING, INTERFACE_TRANSACTION) carry no token.
// Resolve the service's descriptor to route through the daemon.
if err := b.ensureDescriptor(ctx); err != nil {
return nil, fmt.Errorf("resolving descriptor for %q: %w", b.serviceName, err)
}
return b.rsm.rt.Transact(ctx, b.descriptor, uint32(code), uint32(flags), data)
}
func (b *remoteIBinder) ResolveCode(
_ context.Context,
descriptor string,
method string,
) (binder.TransactionCode, error) {
code := b.rsm.table.Resolve(descriptor, method)
if code == 0 {
return 0, fmt.Errorf(
"remote: method %s.%s not found in version table",
descriptor, method,
)
}
return code, nil
}
func (b *remoteIBinder) Handle() uint32 {
return 0
}
// IsAlive returns true unconditionally. The service was confirmed
// registered by CheckService immediately before this IBinder was created.
// Sending a PING through the daemon would require the descriptor, which
// triggers lazy discovery — too expensive for bulk liveness checks.
func (b *remoteIBinder) IsAlive(_ context.Context) bool {
return true
}
func (b *remoteIBinder) LinkToDeath(_ context.Context, _ binder.DeathRecipient) error {
return fmt.Errorf("remote: LinkToDeath not supported")
}
func (b *remoteIBinder) UnlinkToDeath(_ context.Context, _ binder.DeathRecipient) error {
return fmt.Errorf("remote: UnlinkToDeath not supported")
}
func (b *remoteIBinder) Cookie() uintptr {
return 0
}
func (b *remoteIBinder) Transport() binder.VersionAwareTransport {
return nil
}
func (b *remoteIBinder) Identity() binder.CallerIdentity {
return binder.DefaultCallerIdentity()
}
var _ binder.IBinder = (*remoteIBinder)(nil)
// peekInterfaceToken extracts the AIDL descriptor from a parcel's
// interface token without consuming the parcel data. Returns "" if
// the parcel is too short or the token cannot be read.
//
// Interface token layout (all little-endian):
//
// offset 0: int32 strict-mode policy
// offset 4: int32 work-source UID
// offset 8: int32 vendor header
// offset 12: int32 char count (UTF-16 characters, excluding null terminator)
// offset 16: UTF-16LE encoded string
func peekInterfaceToken(p *parcel.Parcel) string {
if p == nil {
return ""
}
raw := p.Data()
// 4 int32 header fields = 16 bytes minimum.
if len(raw) < 16 {
return ""
}
charCount := int32(binary.LittleEndian.Uint32(raw[12:16]))
if charCount <= 0 || charCount > 1024 {
return ""
}
// UTF-16LE: (charCount + 1) * 2 bytes (+1 for null terminator).
strBytes := int(charCount+1) * 2
if len(raw) < 16+strBytes {
return ""
}
units := make([]uint16, charCount)
for i := range units {
units[i] = binary.LittleEndian.Uint16(raw[16+i*2:])
}
return string(utf16.Decode(units))
}