-
Notifications
You must be signed in to change notification settings - Fork 306
/
emulated_device.py
4064 lines (3504 loc) · 151 KB
/
emulated_device.py
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 2014 Google Inc. All Rights Reserved.
#
# 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.
"""Classes to interact with android emulator."""
import collections
import contextlib
import json
import logging
import os
import re
import shutil
import signal
import socket
import stat
import struct
import subprocess
import sys
import telnetlib
import tempfile
import threading
import time
import uuid
# pylint: disable=g-import-not-at-top
try:
from M2Crypto import X509
except ImportError as e:
# Initialize X509 to None, so that we don't get NameErrors while trying to
# boot up a device if users have not installed the X509 library.
X509 = collections.namedtuple('X509', ['FORMAT_PEM', 'FORMAT_DER'])
print ('If you want to add certificates to the emulator, Please install '
'MCrypt library using sudo apt-get install python-mcrypt .')
from absl import flags
import portpicker
from tools.android.emulator import resources
from google.apputils import stopwatch
from tools.android.emulator import common
from tools.android.emulator import emulator_meta_data_pb2
from tools.android.emulator import reporting
from tools.android.emulator import xserver
FLAGS = flags.FLAGS
flags.DEFINE_integer('data_partition_size', None, '[START ONLY] expand data '
'partition to a bigger size. The unit is in megabytes.')
flags.DEFINE_integer('long_press_timeout', None, 'Timeout for considering '
'press to be long.The unit is in millisecond.')
flags.DEFINE_bool('hardware_keyboard', True, 'Whether to connect hardware '
'keyboard to device.')
flags.DEFINE_bool('boost_dex2oat', False, 'Decrease dex2oat time. This could '
'hurt runtime performance.')
flags.DEFINE_integer('cores', 2, 'Cores number for emulated devices, only '
'meaningful for qemu2.')
flags.DEFINE_bool('skip_connect_device', False, 'Skip to connect device.')
flags.DEFINE_bool('dex2oat_on_cloud_enabled', False,
'Was Dex2oat run in cloud.')
flags.DEFINE_bool('enable_test_harness', True, 'Whether device should run in '
'test_harness mode: ro.test_harness=1')
LoadInfo = collections.namedtuple('LoadInfo', 'timestamp up_time idle_time')
Properties = collections.namedtuple('Properties', 'name value')
# speeds from:
# http://developer.android.com/guide/developing/devices/emulator.html#netspeed
# and
# http://chimera.labs.oreilly.com/books/1230000000545/ch07.html
NET_TYPE_TO_SPEED = {
'edge': '118.4:236.8',
'fastnet': 'full',
'gprs': '40.0:80.0',
'gsm': '14.4:14.4',
'hscsd': '14.4:43.2',
'hsdpa': '348.0:14400.0',
'umts': '128.0:1920.0'
}
NET_TYPE_TO_DELAY = {
'edge': '80:400',
'fastnet': 'none',
'gprs': '150:550',
'gsm': '300:1000',
'hscsd': 'none', # no data
'hsdpa': 'none', # no data
'umts': '35:200'
}
# HONEYCOMB has a bug where netcfg dhcp eth0
# will kill the adb connection permenantly
# luckily it does not need to dhcp on boot.
HONEYCOMB_SYSTEM_IMAGES = [
'google_inc_13',
'google_13',
'android_13']
PERMANENT_INSTALL_ERROR = [
'INSTALL_FAILED_INVALID_APK',
'INSTALL_FAILED_OLDER_SDK',
'INSTALL_FAILED_INSUFFICIENT_STORAGE',
'INSTALL_FAILED_NO_MATCHING_ABIS',
'INSTALL_FAILED_VERSION_DOWNGRADE',
'INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE',
'INSTALL_PARSE_FAILED_MANIFEST_MALFORMED']
INSTALL_FAILURE_REGEXP = re.compile(r'.*(INSTALL_FAILED_[a-zA-Z_]+).*',
re.MULTILINE | re.DOTALL)
_CORES_PROP = 'hw.cpu.ncore'
DIRECT_BOOT_PROP = 'persist.sys.emulate_fbe' # Emulate File-Based Encryption
# http://android.googlesource.com/platform/sdk/+/master/emulator/mksdcard/src/source/mksdcard.c#150
SD_CARD_UUID_OFFSET = 0x43
# The maximum time that near-zero before we give up on an install
INSTALL_IDLE_TIMEOUT_SECONDS = 120
def _InstallFailureType(output):
"""Attempts to extract an installation failure reason from the output.
Args:
output: output from an installation failure.
Returns:
Either the failure string or UNKNOWN.
"""
m = INSTALL_FAILURE_REGEXP.match(output)
if m:
return m.groups()[0]
return 'UNKNOWN'
# These services are not stopped at shutdown time.
# We depend on them to communicate with emulated devices.
SHUTDOWN_PROTECTED_SERVICES = ['waterfall', 'pipe_traverse', 'adbd']
AUTO_OPEN_GL = 'auto'
GUEST_OPEN_GL = 'guest'
HOST_OPEN_GL = 'host'
MESA_OPEN_GL = 'mesa'
NO_OPEN_GL = 'no_open_gl'
SWIFTSHADER_OPEN_GL = 'swiftshader'
SWIFTSHADER_INDIRECT = 'swiftshader_indirect'
OPEN_GL_DRIVERS = [AUTO_OPEN_GL, MESA_OPEN_GL, HOST_OPEN_GL, NO_OPEN_GL,
GUEST_OPEN_GL, SWIFTSHADER_OPEN_GL, SWIFTSHADER_INDIRECT]
SDCARD_SIZE_KEY = 'sdcard_size_mb'
SYSTEM_ABI_KEY = 'systemimage.abi'
API_LEVEL_KEY = 'androidversion.apilevel'
API_CODE_NAME = 'androidversion.codename'
HEAP_GROWTH_LIMIT_KEY = 'dalvik.vm.heapgrowthlimit'
EMULATOR_TYPE_KEY = 'ro.mobile_ninjas.emulator_type'
SENSITIVE_SYSTEM_IMAGE = 'sensitive.systemimage'
ADB_INSTALL_TIMEOUT_SECONDS = 90
ADB_SHORT_TIMEOUT_SECONDS = 20
_OPEN_TARBALL = 'OPEN_TARBALL'
_EXTRACT_TARBALL = 'EXTRACT_TARBALL'
_BOOT_COMPLETE_PRESENT = 'CHECK_BOOT_PROP'
_BOOT_COMPLETE_FAIL_SLEEP = 'CHECK_BOOT_PROP_FAIL_SLEEP'
_LAUNCHER_STARTED = 'CHECK_BOOT_PROP'
_LAUNCHER_STARTED_FAIL_SLEEP = 'CHECK_BOOT_PROP_FAIL_SLEEP'
_PIPE_TRAVERSAL_CHECK = 'PIPE_TRAVERSAL_CHECK'
_PIPE_TRAVERSAL_CHECK_FAIL_SLEEP = 'PIPE_TRAVERSAL_CHECK_FAIL_SLEEP'
_SNAPSHOT_COPY = 'SNAPSHOT_COPY'
_ADB_LISTENING_CHECK = 'ADB_LISTENING_CHECK'
_ADB_LISTENING_CHECK_FAIL_SLEEP = 'ADB_LISTENING_CHECK_FAIL_SLEEP'
_WATERFALL_LISTENING_CHECK = 'WATERFALL_LISTENING_CHECK'
_WATERFALL_LISTENING_CHECK_FAIL_SLEEP = 'WATERFALL_LISTENING_CHECK_FAIL_SLEEP'
_SDCARD_CREATE = 'SDCARD_CREATE'
_STAGE_DATA = 'STAGE_DATA'
_START_PROCESS = 'START_PROCESS'
_KILL_EMULATOR = 'KILL_EMULATOR'
_SPAWN_EMULATOR = 'SPAWN_EMULATOR'
_ADB_CONNECT = 'ADB_CONNECT'
_ADB_CONNECT_FAIL_SLEEP = 'ADB_CONNECT_FAIL_SLEEP'
_SYS_SERVER_CHECK = 'SYS_SERVER_CHECK'
_SYS_SERVER_CHECK_FAIL_SLEEP = 'SYS_SERVER_CHECK_FAIL_SLEEP'
_PM_CHECK = 'PM_CHECK'
_PM_CHECK_FAIL_SLEEP = 'PM_CHECK_FAIL_SLEEP'
_ENSURE_CACHED = 'ENSURE_CACHED'
_INSTALL_TASK = 'INSTALL_TASK'
_SD_CARD_MOUNT_CHECK = 'SD_CARD_MOUNT_CHECK'
_SD_CARD_MOUNT_CHECK_FAIL_SLEEP = 'SD_CARD_MOUNT_CHECK_FAIL_SLEEP'
_RAMDISK_MOD = 'RAMDISK_MOD'
_CHECK_DPI = 'CHECK_DPI'
_CHECK_DPI_FAIL_SLEEP = 'CHECK_DPI_FAIL_SLEEP'
EMULATOR_PID = 'emulator_process.pid'
_ANR_RE = re.compile(r'\w\/(am_(?:crash|anr|proc_died)).*\[(\w.*)\]')
_DEV_NULL = open('/dev/null')
_DENSITY_TVDPI = 213
# A quick way to get this list:
# Generate an avd which api level 19+
# ~/Android/Sdk/tools/android create avd -n K -t 16 --abi x86
# Run
# ~/Android/Sdk/tools/emulator -avd K -qemu -lcd-density 1
# It will tell you in error message.
# TODO: automatically update this list so we don't need to maintain it
# manually.
_BUCKET_DPI = [120, 160, 213, 240, 280, 320, 360, 400, 420, 480, 560, 640]
# Make sure it's sorted.
_BUCKET_DPI.sort()
# tvdpi is not part of the dpi bucket list
_BUCKET_DPI.remove(_DENSITY_TVDPI)
_DB_PATH = '/data/data/com.android.providers.settings/databases/settings.db'
_DEFAULT_QEMU_TELNET_PORT = 52222
_BOOTSTRAP_PKG = 'com.google.android.apps.common.testing.services.bootstrap'
_DEX2OAT = 'android_test_support/tools/android/emulator/daemon/dex2oat'
_BOOTSTRAP_PATH = 'android_test_support/tools/android/emulator/daemon/bootstrap.apk'
_FORWARDER_PATH = 'android_test_support/tools/android/emulator/support/waterfall/forward_bin'
_FORWARD_BIN = 'forward_bin'
_PORTS_PATH = 'android_test_support/tools/android/emulator/support/waterfall/ports_bin'
_PORTS_BIN = 'ports_bin'
_DEFAULT_BROADCAST_ACTION = 'ACTION_MOBILE_NINJAS_START'
_CONSOLE_TOKEN_DEVICE_PATH = '/data/console_token'
_MAX_CORES_NUM = 16
@flags.validator('cores')
def _CheckCoresFlag(cores):
"""Check cores flag value for validity."""
if cores < 1 or cores > _MAX_CORES_NUM:
raise flags.ValidationError(
'%d not a valid cores number[1 - %d]' % (cores, _MAX_CORES_NUM))
return True
class AndroidPlatform(object):
"""Used to find all the binaries offered in the android sdk."""
def __init__(self, android_sdk='third_party/java/android/android_sdk_linux'):
self.android_sdk = os.path.join('android_test_support', android_sdk)
self._android_platform_tools = os.path.join(self.android_sdk,
'platform-tools')
self.adb = None
self.emulator_x86 = None
self.emulator_arm = None
self.emulator_wrapper_launcher = None
self.empty_snapshot_fs = None
self.mksdcard = None
self.prepended_library_path = '' # prepended to the emulators lib path
self.base_emulator_path = '' # emulator binaries directory
self.emulator_support_lib_path = '' # shared libs the emu needs
self.xkb_path = '' # xkb stuff X/Qt need.
self.kvm_device = '/dev/kvm'
self.bios_files = None
self.bios_dir = None
self.real_adb = None
# Any screen resolution > 1280 x 800 won't boot without OpenGL.
# We consider such size resolution as big screen.
self.big_screen = False
def GetEmulator(self, arch_type, emulator_type):
"""Gets the Emulator Launcher based on the architecture."""
logging.info('Emulator type: %d', emulator_type)
if emulator_type == emulator_meta_data_pb2.EmulatorMetaDataPb.QEMU2:
return self.emulator_wrapper_launcher
if 'x86' == arch_type:
return self.emulator_x86
elif arch_type.startswith('arm'):
return self.emulator_arm
else:
raise Exception('Unknown arch: %s' % arch_type)
def MakeBiosDir(self, tmp_dir):
"""Creates a temp directory to hold bios files."""
if not self.bios_dir:
self.bios_dir = tmp_dir
if self.bios_files:
for bios_file in self.bios_files:
shutil.copy2(bios_file, self.bios_dir)
else:
emulator_dir = os.path.dirname(self.emulator_x86)
lib_dir = os.path.join(emulator_dir, 'lib', 'pc-bios')
for root, unused_subdirs, files in os.walk(lib_dir):
for filepath in files:
shutil.copy2(os.path.join(root, filepath),
self.bios_dir)
return self.bios_dir
default_android_platform = AndroidPlatform()
class EmulatedDevice(object):
"""An interface to manage emulated android devices."""
def __init__(self,
adb_server_port=None,
emulator_telnet_port=None,
emulator_adb_port=None,
device_serial=None,
android_platform=None,
qemu_gdb_port=0,
enable_single_step=False,
logcat_path=None,
logcat_filter='*:D',
enable_console_auth=False,
enable_g3_monitor=True,
enable_gps=True,
add_insecure_cert=False,
reporter=None,
mini_boot=False,
sim_access_rules_file=None,
phone_number=None,
source_properties=None,
use_waterfall=False,
forward_bin=None,
ports_bin=None):
self.adb_server_port = adb_server_port
self.emulator_adb_port = emulator_adb_port
self.emulator_telnet_port = emulator_telnet_port
self.device_serial = device_serial
self.android_platform = android_platform
self._metadata_pb = None
self._connect_poll_interval = 1
self._connect_max_attempts = 300
self._emulator_log_file = None
self._images_dir = None
self._running = False
self._kicked_launcher = False
self._emulator_start_args = None
self._emulator_env = None
self._emu_process_pid = None
self._sysimages_tmp_dir = None
self._qemu_gdb_port = qemu_gdb_port
self._enable_single_step = enable_single_step
self._emulator_tmp_dir = None
self.delete_temp_on_exit = True
self._child_will_delete_tmp = True
self._sockets_dir = None
self._pipe_traversal_log_dir = None
self._pipe_traversal_running = None
self._vm_running = True
self._logcat_path = logcat_path
self._logcat_filter = logcat_filter
self._enable_console_auth = enable_console_auth
self._console_auth_token_file = None
self._enable_g3_monitor = enable_g3_monitor
self._enable_gps = enable_gps
self._add_insecure_cert = add_insecure_cert
# There is a hard coded 10 minutes timeout in bazel side.
# We use a shorter cut off here to make sure we have chances
# to print log.
self._start_time = time.time()
self._time_out_time = self._start_time + 580
self._use_real_adb = False
self._reporter = reporter or reporting.NoOpReporter()
self._direct_boot = False
self._mini_boot = mini_boot
self._sim_access_rules_file = sim_access_rules_file
self._source_properties = source_properties
self._phone_number = phone_number
self._use_waterfall = use_waterfall
self._forward_bin = forward_bin
self._ports_bin = ports_bin
def _IsUserBuild(self, build_prop):
"""Check if a build is user build from build.prop file."""
with open(build_prop, 'r') as f:
return 'ro.build.type=user\n' in f.read()
return False
def _IsBuggyWearBuild(self, build_prop):
"""Check if this is the buggy wear build described in b/67322170."""
with open(build_prop, 'r') as f:
return 'ro.build.version.incremental=2424746\n' in f.read()
def _IsPipeTraversalRunning(self):
if self._pipe_traversal_running is None:
if self._SnapshotPresent().value == 'True':
# snapshot restore - it must be started explicitly.
self._pipe_traversal_running = False
else:
# fresh boot - of course it's running.
self._pipe_traversal_running = True
return self._pipe_traversal_running
def PreverifyApks(self):
"""Causes APKs to be verified upon installation."""
logging.info('enabling preverify...')
# no longer applicable in ART world.
if self.GetApiVersion() <= 20:
# v=a,o=v means -Xverify:all -Xdexopt:verified
self.ExecOnDevice(['setprop', 'dalvik.vm.dexopt-flags', 'v=a,o=v'])
self._RestartAndroid()
self._PollEmulatorStatus()
if not self._direct_boot:
self._UnlockScreen()
def _PossibleImgSuffix(self):
if (self._metadata_pb.emulator_type ==
emulator_meta_data_pb2.EmulatorMetaDataPb.QEMU2):
return '.qcow2'
return ''
def _UserdataQemuFile(self):
return os.path.join(self._SessionImagesDir(), 'userdata-qemu.img')
def _SnapshotFile(self):
return os.path.join(self._SessionImagesDir(), 'snapshots.img')
def _SdcardFile(self):
return os.path.join(self._SessionImagesDir(), 'sdcard.img')
def _CacheFile(self):
return os.path.join(self._SessionImagesDir(), 'cache.img')
def _RamdiskFile(self):
return os.path.join(self._SessionImagesDir(), 'ramdisk.img')
def _EncryptionKeyImageFile(self):
return os.path.join(self._SessionImagesDir(), 'encryptionkey.img')
def _AdvancedFeaturesFile(self):
return os.path.join(self._SessionImagesDir(), 'advancedFeatures.ini')
def _VendorFile(self):
return os.path.join(self._SessionImagesDir(), 'vendor.img')
def _InitSystemFile(self):
return os.path.join(self._InitImagesDir(), 'system.img')
def _SystemName(self):
if (self._metadata_pb.emulator_type ==
emulator_meta_data_pb2.EmulatorMetaDataPb.QEMU2):
return 'system.img'
return 'system-qemu.img'
def _SystemFile(self):
return os.path.join(self._SessionImagesDir(), self._SystemName())
def _KernelFileName(self):
if (self._metadata_pb.emulator_type ==
emulator_meta_data_pb2.EmulatorMetaDataPb.QEMU2):
possible_kernels = ['kernel-ranchu-64', 'kernel-ranchu']
else:
possible_kernels = ['kernel-qemu']
system_image_dir = self._metadata_pb.system_image_dir
for name in possible_kernels:
if os.path.isfile(os.path.join(system_image_dir, name)):
return name
raise Exception('No kernel file found in %s' % system_image_dir)
def _KernelFile(self):
return os.path.join(self._SessionImagesDir(), self._KernelFileName())
def _InitImagesDir(self):
return os.path.join(self._images_dir, 'init')
def _SessionImagesDir(self):
return os.path.join(self._images_dir, 'session')
def _SnapshotRamBinFile(self):
return os.path.join(self._SessionImagesDir(), 'snapshots', 'default_boot',
'ram.bin')
def _SetUUID(self, sd, uuid_value):
"""Set UUID for sd card image."""
with open(sd, 'r+b') as f:
f.seek(SD_CARD_UUID_OFFSET)
f.write(struct.pack('i', uuid_value))
def _SparseCp(self, src, dst):
"""Copies a file and respects its sparseness.
Symbolic links are dereferenced.
Args:
src: the source file
dst: the destination file
"""
subprocess.check_call(
['cp', '--sparse=always', '--dereference', src, dst])
def _ExtractTarEntry(self, archive, entry, working_dir):
"""Extracts a single entry from a compressed tar archive."""
subprocess.check_call([
'tar', '-xzSf', archive, '--no-same-owner',
'-C', working_dir, '--no-anchored', entry])
def _StageDataFiles(self,
system_image_dir,
userdata_tarball,
timer,
enable_guest_gl,
snapshot_file,
system_image_path=None,
data_image_path=None,
vendor_img_path=None,
encryptionkey_img_path=None,
advanced_features_ini=None,
build_prop_path=None,
modified_ramdisk_path=None,
data_files=None):
"""Stages files for the emulator launch."""
self._images_dir = os.path.abspath(self._TempDir('images'))
os.makedirs(self._InitImagesDir())
os.makedirs(self._SessionImagesDir())
# Copy build.prop into the session dir where the emulator will find it.
# TODO(b/67322170): Generally we want build.prop in the session dir where
# the emulator will see it, but swordfish wear_23 breaks when we do that.
# Until we fix that device, we need a special case to avoid breaking it.
if (self.GetApiVersion() > 10 and
not self._IsBuggyWearBuild(build_prop_path)):
shutil.copy(build_prop_path,
os.path.join(self._SessionImagesDir(), 'build.prop'))
# kernel is never compressed (thank god.)
init_kernel = os.path.abspath(
os.path.join(system_image_dir, self._KernelFileName()))
assert os.path.exists(init_kernel)
os.symlink(init_kernel, self._KernelFile())
init_sys = os.path.abspath(system_image_path)
assert os.path.exists(init_sys), '%s: no system.img' % system_image_path
if system_image_path.endswith('.img'):
os.symlink(init_sys, self._InitSystemFile())
if (self._metadata_pb.emulator_type ==
emulator_meta_data_pb2.EmulatorMetaDataPb.QEMU2 and
not self._ShouldModifySystemImage(enable_guest_gl)):
# Qemu2 does not need a writable system.img file, so we symlink to
# ObjFS to avoid a copy.
os.symlink(init_sys, self._SystemFile())
else:
logging.info('Copying system image to %s', self._SystemFile())
timer.start('COPY_SYSTEM_IMAGE')
self._SparseCp(self._InitSystemFile(), self._SystemFile())
timer.stop('COPY_SYSTEM_IMAGE')
os.chmod(self._SystemFile(), stat.S_IRWXU)
else:
assert system_image_path.endswith('.img.tar.gz'), 'Not known format'
logging.info('Extracting system image from tar.gz')
timer.start('EXTRACT_SYSTEM_IMAGE')
self._ExtractTarEntry(
init_sys, 'system.img', os.path.dirname(self._SystemFile()))
shutil.move(os.path.join(os.path.dirname(self._SystemFile()),
'system.img'),
self._SystemFile())
timer.stop('EXTRACT_SYSTEM_IMAGE')
os.chmod(self._SystemFile(), stat.S_IRWXU)
timer.start('MODIFY_SYSTEM_IMAGE')
self._ModifySystemImage(enable_guest_gl)
timer.stop('MODIFY_SYSTEM_IMAGE')
# Folders created are data/misc/*
# Folders created are data/nativetest/**/* and so on.
# If we don't place the files in the right location, we end up
# getting weird exceptions in logcat since emulator requires those files
# to be present.
if data_files:
for each_file in data_files:
fn = each_file.split('data/')[1]
dn = os.path.join(self._SessionImagesDir(), 'data', os.path.dirname(fn))
# Create if this dir does not exist.
if not os.path.exists(dn):
os.makedirs(dn)
bn = os.path.basename(fn)
shutil.copy(each_file, os.path.join(dn, bn))
# Pipe service won't work for user build and api level 23+, since
# pipe_traversal doesn't have a right seclinux policy. In this case, just
# use real adb.
self._use_real_adb = (
self._IsUserBuild(build_prop_path) and self.GetApiVersion() >= 23)
if userdata_tarball:
# userdata tarball should contain:
# self._UserdataQemuFile()
# self._RamdiskFile()
# self._CacheFile()
# self._SdcardFile()
# self._SnapshotFile()
#
# It does not include:
# self._KernelFile() # handled above
# self._SystemFile() # handled above
# self._InitSystemFile() # handled above
tar_opts = '-xzSf'
if (self._metadata_pb.emulator_type ==
emulator_meta_data_pb2.EmulatorMetaDataPb.QEMU2):
# qemu2's userdata.dat is not gzipped because it is a diff of the
# initial userdata partition and thus quite small already. It also
# doesn't compress as well as a raw image does.
tar_opts = '-xSf'
subprocess.check_call(['tar', tar_opts, userdata_tarball, '-C',
self._images_dir])
data_size = FLAGS.data_partition_size
if (self.GetApiVersion() >= 19 and data_size and
data_size > os.path.getsize(self._UserdataQemuFile()) >> 20):
logging.info('Resize data partition to %dM', data_size)
subprocess.check_call(['/sbin/resize2fs', '-f',
self._UserdataQemuFile(), '%dM' % data_size])
# Symlink the snapshot file to the actual location.
if (snapshot_file and self._metadata_pb.emulator_architecture == 'x86' and
os.path.exists(snapshot_file)):
os.symlink(snapshot_file, self._SnapshotRamBinFile())
else:
# self._RamdiskFile() - we modify this abit
# self._SnapshotFile() - always exists
self._InitializeRamdisk(system_image_dir, modified_ramdisk_path)
self._SparseCp(self.android_platform.empty_snapshot_fs,
self._SnapshotFile())
if vendor_img_path and not os.path.exists(self._VendorFile()):
init_data = vendor_img_path
assert os.path.exists(init_data), '%s: no vendor.img' % vendor_img_path
if init_data.endswith('.img.tar.gz'):
self._ExtractTarEntry(
init_data, 'vendor.img', os.path.dirname(self._VendorFile()))
shutil.move(os.path.join(os.path.dirname(self._VendorFile()),
'vendor.img'),
self._VendorFile())
elif init_data.endswith('.img'):
self._SparseCp(init_data, self._VendorFile())
else:
raise Exception('Unknown vendor image type %s', vendor_img_path)
os.chmod(self._VendorFile(), stat.S_IRWXU)
if encryptionkey_img_path and not os.path.exists(
self._EncryptionKeyImageFile()):
init_data = encryptionkey_img_path
assert os.path.exists(init_data), (
'%s: no encryptionkey.img' % encryptionkey_img_path)
assert init_data.endswith('.img'), 'Not known format'
shutil.copy(init_data, self._EncryptionKeyImageFile())
os.chmod(self._EncryptionKeyImageFile(), stat.S_IRWXU)
if advanced_features_ini and not os.path.exists(
self._AdvancedFeaturesFile()):
assert os.path.exists(advanced_features_ini), (
'Advanced Features file %s does not exist' % advanced_features_ini)
shutil.copy(advanced_features_ini, self._AdvancedFeaturesFile())
os.chmod(self._AdvancedFeaturesFile(), stat.S_IRWXU)
if data_image_path and not os.path.exists(self._UserdataQemuFile()):
init_data = data_image_path
assert os.path.exists(init_data), '%s: no userdata.img' % data_image_path
if init_data.endswith('.img'):
self._SparseCp(init_data, self._UserdataQemuFile())
else:
assert init_data.endswith('.img.tar.gz'), 'Not known format'
self._ExtractTarEntry(
init_data,
'userdata.img',
os.path.dirname(self._UserdataQemuFile()))
shutil.move(os.path.join(os.path.dirname(self._UserdataQemuFile()),
'userdata.img'),
self._UserdataQemuFile())
if not os.path.exists(self._CacheFile()):
init_cache = resources.GetResourceFilename(
'android_test_support/'
'tools/android/emulator/support/cache.img.tar.gz')
self._ExtractTarEntry(init_cache, 'cache.img',
os.path.dirname(self._CacheFile()))
if not os.path.exists(self._SdcardFile()):
sdcard_size_mb = self._metadata_pb.sdcard_size_mb
if sdcard_size_mb == 256:
sd_name = 'default_sdcard.256.img'
self._ExtractTarEntry(
resources.GetResourceFilename(
'android_test_support/'
'tools/android/emulator/support/%s.tar.gz' % sd_name),
sd_name, os.path.dirname(self._SdcardFile()))
shutil.move(os.path.join(os.path.dirname(self._SdcardFile()),
sd_name),
self._SdcardFile())
logging.info('Using default sd card.')
else:
logging.info('Making sdcard on the fly due to a nonstandard size')
sdcard_args = [
self.android_platform.mksdcard,
'%sM' % sdcard_size_mb,
self._SdcardFile()]
timer.start(_SDCARD_CREATE)
common.SpawnAndWaitWithRetry(sdcard_args)
# 1AEF-1A1E is hard coded in AdbController.java
self._SetUUID(self._SdcardFile(), 0x1AEF1A1E)
timer.stop(_SDCARD_CREATE)
os.chmod(self._SdcardFile(), stat.S_IRWXU)
if os.path.exists(self._UserdataQemuFile()):
os.chmod(self._UserdataQemuFile(), stat.S_IRWXU)
os.chmod(self._CacheFile(), stat.S_IRWXU)
os.chmod(self._SnapshotFile(), stat.S_IRWXU)
# pylint: disable=too-many-statements
def _MakeAvd(self):
"""Crafts a set of ini files to correspond to an avd for this device.
AVD is the only way to pass certain properties on to the emulated device,
most notably dpi-device and vm heapsize (both of which are ignored from the
command line). Unfortunately there are options which are only controllable
from commandline (instead of avd) so we get to configure things thru both
interfaces. One day I hope the configuration style will all be unified into
one rational method which is effective both thru ADT/eclipse and
programatically. (As you're about to see, programmatically creating AVDs is
a bit of a trip!).
Returns:
an appropriate avd_name to pass to the emulator.
"""
# When using AVDs, the emulator expects to find AVDs beneath
#
# $ANDROID_SDK_HOME/.android/avd/[avd_name].
# if unset, this defaults to $HOME or /tmp
# both of these are undesired in our case.
#
# Also when using AVDs the emulator wants to find $ANDROID_SDK_ROOT
# and expects skin info to be stored beneath that location. We will
# in the future need to support skins.
avd_files = self._TempDir('avd_files')
android_tmp_dir = os.path.join(avd_files, 'tmp')
home_dir = os.path.join(avd_files, 'home')
os.makedirs(android_tmp_dir)
os.makedirs(home_dir)
# New version of emulator check for these directories.
os.makedirs(os.path.join(self._images_dir, 'platforms'))
os.makedirs(os.path.join(self._images_dir, 'platform-tools'))
self._emulator_env['ANDROID_HOME'] = self._images_dir
self._emulator_env['ANDROID_SDK_ROOT'] = self._images_dir
self._emulator_env['ANDROID_SDK_HOME'] = home_dir
self._emulator_env['HOME'] = home_dir
self._emulator_env['ANDROID_TMP'] = android_tmp_dir
self._console_auth_token_file = os.path.join(home_dir,
'.emulator_console_auth_token')
if not self._enable_console_auth:
# Write an empty file to disable console auth.
with open(self._console_auth_token_file, 'w+') as f:
f.write('')
dot_android_dir = os.path.join(home_dir, '.android')
os.makedirs(dot_android_dir)
ddms_cfg_file = os.path.join(dot_android_dir, 'ddms.cfg')
with open(ddms_cfg_file, 'w+') as ddms_cfg:
# suppress the 'welcome to android' dialog
ddms_cfg.write('pingOptIn=false\n')
ddms_cfg.write('pingTime.emulator=1348614108574\n')
ddms_cfg.write('pingId=592273184351987827\n')
dot_config_dir = os.path.join(home_dir, '.config',
'Android Open Source Project')
os.makedirs(dot_config_dir)
emulator_cfg_file = os.path.join(dot_config_dir, 'Emulator.conf')
with open(emulator_cfg_file, 'w+') as emulator_cfg:
# suppress some dialogs
emulator_cfg.write('[General]\n')
emulator_cfg.write('showAdbWarning=false\n')
emulator_cfg.write('showAvdArchWarning=false\n')
avd_dir = os.path.join(home_dir, '.android', 'avd')
# Allowed chars are:
# ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.-
avd_name = 'mobile_ninjas.adb.%s' % self.emulator_adb_port
content_dir = os.path.join(avd_dir, avd_name)
os.makedirs(content_dir)
root_config_file = os.path.join(avd_dir, '%s.ini' % avd_name)
with open(root_config_file, 'w+') as root_config:
root_config.write('path=%s\n' % self._SessionImagesDir())
root_config.write('target=android-%s\n' % self._metadata_pb.api_name)
user_cfg_file = os.path.join(self._SessionImagesDir(), 'emulator-user.ini')
with open(user_cfg_file, 'w+') as user_cfg:
# Always put emulator window in fixed position.
user_cfg.write('window.x = 0\n')
user_cfg.write('window.y = 0\n')
config_ini_file = os.path.join(self._SessionImagesDir(), 'config.ini')
with open(config_ini_file, 'w+') as config_ini:
wrote_cores = False
for prop in self._metadata_pb.avd_config_property:
config_ini.write('%s=%s\n' % (prop.name, prop.value))
wrote_cores |= prop.name == _CORES_PROP
# the default size is ~256 megs, which fills up fast on iterative
# development.
if 'ext4' in subprocess.check_output(['file', self._UserdataQemuFile()]):
# getting this size right is pretty crucial - if it doesnt match
# the underlying file the guest os will get confused.
config_ini.write('disk.dataPartition.size=%s\n' %
os.path.getsize(self._UserdataQemuFile()))
else:
config_ini.write('disk.dataPartition.size=2047m\n')
# system partition must be less than 2GB (there's a constraint check in
# qemu). Also we must set the commandline flag too - which sets both
# userdata and system sizes, so everything is set to 2047 for sanity.
if 'ext4' in subprocess.check_output(['file', self._SystemFile()]):
# getting this size right is pretty crucial - if it doesnt match
# the underlying file the guest os will get confused.
config_ini.write('disk.systemPartition.size=%s\n' %
os.path.getsize(self._SystemFile()))
else:
config_ini.write('disk.systemPartition.size=2047m\n')
# a link back to our original name, not sure if this is needed, but lets
# be consistant.
config_ini.write('avd.name=%s\n' % avd_name)
config_ini.write('image.sysdir.1=%s\n' % 'session')
config_ini.write('image.sysdir.2=%s\n' % 'init')
# if we do not set this - android just creates cache by itself.
config_ini.write('disk.cachePartition=1\n')
config_ini.write('disk.cachePartition.path=cache.img\n')
cache_size = '66m'
if 'ext4' in subprocess.check_output(['file', self._CacheFile()]):
cache_size = os.path.getsize(self._CacheFile())
# getting this size right is pretty crucial - if it doesnt match
# the underlying file the guest os will get confused.
config_ini.write('disk.cachePartition.size=%s\n' % cache_size)
if self._metadata_pb.with_adbd_pipe:
config_ini.write('adbd.over.pipe=1\n')
# this really could be determined by the emulator-arm vs emulator-x86
# binary itself, and when we run without any AVD at all, it does. However
# once we start specifying avds, we need to re-specify this info in the
# avd, otherwise the emulator will balk.
config_ini.write(
'abi.type=%s\n' % self._metadata_pb.emulator_architecture)
avd_cpu_arch = self._metadata_pb.emulator_architecture
if avd_cpu_arch.startswith('arm'):
avd_cpu_arch = 'arm'
# else hopefully source properties matches. sigh!
config_ini.write('hw.cpu.arch=%s\n' % avd_cpu_arch)
# allow the user to override from the launch command any core values
# the system image may set by default.
if FLAGS['cores'].present or not wrote_cores:
config_ini.write('%s=%d\n' % (_CORES_PROP, FLAGS.cores))
config_ini.write('hw.gpu.enabled=yes\n')
if not FLAGS.hardware_keyboard:
config_ini.write('hw.keyboard=no\n')
# and there are race conditions if skin and the hw ini values do not agree
# with each other.
skin = self._metadata_pb.skin
height = skin[skin.index('x') + 1:]
width = skin[:skin.index('x')]
config_ini.write('hw.lcd.width=%s\n' % width)
config_ini.write('hw.lcd.height=%s\n' % height)
# there are other avd pieces we omit, because they're overridden by the
# flags we pass in from the commandline.
return avd_name
# pylint: enable=too-many-statements
def _GetProperty(self, property_name, default_properties,
source_properties, default_value):
default_properties = default_properties or {}
source_properties = source_properties or {}
key = 'avd_config_ini.%s' % property_name
key = key.lower()
return default_properties.get(key, source_properties.get(key,
default_value))
def _MapToSupportedDensity(self, density):
"""Map density to emulator supported buckets."""
if density == _DENSITY_TVDPI:
return density
# The reference source code is here:
# https://android.googlesource.com/platform/external/qemu/+/emu-2.2-release/android/hw-lcd.c#18
# It finds the closest (either higher or lower) supported dpi for a given
# density.
for i in range(len(_BUCKET_DPI[:-1])):
if density < ((_BUCKET_DPI[i] + _BUCKET_DPI[i+1])/2):
return _BUCKET_DPI[i]
return _BUCKET_DPI[-1]
def _GetImagePath(self, image_dir, suffix, ignore_non_existent_file=False):
"""Generate image path from image_dir and suffix."""
file_path = os.path.join(image_dir, suffix)
if os.path.exists(file_path):
return file_path
elif os.path.exists(file_path + '.tar.gz'):
return file_path + '.tar.gz'
else:
if ignore_non_existent_file:
logging.info('%s file does not exist', file_path)
return None
else:
raise Exception('%s not found in %s' % (suffix, os.listdir(image_dir)))
def BuildImagesDict(self, system_image_path, data_image_path, vendor_img_path,
encryptionkey_img_path, advanced_features_ini,
build_prop_path, data_files):
images_dict = {
'system_image_path': system_image_path,
'data_image_path': data_image_path
}
if vendor_img_path:
images_dict['vendor_img_path'] = vendor_img_path
if encryptionkey_img_path:
images_dict['encryptionkey_img_path'] = encryptionkey_img_path
if advanced_features_ini:
images_dict['advanced_features_ini'] = advanced_features_ini
if build_prop_path:
images_dict['build_prop_path'] = build_prop_path
if data_files:
images_dict['data_files'] = data_files
return images_dict
def Configure(self,
system_image_dir,
skin,
memory,
density,
vm_heap,
net_type='fastnet',
source_properties=None,
default_properties=None,
kvm_present=False,
system_image_path=None,
data_image_path=None,
vendor_img_path=None,
encryptionkey_img_path=None,
advanced_features_ini=None,
build_prop_path=None,
data_files=None):
"""Performs pre-start configuration of the emulator."""
assert os.path.exists(system_image_dir), ('Sysdir doesnt exist: %s' %
system_image_dir)
system_image_path = (system_image_path or
self._GetImagePath(system_image_dir, 'system.img'))
data_image_path = (data_image_path or
self._GetImagePath(system_image_dir, 'userdata.img',
ignore_non_existent_file=True))
build_prop_path = (
build_prop_path or self._GetImagePath(system_image_dir, 'build.prop'))
images_dict = self.BuildImagesDict(system_image_path, data_image_path,
vendor_img_path, encryptionkey_img_path,
advanced_features_ini, build_prop_path,
data_files)