blob: 0f555b11d30faa6e668dac98d73475db9c73e193 [file] [log] [blame]
Joe Onorato0578cbc2016-10-19 17:03:06 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "aapt.h"
18#include "adb.h"
19#include "make.h"
20#include "print.h"
21#include "util.h"
22
23#include <sstream>
24#include <string>
25#include <vector>
26
27#include <stdio.h>
28#include <stdlib.h>
29#include <string.h>
30#include <unistd.h>
31
32#include <google/protobuf/stubs/common.h>
33
34using namespace std;
35
Joe Onorato6c97f492019-02-27 20:42:37 -050036#define NATIVE_TESTS "NATIVE_TESTS"
37
Joe Onorato0578cbc2016-10-19 17:03:06 -070038/**
39 * An entry from the command line for something that will be built, installed,
40 * and/or tested.
41 */
42struct Target {
43 bool build;
44 bool install;
45 bool test;
46 string pattern;
47 string name;
48 vector<string> actions;
49 Module module;
50
51 int testActionCount;
52
53 int testPassCount;
54 int testFailCount;
Makoto Onuki6fb2c972017-08-02 14:40:12 -070055 int unknownFailureCount; // unknown failure == "Process crashed", etc.
Joe Onorato0578cbc2016-10-19 17:03:06 -070056 bool actionsWithNoTests;
57
58 Target(bool b, bool i, bool t, const string& p);
59};
60
61Target::Target(bool b, bool i, bool t, const string& p)
62 :build(b),
63 install(i),
64 test(t),
65 pattern(p),
66 testActionCount(0),
67 testPassCount(0),
68 testFailCount(0),
Makoto Onuki6fb2c972017-08-02 14:40:12 -070069 unknownFailureCount(0),
Joe Onorato0578cbc2016-10-19 17:03:06 -070070 actionsWithNoTests(false)
71{
72}
73
74/**
75 * Command line options.
76 */
77struct Options {
78 // For help
79 bool runHelp;
80
Joe Onorato7acae742019-03-23 16:12:32 -070081 // For refreshing module-info.json
82 bool runRefresh;
83
Joe Onorato0578cbc2016-10-19 17:03:06 -070084 // For tab completion
85 bool runTab;
86 string tabPattern;
87
88 // For build/install/test
Joe Onorato6592c3c2016-11-12 16:34:25 -080089 bool noRestart;
Joe Onorato0578cbc2016-10-19 17:03:06 -070090 bool reboot;
91 vector<Target*> targets;
92
93 Options();
94 ~Options();
95};
96
97Options::Options()
98 :runHelp(false),
Joe Onorato7acae742019-03-23 16:12:32 -070099 runRefresh(false),
Joe Onorato0578cbc2016-10-19 17:03:06 -0700100 runTab(false),
Joe Onorato6592c3c2016-11-12 16:34:25 -0800101 noRestart(false),
Joe Onorato0578cbc2016-10-19 17:03:06 -0700102 reboot(false),
103 targets()
104{
105}
106
107Options::~Options()
108{
109}
110
111struct InstallApk
112{
113 TrackedFile file;
114 bool alwaysInstall;
115 bool installed;
116
117 InstallApk();
118 InstallApk(const InstallApk& that);
119 InstallApk(const string& filename, bool always);
120 ~InstallApk() {};
121};
122
123InstallApk::InstallApk()
124{
125}
126
127InstallApk::InstallApk(const InstallApk& that)
128 :file(that.file),
129 alwaysInstall(that.alwaysInstall),
130 installed(that.installed)
131{
132}
133
134InstallApk::InstallApk(const string& filename, bool always)
135 :file(filename),
136 alwaysInstall(always),
137 installed(false)
138{
139}
140
Joe Onorato6c97f492019-02-27 20:42:37 -0500141struct PushedFile
142{
143 TrackedFile file;
144 string dest;
145
146 PushedFile();
147 PushedFile(const PushedFile& that);
148 PushedFile(const string& filename, const string& dest);
149 ~PushedFile() {};
150};
151
152PushedFile::PushedFile()
153{
154}
155
156PushedFile::PushedFile(const PushedFile& that)
157 :file(that.file),
158 dest(that.dest)
159{
160}
161
162PushedFile::PushedFile(const string& f, const string& d)
163 :file(f),
164 dest(d)
165{
166}
Joe Onorato0578cbc2016-10-19 17:03:06 -0700167
168/**
169 * Record for an test that is going to be launched.
170 */
171struct TestAction {
172 TestAction();
173
174 // The package name from the apk
175 string packageName;
176
177 // The test runner class
178 string runner;
179
180 // The test class, or none if all tests should be run
181 string className;
182
183 // The original target that requested this action
184 Target* target;
185
186 // The number of tests that passed
187 int passCount;
188
189 // The number of tests that failed
190 int failCount;
191};
192
193TestAction::TestAction()
194 :passCount(0),
195 failCount(0)
196{
197}
198
199/**
200 * Record for an activity that is going to be launched.
201 */
202struct ActivityAction {
203 // The package name from the apk
204 string packageName;
205
206 // The test class, or none if all tests should be run
207 string className;
208};
209
210/**
211 * Callback class for the am instrument command.
212 */
213class TestResults: public InstrumentationCallbacks
214{
215public:
216 virtual void OnTestStatus(TestStatus& status);
217 virtual void OnSessionStatus(SessionStatus& status);
218
219 /**
220 * Set the TestAction that the tests are for.
221 * It will be updated with statistics as the tests run.
222 */
223 void SetCurrentAction(TestAction* action);
224
Makoto Onuki6fb2c972017-08-02 14:40:12 -0700225 bool IsSuccess();
226
227 string GetErrorMessage();
228
Joe Onorato0578cbc2016-10-19 17:03:06 -0700229private:
230 TestAction* m_currentAction;
Makoto Onuki6fb2c972017-08-02 14:40:12 -0700231 SessionStatus m_sessionStatus;
Joe Onorato0578cbc2016-10-19 17:03:06 -0700232};
233
234void
235TestResults::OnTestStatus(TestStatus& status)
236{
237 bool found;
238// printf("OnTestStatus\n");
239// status.PrintDebugString();
240 int32_t resultCode = status.has_results() ? status.result_code() : 0;
241
242 if (!status.has_results()) {
243 return;
244 }
245 const ResultsBundle &results = status.results();
246
247 int32_t currentTestNum = get_bundle_int(results, &found, "current", NULL);
248 if (!found) {
249 currentTestNum = -1;
250 }
251
252 int32_t testCount = get_bundle_int(results, &found, "numtests", NULL);
253 if (!found) {
254 testCount = -1;
255 }
256
257 string className = get_bundle_string(results, &found, "class", NULL);
258 if (!found) {
259 return;
260 }
261
262 string testName = get_bundle_string(results, &found, "test", NULL);
263 if (!found) {
264 return;
265 }
266
267 if (resultCode == 0) {
268 // test passed
269 m_currentAction->passCount++;
270 m_currentAction->target->testPassCount++;
271 } else if (resultCode == 1) {
272 // test starting
273 ostringstream line;
274 line << "Running";
275 if (currentTestNum > 0) {
276 line << ": " << currentTestNum;
277 if (testCount > 0) {
278 line << " of " << testCount;
279 }
280 }
281 line << ": " << m_currentAction->target->name << ':' << className << "\\#" << testName;
282 print_one_line("%s", line.str().c_str());
Makoto Onuki6fb2c972017-08-02 14:40:12 -0700283 } else if ((resultCode == -1) || (resultCode == -2)) {
Joe Onorato0578cbc2016-10-19 17:03:06 -0700284 // test failed
Makoto Onuki6fb2c972017-08-02 14:40:12 -0700285 // Note -2 means an assertion failure, and -1 means other exceptions. We just treat them
286 // all as "failures".
Joe Onorato0578cbc2016-10-19 17:03:06 -0700287 m_currentAction->failCount++;
288 m_currentAction->target->testFailCount++;
289 printf("%s\n%sFailed: %s:%s\\#%s%s\n", g_escapeClearLine, g_escapeRedBold,
290 m_currentAction->target->name.c_str(), className.c_str(),
291 testName.c_str(), g_escapeEndColor);
292
293 string stack = get_bundle_string(results, &found, "stack", NULL);
294 if (found) {
295 printf("%s\n", stack.c_str());
296 }
297 }
298}
299
300void
Makoto Onuki6fb2c972017-08-02 14:40:12 -0700301TestResults::OnSessionStatus(SessionStatus& status)
Joe Onorato0578cbc2016-10-19 17:03:06 -0700302{
303 //status.PrintDebugString();
Makoto Onuki6fb2c972017-08-02 14:40:12 -0700304 m_sessionStatus = status;
305 if (m_currentAction && !IsSuccess()) {
306 m_currentAction->target->unknownFailureCount++;
307 }
Joe Onorato0578cbc2016-10-19 17:03:06 -0700308}
309
310void
311TestResults::SetCurrentAction(TestAction* action)
312{
313 m_currentAction = action;
314}
315
Makoto Onuki6fb2c972017-08-02 14:40:12 -0700316bool
317TestResults::IsSuccess()
318{
319 return m_sessionStatus.result_code() == -1; // Activity.RESULT_OK.
320}
321
322string
323TestResults::GetErrorMessage()
324{
325 bool found;
326 string shortMsg = get_bundle_string(m_sessionStatus.results(), &found, "shortMsg", NULL);
327 if (!found) {
328 return IsSuccess() ? "" : "Unknown failure";
329 }
330 return shortMsg;
331}
332
333
Joe Onorato0578cbc2016-10-19 17:03:06 -0700334/**
335 * Prints the usage statement / help text.
336 */
337static void
338print_usage(FILE* out) {
339 fprintf(out, "usage: bit OPTIONS PATTERN\n");
340 fprintf(out, "\n");
341 fprintf(out, " Build, sync and test android code.\n");
342 fprintf(out, "\n");
343 fprintf(out, " The -b -i and -t options allow you to specify which phases\n");
344 fprintf(out, " you want to run. If none of those options are given, then\n");
345 fprintf(out, " all phases are run. If any of these options are provided\n");
346 fprintf(out, " then only the listed phases are run.\n");
347 fprintf(out, "\n");
348 fprintf(out, " OPTIONS\n");
349 fprintf(out, " -b Run a build\n");
350 fprintf(out, " -i Install the targets\n");
351 fprintf(out, " -t Run the tests\n");
352 fprintf(out, "\n");
Joe Onorato6592c3c2016-11-12 16:34:25 -0800353 fprintf(out, " -n Don't reboot or restart\n");
Joe Onorato0578cbc2016-10-19 17:03:06 -0700354 fprintf(out, " -r If the runtime needs to be restarted, do a full reboot\n");
355 fprintf(out, " instead\n");
356 fprintf(out, "\n");
357 fprintf(out, " PATTERN\n");
358 fprintf(out, " One or more targets to build, install and test. The target\n");
359 fprintf(out, " names are the names that appear in the LOCAL_MODULE or\n");
360 fprintf(out, " LOCAL_PACKAGE_NAME variables in Android.mk or Android.bp files.\n");
361 fprintf(out, "\n");
362 fprintf(out, " Building and installing\n");
363 fprintf(out, " -----------------------\n");
364 fprintf(out, " The modules specified will be built and then installed. If the\n");
365 fprintf(out, " files are on the system partition, they will be synced and the\n");
366 fprintf(out, " attached device rebooted. If they are APKs that aren't on the\n");
367 fprintf(out, " system partition they are installed with adb install.\n");
368 fprintf(out, "\n");
369 fprintf(out, " For example:\n");
370 fprintf(out, " bit framework\n");
371 fprintf(out, " Builds framework.jar, syncs the system partition and reboots.\n");
372 fprintf(out, "\n");
373 fprintf(out, " bit SystemUI\n");
374 fprintf(out, " Builds SystemUI.apk, syncs the system partition and reboots.\n");
375 fprintf(out, "\n");
376 fprintf(out, " bit CtsProtoTestCases\n");
377 fprintf(out, " Builds this CTS apk, adb installs it, but does not run any\n");
378 fprintf(out, " tests.\n");
379 fprintf(out, "\n");
380 fprintf(out, " Running Unit Tests\n");
381 fprintf(out, " ------------------\n");
382 fprintf(out, " To run a unit test, list the test class names and optionally the\n");
383 fprintf(out, " test method after the module.\n");
384 fprintf(out, "\n");
385 fprintf(out, " For example:\n");
386 fprintf(out, " bit CtsProtoTestCases:*\n");
387 fprintf(out, " Builds this CTS apk, adb installs it, and runs all the tests\n");
388 fprintf(out, " contained in that apk.\n");
389 fprintf(out, "\n");
390 fprintf(out, " bit framework CtsProtoTestCases:*\n");
391 fprintf(out, " Builds the framework and the apk, syncs and reboots, then\n");
392 fprintf(out, " adb installs CtsProtoTestCases.apk, and runs all tests \n");
393 fprintf(out, " contained in that apk.\n");
394 fprintf(out, "\n");
395 fprintf(out, " bit CtsProtoTestCases:.ProtoOutputStreamBoolTest\n");
396 fprintf(out, " bit CtsProtoTestCases:android.util.proto.cts.ProtoOutputStreamBoolTest\n");
397 fprintf(out, " Builds and installs CtsProtoTestCases.apk, and runs all the\n");
398 fprintf(out, " tests in the ProtoOutputStreamBoolTest class.\n");
399 fprintf(out, "\n");
400 fprintf(out, " bit CtsProtoTestCases:.ProtoOutputStreamBoolTest\\#testWrite\n");
401 fprintf(out, " Builds and installs CtsProtoTestCases.apk, and runs the testWrite\n");
402 fprintf(out, " test method on that class.\n");
403 fprintf(out, "\n");
404 fprintf(out, " bit CtsProtoTestCases:.ProtoOutputStreamBoolTest\\#testWrite,.ProtoOutputStreamBoolTest\\#testRepeated\n");
405 fprintf(out, " Builds and installs CtsProtoTestCases.apk, and runs the testWrite\n");
406 fprintf(out, " and testRepeated test methods on that class.\n");
407 fprintf(out, "\n");
Makoto Onuki164e7962017-07-06 16:20:11 -0700408 fprintf(out, " bit CtsProtoTestCases:android.util.proto.cts.\n");
409 fprintf(out, " Builds and installs CtsProtoTestCases.apk, and runs the tests in the java package\n");
410 fprintf(out, " \"android.util.proto.cts\".\n");
411 fprintf(out, "\n");
Joe Onorato0578cbc2016-10-19 17:03:06 -0700412 fprintf(out, " Launching an Activity\n");
413 fprintf(out, " ---------------------\n");
414 fprintf(out, " To launch an activity, specify the activity class name after\n");
415 fprintf(out, " the module name.\n");
416 fprintf(out, "\n");
417 fprintf(out, " For example:\n");
418 fprintf(out, " bit StatusBarTest:NotificationBuilderTest\n");
419 fprintf(out, " bit StatusBarTest:.NotificationBuilderTest\n");
420 fprintf(out, " bit StatusBarTest:com.android.statusbartest.NotificationBuilderTest\n");
421 fprintf(out, " Builds and installs StatusBarTest.apk, launches the\n");
422 fprintf(out, " com.android.statusbartest/.NotificationBuilderTest activity.\n");
423 fprintf(out, "\n");
424 fprintf(out, "\n");
Joe Onorato7acae742019-03-23 16:12:32 -0700425 fprintf(out, "usage: bit --refresh\n");
426 fprintf(out, "\n");
427 fprintf(out, " Update module-info.json, the cache of make goals that can be built.\n");
428 fprintf(out, "\n");
Joe Onorato0578cbc2016-10-19 17:03:06 -0700429 fprintf(out, "usage: bit --tab ...\n");
430 fprintf(out, "\n");
431 fprintf(out, " Lists the targets in a format for tab completion. To get tab\n");
432 fprintf(out, " completion, add this to your bash environment:\n");
433 fprintf(out, "\n");
434 fprintf(out, " complete -C \"bit --tab\" bit\n");
435 fprintf(out, "\n");
436 fprintf(out, " Sourcing android's build/envsetup.sh will do this for you\n");
437 fprintf(out, " automatically.\n");
438 fprintf(out, "\n");
439 fprintf(out, "\n");
440 fprintf(out, "usage: bit --help\n");
441 fprintf(out, "usage: bit -h\n");
442 fprintf(out, "\n");
443 fprintf(out, " Print this help message\n");
444 fprintf(out, "\n");
445}
446
447
448/**
449 * Sets the appropriate flag* variables. If there is a problem with the
450 * commandline arguments, prints the help message and exits with an error.
451 */
452static void
453parse_args(Options* options, int argc, const char** argv)
454{
455 // Help
456 if (argc == 2 && (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)) {
457 options->runHelp = true;
458 return;
459 }
460
Joe Onorato7acae742019-03-23 16:12:32 -0700461 // Refresh
462 if (argc == 2 && strcmp(argv[1], "--refresh") == 0) {
463 options->runRefresh = true;
464 return;
465 }
466
Joe Onorato0578cbc2016-10-19 17:03:06 -0700467 // Tab
468 if (argc >= 4 && strcmp(argv[1], "--tab") == 0) {
469 options->runTab = true;
470 options->tabPattern = argv[3];
471 return;
472 }
473
474 // Normal usage
475 bool anyPhases = false;
476 bool gotPattern = false;
477 bool flagBuild = false;
478 bool flagInstall = false;
479 bool flagTest = false;
480 for (int i=1; i < argc; i++) {
481 string arg(argv[i]);
482 if (arg[0] == '-') {
483 for (size_t j=1; j<arg.size(); j++) {
484 switch (arg[j]) {
485 case '-':
486 break;
487 case 'b':
488 if (gotPattern) {
489 gotPattern = false;
490 flagInstall = false;
491 flagTest = false;
492 }
493 flagBuild = true;
494 anyPhases = true;
495 break;
496 case 'i':
497 if (gotPattern) {
498 gotPattern = false;
499 flagBuild = false;
500 flagTest = false;
501 }
502 flagInstall = true;
503 anyPhases = true;
504 break;
505 case 't':
506 if (gotPattern) {
507 gotPattern = false;
508 flagBuild = false;
509 flagInstall = false;
510 }
511 flagTest = true;
512 anyPhases = true;
513 break;
Joe Onorato6592c3c2016-11-12 16:34:25 -0800514 case 'n':
515 options->noRestart = true;
516 break;
Joe Onorato0578cbc2016-10-19 17:03:06 -0700517 case 'r':
518 options->reboot = true;
519 break;
520 default:
521 fprintf(stderr, "Unrecognized option '%c'\n", arg[j]);
522 print_usage(stderr);
523 exit(1);
524 break;
525 }
526 }
527 } else {
528 Target* target = new Target(flagBuild || !anyPhases, flagInstall || !anyPhases,
529 flagTest || !anyPhases, arg);
530 size_t colonPos = arg.find(':');
531 if (colonPos == 0) {
532 fprintf(stderr, "Test / activity supplied without a module to build: %s\n",
533 arg.c_str());
534 print_usage(stderr);
Yunlian Jiang2cfa8492016-12-06 16:08:39 -0800535 delete target;
Joe Onorato0578cbc2016-10-19 17:03:06 -0700536 exit(1);
537 } else if (colonPos == string::npos) {
538 target->name = arg;
539 } else {
540 target->name.assign(arg, 0, colonPos);
541 size_t beginPos = colonPos+1;
542 size_t commaPos;
543 while (true) {
544 commaPos = arg.find(',', beginPos);
545 if (commaPos == string::npos) {
546 if (beginPos != arg.size()) {
547 target->actions.push_back(string(arg, beginPos, commaPos));
548 }
549 break;
550 } else {
551 if (commaPos != beginPos) {
552 target->actions.push_back(string(arg, beginPos, commaPos-beginPos));
553 }
554 beginPos = commaPos+1;
555 }
556 }
557 }
558 options->targets.push_back(target);
559 gotPattern = true;
560 }
561 }
562 // If no pattern was supplied, give an error
563 if (options->targets.size() == 0) {
564 fprintf(stderr, "No PATTERN supplied.\n\n");
565 print_usage(stderr);
566 exit(1);
567 }
568}
569
570/**
571 * Get an environment variable.
572 * Exits with an error if it is unset or the empty string.
573 */
574static string
575get_required_env(const char* name, bool quiet)
576{
577 const char* value = getenv(name);
578 if (value == NULL || value[0] == '\0') {
579 if (!quiet) {
580 fprintf(stderr, "%s not set. Did you source build/envsetup.sh,"
581 " run lunch and do a build?\n", name);
582 }
583 exit(1);
584 }
585 return string(value);
586}
587
588/**
589 * Get the out directory.
590 *
591 * This duplicates the logic in build/make/core/envsetup.mk (which hasn't changed since 2011)
592 * so that we don't have to wait for get_build_var make invocation.
593 */
594string
595get_out_dir()
596{
597 const char* out_dir = getenv("OUT_DIR");
598 if (out_dir == NULL || out_dir[0] == '\0') {
599 const char* common_base = getenv("OUT_DIR_COMMON_BASE");
600 if (common_base == NULL || common_base[0] == '\0') {
601 // We don't prefix with buildTop because we cd there and it
602 // makes all the filenames long when being pretty printed.
603 return "out";
604 } else {
Joe Onorato8a5bb632016-10-21 14:31:42 -0700605 char pwd[PATH_MAX];
606 if (getcwd(pwd, PATH_MAX) == NULL) {
607 fprintf(stderr, "Your pwd is too long.\n");
608 exit(1);
609 }
Joe Onorato0578cbc2016-10-19 17:03:06 -0700610 const char* slash = strrchr(pwd, '/');
611 if (slash == NULL) {
612 slash = "";
613 }
614 string result(common_base);
615 result += slash;
Joe Onorato0578cbc2016-10-19 17:03:06 -0700616 return result;
617 }
618 }
619 return string(out_dir);
620}
621
622/**
623 * Check that a system property on the device matches the expected value.
624 * Exits with an error if they don't.
625 */
626static void
627check_device_property(const string& property, const string& expected)
628{
629 int err;
630 string deviceValue = get_system_property(property, &err);
631 check_error(err);
632 if (deviceValue != expected) {
633 print_error("There is a mismatch between the build you just did and the device you");
634 print_error("are trying to sync it to in the %s system property", property.c_str());
635 print_error(" build: %s", expected.c_str());
636 print_error(" device: %s", deviceValue.c_str());
637 exit(1);
638 }
639}
640
Chih-Hung Hsiehc7edf072017-10-03 09:57:55 -0700641static void
642chdir_or_exit(const char *path) {
643 // TODO: print_command("cd", path);
644 if (0 != chdir(path)) {
645 print_error("Error: Could not chdir: %s", path);
646 exit(1);
647 }
648}
649
Joe Onorato0578cbc2016-10-19 17:03:06 -0700650/**
651 * Run the build, install, and test actions.
652 */
Makoto Onuki6fb2c972017-08-02 14:40:12 -0700653bool
Joe Onorato6592c3c2016-11-12 16:34:25 -0800654run_phases(vector<Target*> targets, const Options& options)
Joe Onorato0578cbc2016-10-19 17:03:06 -0700655{
656 int err = 0;
657
658 //
659 // Initialization
660 //
661
662 print_status("Initializing");
663
664 const string buildTop = get_required_env("ANDROID_BUILD_TOP", false);
665 const string buildProduct = get_required_env("TARGET_PRODUCT", false);
666 const string buildVariant = get_required_env("TARGET_BUILD_VARIANT", false);
667 const string buildType = get_required_env("TARGET_BUILD_TYPE", false);
Joe Onoratoce0bd062019-01-14 15:30:05 -0800668 const string buildOut = get_out_dir();
Chih-Hung Hsiehc7edf072017-10-03 09:57:55 -0700669 chdir_or_exit(buildTop.c_str());
Joe Onorato0578cbc2016-10-19 17:03:06 -0700670
Joe Onoratoce0bd062019-01-14 15:30:05 -0800671 BuildVars buildVars(buildOut, buildProduct, buildVariant, buildType);
672
673 const string buildDevice = buildVars.GetBuildVar("TARGET_DEVICE", false);
674 const string buildId = buildVars.GetBuildVar("BUILD_ID", false);
Dan Willemsena40118d2017-10-17 17:46:41 -0700675
Joe Onorato0578cbc2016-10-19 17:03:06 -0700676 // Get the modules for the targets
677 map<string,Module> modules;
678 read_modules(buildOut, buildDevice, &modules, false);
679 for (size_t i=0; i<targets.size(); i++) {
680 Target* target = targets[i];
681 map<string,Module>::iterator mod = modules.find(target->name);
682 if (mod != modules.end()) {
683 target->module = mod->second;
684 } else {
685 print_error("Error: Could not find module: %s", target->name.c_str());
Joe Onorato7acae742019-03-23 16:12:32 -0700686 fprintf(stderr, "Try running %sbit --refresh%s if you recently added %s%s%s.\n",
687 g_escapeBold, g_escapeEndColor,
688 g_escapeBold, target->name.c_str(), g_escapeEndColor);
Joe Onorato0578cbc2016-10-19 17:03:06 -0700689 err = 1;
690 }
691 }
692 if (err != 0) {
693 exit(1);
694 }
695
696 // Choose the goals
697 vector<string> goals;
698 for (size_t i=0; i<targets.size(); i++) {
699 Target* target = targets[i];
700 if (target->build) {
701 goals.push_back(target->name);
702 }
703 }
704
705 // Figure out whether we need to sync the system and which apks to install
Joe Onorato6c97f492019-02-27 20:42:37 -0500706 string deviceTargetPath = buildOut + "/target/product/" + buildDevice;
707 string systemPath = deviceTargetPath + "/system/";
708 string dataPath = deviceTargetPath + "/data/";
Joe Onorato0578cbc2016-10-19 17:03:06 -0700709 bool syncSystem = false;
710 bool alwaysSyncSystem = false;
Joe Onorato70edfa82018-12-14 15:46:27 -0800711 vector<string> systemFiles;
Joe Onorato0578cbc2016-10-19 17:03:06 -0700712 vector<InstallApk> installApks;
Joe Onorato6c97f492019-02-27 20:42:37 -0500713 vector<PushedFile> pushedFiles;
Joe Onorato0578cbc2016-10-19 17:03:06 -0700714 for (size_t i=0; i<targets.size(); i++) {
715 Target* target = targets[i];
716 if (target->install) {
717 for (size_t j=0; j<target->module.installed.size(); j++) {
718 const string& file = target->module.installed[j];
719 // System partition
720 if (starts_with(file, systemPath)) {
721 syncSystem = true;
Joe Onorato70edfa82018-12-14 15:46:27 -0800722 systemFiles.push_back(file);
Joe Onorato0578cbc2016-10-19 17:03:06 -0700723 if (!target->build) {
724 // If a system partition target didn't get built then
725 // it won't change we will always need to do adb sync
726 alwaysSyncSystem = true;
727 }
728 continue;
729 }
730 // Apk in the data partition
731 if (starts_with(file, dataPath) && ends_with(file, ".apk")) {
732 // Always install it if we didn't build it because otherwise
733 // it will never have changed.
734 installApks.push_back(InstallApk(file, !target->build));
735 continue;
736 }
Joe Onorato6c97f492019-02-27 20:42:37 -0500737 // If it's a native test module, push it.
738 if (target->module.HasClass(NATIVE_TESTS) && starts_with(file, dataPath)) {
739 string installedPath(file.c_str() + deviceTargetPath.length());
740 pushedFiles.push_back(PushedFile(file, installedPath));
741 }
Joe Onorato0578cbc2016-10-19 17:03:06 -0700742 }
743 }
744 }
745 map<string,FileInfo> systemFilesBefore;
746 if (syncSystem && !alwaysSyncSystem) {
747 get_directory_contents(systemPath, &systemFilesBefore);
748 }
749
Joe Onorato70edfa82018-12-14 15:46:27 -0800750 if (systemFiles.size() > 0){
751 print_info("System files:");
752 for (size_t i=0; i<systemFiles.size(); i++) {
753 printf(" %s\n", systemFiles[i].c_str());
754 }
755 }
Joe Onorato6c97f492019-02-27 20:42:37 -0500756 if (pushedFiles.size() > 0){
757 print_info("Files to push:");
758 for (size_t i=0; i<pushedFiles.size(); i++) {
759 printf(" %s\n", pushedFiles[i].file.filename.c_str());
760 printf(" --> %s\n", pushedFiles[i].dest.c_str());
761 }
762 }
Joe Onorato70edfa82018-12-14 15:46:27 -0800763 if (installApks.size() > 0){
764 print_info("APKs to install:");
765 for (size_t i=0; i<installApks.size(); i++) {
766 printf(" %s\n", installApks[i].file.filename.c_str());
767 }
768 }
769
Joe Onorato0578cbc2016-10-19 17:03:06 -0700770 //
771 // Build
772 //
773
774 // Run the build
775 if (goals.size() > 0) {
776 print_status("Building");
777 err = build_goals(goals);
778 check_error(err);
779 }
780
781 //
782 // Install
783 //
784
785 // Sync the system partition and reboot
786 bool skipSync = false;
787 if (syncSystem) {
788 print_status("Syncing /system");
789
790 if (!alwaysSyncSystem) {
791 // If nothing changed and we weren't forced to sync, skip the reboot for speed.
792 map<string,FileInfo> systemFilesAfter;
793 get_directory_contents(systemPath, &systemFilesAfter);
794 skipSync = !directory_contents_differ(systemFilesBefore, systemFilesAfter);
795 }
796 if (skipSync) {
797 printf("Skipping sync because no files changed.\n");
798 } else {
799 // Do some sanity checks
800 check_device_property("ro.build.product", buildProduct);
801 check_device_property("ro.build.type", buildVariant);
802 check_device_property("ro.build.id", buildId);
803
804 // Stop & Sync
Joe Onorato6592c3c2016-11-12 16:34:25 -0800805 if (!options.noRestart) {
806 err = run_adb("shell", "stop", NULL);
807 check_error(err);
808 }
Joe Onorato0578cbc2016-10-19 17:03:06 -0700809 err = run_adb("remount", NULL);
810 check_error(err);
811 err = run_adb("sync", "system", NULL);
812 check_error(err);
813
Joe Onorato6592c3c2016-11-12 16:34:25 -0800814 if (!options.noRestart) {
815 if (options.reboot) {
816 print_status("Rebooting");
Joe Onorato0578cbc2016-10-19 17:03:06 -0700817
Joe Onorato6592c3c2016-11-12 16:34:25 -0800818 err = run_adb("reboot", NULL);
819 check_error(err);
820 err = run_adb("wait-for-device", NULL);
821 check_error(err);
822 } else {
823 print_status("Restarting the runtime");
Joe Onorato0578cbc2016-10-19 17:03:06 -0700824
Joe Onorato6592c3c2016-11-12 16:34:25 -0800825 err = run_adb("shell", "setprop", "sys.boot_completed", "0", NULL);
826 check_error(err);
827 err = run_adb("shell", "start", NULL);
828 check_error(err);
Joe Onorato0578cbc2016-10-19 17:03:06 -0700829 }
Joe Onorato6592c3c2016-11-12 16:34:25 -0800830
831 while (true) {
832 string completed = get_system_property("sys.boot_completed", &err);
833 check_error(err);
834 if (completed == "1") {
835 break;
836 }
837 sleep(2);
838 }
839 sleep(1);
840 err = run_adb("shell", "wm", "dismiss-keyguard", NULL);
841 check_error(err);
Joe Onorato0578cbc2016-10-19 17:03:06 -0700842 }
Joe Onorato0578cbc2016-10-19 17:03:06 -0700843 }
844 }
845
Joe Onorato6c97f492019-02-27 20:42:37 -0500846 // Push files
847 if (pushedFiles.size() > 0) {
848 print_status("Pushing files");
849 for (size_t i=0; i<pushedFiles.size(); i++) {
850 const PushedFile& pushed = pushedFiles[i];
851 string dir = dirname(pushed.dest);
852 if (dir.length() == 0 || dir == "/") {
853 // This isn't really a file inside the data directory. Just skip it.
854 continue;
855 }
856 // TODO: if (!apk.file.fileInfo.exists || apk.file.HasChanged())
857 err = run_adb("shell", "mkdir", "-p", dir.c_str(), NULL);
858 check_error(err);
859 err = run_adb("push", pushed.file.filename.c_str(), pushed.dest.c_str());
860 check_error(err);
861 // pushed.installed = true;
862 }
863 }
864
Joe Onorato0578cbc2016-10-19 17:03:06 -0700865 // Install APKs
866 if (installApks.size() > 0) {
867 print_status("Installing APKs");
868 for (size_t i=0; i<installApks.size(); i++) {
869 InstallApk& apk = installApks[i];
870 if (!apk.file.fileInfo.exists || apk.file.HasChanged()) {
871 // It didn't exist before or it changed, so int needs install
Jeff Sharkey5f9dc422017-07-06 12:13:42 -0600872 err = run_adb("install", "-r", "-g", apk.file.filename.c_str(), NULL);
Joe Onorato0578cbc2016-10-19 17:03:06 -0700873 check_error(err);
874 apk.installed = true;
875 } else {
876 printf("APK didn't change. Skipping install of %s\n", apk.file.filename.c_str());
877 }
878 }
879 }
880
881 //
882 // Actions
883 //
884
Joe Onorato6c97f492019-02-27 20:42:37 -0500885 // Whether there have been any tests run, so we can print a summary.
886 bool testsRun = false;
887
888 // Run the native tests.
889 // TODO: We don't have a good way of running these and capturing the output of
890 // them live. It'll take some work. On the other hand, if they're gtest tests,
891 // the output of gtest is not completely insane like the text output of the
892 // instrumentation tests. So for now, we'll just live with that.
893 for (size_t i=0; i<targets.size(); i++) {
894 Target* target = targets[i];
895 if (target->test && target->module.HasClass(NATIVE_TESTS)) {
896 // We don't have a clear signal from the build system which of the installed
897 // files is actually the test, so we guess by looking for one with the same
898 // leaf name as the module that is executable.
899 for (size_t j=0; j<target->module.installed.size(); j++) {
900 string filename = target->module.installed[j];
901 if (!starts_with(filename, dataPath)) {
902 // Native tests go into the data directory.
903 continue;
904 }
905 if (leafname(filename) != target->module.name) {
906 // This isn't the test executable.
907 continue;
908 }
909 if (!is_executable(filename)) {
910 continue;
911 }
912 string installedPath(filename.c_str() + deviceTargetPath.length());
913 printf("the magic one is: %s\n", filename.c_str());
914 printf(" and it's installed at: %s\n", installedPath.c_str());
915
916 // Convert bit-style actions to gtest test filter arguments
917 if (target->actions.size() > 0) {
918 testsRun = true;
919 target->testActionCount++;
920 bool runAll = false;
921 string filterArg("--gtest_filter=");
922 for (size_t k=0; k<target->actions.size(); k++) {
923 string actionString = target->actions[k];
924 if (actionString == "*") {
925 runAll = true;
926 } else {
927 filterArg += actionString;
928 if (k != target->actions.size()-1) {
929 // We would otherwise have to worry about this condition
930 // being true, and appending an extra ':', but we know that
931 // if the extra action is "*", then we'll just run all and
932 // won't use filterArg anyway, so just keep this condition
933 // simple.
934 filterArg += ':';
935 }
936 }
937 }
938 if (runAll) {
939 err = run_adb("shell", installedPath.c_str(), NULL);
940 } else {
941 err = run_adb("shell", installedPath.c_str(), filterArg.c_str(), NULL);
942 }
943 if (err == 0) {
944 target->testPassCount++;
945 } else {
946 target->testFailCount++;
947 }
948 }
949 }
950 }
951 }
952
Joe Onorato0578cbc2016-10-19 17:03:06 -0700953 // Inspect the apks, and figure out what is an activity and what needs a test runner
954 bool printedInspecting = false;
955 vector<TestAction> testActions;
956 vector<ActivityAction> activityActions;
957 for (size_t i=0; i<targets.size(); i++) {
958 Target* target = targets[i];
959 if (target->test) {
960 for (size_t j=0; j<target->module.installed.size(); j++) {
961 string filename = target->module.installed[j];
962
Joe Onorato70edfa82018-12-14 15:46:27 -0800963 // Apk in the data partition
964 if (!starts_with(filename, dataPath) || !ends_with(filename, ".apk")) {
Joe Onorato0578cbc2016-10-19 17:03:06 -0700965 continue;
966 }
967
968 if (!printedInspecting) {
969 printedInspecting = true;
970 print_status("Inspecting APKs");
971 }
972
973 Apk apk;
974 err = inspect_apk(&apk, filename);
975 check_error(err);
976
977 for (size_t k=0; k<target->actions.size(); k++) {
978 string actionString = target->actions[k];
979 if (actionString == "*") {
980 if (apk.runner.length() == 0) {
981 print_error("Error: Test requested for apk that doesn't"
982 " have an <instrumentation> tag: %s\n",
983 target->module.name.c_str());
984 exit(1);
985 }
986 TestAction action;
987 action.packageName = apk.package;
988 action.runner = apk.runner;
989 action.target = target;
990 testActions.push_back(action);
991 target->testActionCount++;
992 } else if (apk.HasActivity(actionString)) {
993 ActivityAction action;
994 action.packageName = apk.package;
995 action.className = full_class_name(apk.package, actionString);
996 activityActions.push_back(action);
997 } else {
998 if (apk.runner.length() == 0) {
999 print_error("Error: Test requested for apk that doesn't"
1000 " have an <instrumentation> tag: %s\n",
1001 target->module.name.c_str());
1002 exit(1);
1003 }
1004 TestAction action;
1005 action.packageName = apk.package;
1006 action.runner = apk.runner;
1007 action.className = full_class_name(apk.package, actionString);
1008 action.target = target;
1009 testActions.push_back(action);
1010 target->testActionCount++;
1011 }
1012 }
1013 }
1014 }
1015 }
1016
1017 // Run the instrumentation tests
1018 TestResults testResults;
1019 if (testActions.size() > 0) {
1020 print_status("Running tests");
Joe Onorato6c97f492019-02-27 20:42:37 -05001021 testsRun = true;
Joe Onorato0578cbc2016-10-19 17:03:06 -07001022 for (size_t i=0; i<testActions.size(); i++) {
1023 TestAction& action = testActions[i];
1024 testResults.SetCurrentAction(&action);
1025 err = run_instrumentation_test(action.packageName, action.runner, action.className,
1026 &testResults);
1027 check_error(err);
1028 if (action.passCount == 0 && action.failCount == 0) {
1029 action.target->actionsWithNoTests = true;
1030 }
1031 int total = action.passCount + action.failCount;
1032 printf("%sRan %d test%s for %s. ", g_escapeClearLine,
1033 total, total > 1 ? "s" : "", action.target->name.c_str());
1034 if (action.passCount == 0 && action.failCount == 0) {
1035 printf("%s%d passed, %d failed%s\n", g_escapeYellowBold, action.passCount,
1036 action.failCount, g_escapeEndColor);
1037 } else if (action.failCount > 0) {
1038 printf("%d passed, %s%d failed%s\n", action.passCount, g_escapeRedBold,
1039 action.failCount, g_escapeEndColor);
1040 } else {
1041 printf("%s%d passed%s, %d failed\n", g_escapeGreenBold, action.passCount,
1042 g_escapeEndColor, action.failCount);
1043 }
Makoto Onuki6fb2c972017-08-02 14:40:12 -07001044 if (!testResults.IsSuccess()) {
1045 printf("\n%sTest didn't finish successfully: %s%s\n", g_escapeRedBold,
1046 testResults.GetErrorMessage().c_str(), g_escapeEndColor);
1047 }
Joe Onorato0578cbc2016-10-19 17:03:06 -07001048 }
1049 }
1050
1051 // Launch the activity
1052 if (activityActions.size() > 0) {
1053 print_status("Starting activity");
1054
1055 if (activityActions.size() > 1) {
1056 print_warning("Multiple activities specified. Will only start the first one:");
1057 for (size_t i=0; i<activityActions.size(); i++) {
1058 ActivityAction& action = activityActions[i];
1059 print_warning(" %s",
1060 pretty_component_name(action.packageName, action.className).c_str());
1061 }
1062 }
1063
1064 const ActivityAction& action = activityActions[0];
1065 string componentName = action.packageName + "/" + action.className;
1066 err = run_adb("shell", "am", "start", componentName.c_str(), NULL);
1067 check_error(err);
1068 }
1069
1070 //
1071 // Print summary
1072 //
1073
1074 printf("\n%s--------------------------------------------%s\n", g_escapeBold, g_escapeEndColor);
1075
1076 // Build
1077 if (goals.size() > 0) {
1078 printf("%sBuilt:%s\n", g_escapeBold, g_escapeEndColor);
1079 for (size_t i=0; i<goals.size(); i++) {
1080 printf(" %s\n", goals[i].c_str());
1081 }
1082 }
1083
1084 // Install
1085 if (syncSystem) {
1086 if (skipSync) {
1087 printf("%sSkipped syncing /system partition%s\n", g_escapeBold, g_escapeEndColor);
1088 } else {
1089 printf("%sSynced /system partition%s\n", g_escapeBold, g_escapeEndColor);
1090 }
1091 }
1092 if (installApks.size() > 0) {
1093 bool printedTitle = false;
1094 for (size_t i=0; i<installApks.size(); i++) {
1095 const InstallApk& apk = installApks[i];
1096 if (apk.installed) {
1097 if (!printedTitle) {
1098 printf("%sInstalled:%s\n", g_escapeBold, g_escapeEndColor);
1099 printedTitle = true;
1100 }
1101 printf(" %s\n", apk.file.filename.c_str());
1102 }
1103 }
1104 printedTitle = false;
1105 for (size_t i=0; i<installApks.size(); i++) {
1106 const InstallApk& apk = installApks[i];
1107 if (!apk.installed) {
1108 if (!printedTitle) {
1109 printf("%sSkipped install:%s\n", g_escapeBold, g_escapeEndColor);
1110 printedTitle = true;
1111 }
1112 printf(" %s\n", apk.file.filename.c_str());
1113 }
1114 }
1115 }
1116
1117 // Tests
Makoto Onuki6fb2c972017-08-02 14:40:12 -07001118 bool hasErrors = false;
Joe Onorato6c97f492019-02-27 20:42:37 -05001119 if (testsRun) {
Joe Onorato0578cbc2016-10-19 17:03:06 -07001120 printf("%sRan tests:%s\n", g_escapeBold, g_escapeEndColor);
1121 size_t maxNameLength = 0;
1122 for (size_t i=0; i<targets.size(); i++) {
1123 Target* target = targets[i];
1124 if (target->test) {
1125 size_t len = target->name.length();
1126 if (len > maxNameLength) {
1127 maxNameLength = len;
1128 }
1129 }
1130 }
1131 string padding(maxNameLength, ' ');
1132 for (size_t i=0; i<targets.size(); i++) {
1133 Target* target = targets[i];
1134 if (target->testActionCount > 0) {
1135 printf(" %s%s", target->name.c_str(), padding.c_str() + target->name.length());
Makoto Onuki6fb2c972017-08-02 14:40:12 -07001136 if (target->unknownFailureCount > 0) {
1137 printf(" %sUnknown failure, see above message.%s\n",
1138 g_escapeRedBold, g_escapeEndColor);
1139 hasErrors = true;
1140 } else if (target->actionsWithNoTests) {
Joe Onorato0578cbc2016-10-19 17:03:06 -07001141 printf(" %s%d passed, %d failed%s\n", g_escapeYellowBold,
1142 target->testPassCount, target->testFailCount, g_escapeEndColor);
Makoto Onuki6fb2c972017-08-02 14:40:12 -07001143 hasErrors = true;
Joe Onorato0578cbc2016-10-19 17:03:06 -07001144 } else if (target->testFailCount > 0) {
1145 printf(" %d passed, %s%d failed%s\n", target->testPassCount,
1146 g_escapeRedBold, target->testFailCount, g_escapeEndColor);
Makoto Onuki6fb2c972017-08-02 14:40:12 -07001147 hasErrors = true;
Joe Onorato0578cbc2016-10-19 17:03:06 -07001148 } else {
1149 printf(" %s%d passed%s, %d failed\n", g_escapeGreenBold,
1150 target->testPassCount, g_escapeEndColor, target->testFailCount);
1151 }
1152 }
1153 }
1154 }
1155 if (activityActions.size() > 1) {
1156 printf("%sStarted Activity:%s\n", g_escapeBold, g_escapeEndColor);
1157 const ActivityAction& action = activityActions[0];
1158 printf(" %s\n", pretty_component_name(action.packageName, action.className).c_str());
1159 }
1160
1161 printf("%s--------------------------------------------%s\n", g_escapeBold, g_escapeEndColor);
Makoto Onuki6fb2c972017-08-02 14:40:12 -07001162 return !hasErrors;
Joe Onorato0578cbc2016-10-19 17:03:06 -07001163}
1164
1165/**
Joe Onorato7acae742019-03-23 16:12:32 -07001166 * Refresh module-info.
1167 */
1168void
1169run_refresh()
1170{
1171 int err;
1172
1173 print_status("Initializing");
1174 const string buildTop = get_required_env("ANDROID_BUILD_TOP", false);
1175 const string buildProduct = get_required_env("TARGET_PRODUCT", false);
1176 const string buildVariant = get_required_env("TARGET_BUILD_VARIANT", false);
1177 const string buildType = get_required_env("TARGET_BUILD_TYPE", false);
1178 const string buildOut = get_out_dir();
1179 chdir_or_exit(buildTop.c_str());
1180
1181 BuildVars buildVars(buildOut, buildProduct, buildVariant, buildType);
1182
1183 string buildDevice = buildVars.GetBuildVar("TARGET_DEVICE", false);
1184
1185 vector<string> goals;
1186 goals.push_back(buildOut + "/target/product/" + buildDevice + "/module-info.json");
1187
1188 print_status("Refreshing module-info.json");
1189 err = build_goals(goals);
1190 check_error(err);
1191}
1192
1193/**
Joe Onorato0578cbc2016-10-19 17:03:06 -07001194 * Implement tab completion of the target names from the all modules file.
1195 */
1196void
1197run_tab_completion(const string& word)
1198{
Joe Onoratoce0bd062019-01-14 15:30:05 -08001199 const string buildTop = get_required_env("ANDROID_BUILD_TOP", false);
Joe Onorato0578cbc2016-10-19 17:03:06 -07001200 const string buildProduct = get_required_env("TARGET_PRODUCT", false);
Joe Onoratoce0bd062019-01-14 15:30:05 -08001201 const string buildVariant = get_required_env("TARGET_BUILD_VARIANT", false);
1202 const string buildType = get_required_env("TARGET_BUILD_TYPE", false);
Joe Onorato0578cbc2016-10-19 17:03:06 -07001203 const string buildOut = get_out_dir();
Chih-Hung Hsiehc7edf072017-10-03 09:57:55 -07001204 chdir_or_exit(buildTop.c_str());
Joe Onorato0578cbc2016-10-19 17:03:06 -07001205
Joe Onoratoce0bd062019-01-14 15:30:05 -08001206 BuildVars buildVars(buildOut, buildProduct, buildVariant, buildType);
1207
1208 string buildDevice = buildVars.GetBuildVar("TARGET_DEVICE", false);
Joe Onorato0578cbc2016-10-19 17:03:06 -07001209
1210 map<string,Module> modules;
1211 read_modules(buildOut, buildDevice, &modules, true);
1212
1213 for (map<string,Module>::const_iterator it = modules.begin(); it != modules.end(); it++) {
1214 if (starts_with(it->first, word)) {
1215 printf("%s\n", it->first.c_str());
1216 }
1217 }
1218}
1219
1220/**
1221 * Main entry point.
1222 */
1223int
1224main(int argc, const char** argv)
1225{
1226 GOOGLE_PROTOBUF_VERIFY_VERSION;
1227 init_print();
1228
1229 Options options;
1230 parse_args(&options, argc, argv);
1231
1232 if (options.runHelp) {
1233 // Help
1234 print_usage(stdout);
1235 exit(0);
Joe Onorato7acae742019-03-23 16:12:32 -07001236 } else if (options.runRefresh) {
1237 run_refresh();
1238 exit(0);
Joe Onorato0578cbc2016-10-19 17:03:06 -07001239 } else if (options.runTab) {
1240 run_tab_completion(options.tabPattern);
1241 exit(0);
1242 } else {
1243 // Normal run
Makoto Onuki6fb2c972017-08-02 14:40:12 -07001244 exit(run_phases(options.targets, options) ? 0 : 1);
Joe Onorato0578cbc2016-10-19 17:03:06 -07001245 }
1246
1247 return 0;
1248}
1249