blob: a808d671d85eb487b26724ed5a7f6a0409cbea59 [file] [log] [blame]
Yilin Yang19da6932019-12-10 13:39:28 +08001#!/usr/bin/env python3
Jon Salze60307f2014-08-05 16:20:00 +08002# -*- coding: utf-8 -*-
3# Copyright 2014 The Chromium OS Authors. All rights reserved.
Tammo Spalink9a96b8a2012-04-03 11:10:41 +08004# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
Jon Salze60307f2014-08-05 16:20:00 +08007
Tammo Spalink9a96b8a2012-04-03 11:10:41 +08008"""Google Factory Tool.
9
You-Cheng Syu461ec032017-03-06 15:56:58 +080010This tool is intended to be used on factory assembly lines. It
Tammo Spalink9a96b8a2012-04-03 11:10:41 +080011provides all of the Google required test functionality and must be run
12on each device as part of the assembly process.
13"""
14
Tammo Spalink9a96b8a2012-04-03 11:10:41 +080015import logging
16import os
Jon Salz65266432012-07-30 19:02:49 +080017import pipes
Tammo Spalink9a96b8a2012-04-03 11:10:41 +080018import re
19import sys
Peter Shihfdf17682017-05-26 11:38:39 +080020from tempfile import gettempdir
Cheng-Yi Chiang9fc121c2014-01-27 11:23:22 +080021import threading
Hung-Te Lin6bd16472012-06-20 16:26:47 +080022import time
Yilin Yange02d5722019-10-23 11:07:36 +080023import xmlrpc.client
Peter Shihfdf17682017-05-26 11:38:39 +080024
Wei-Han Chen0a3320e2016-04-23 01:32:07 +080025from cros.factory.gooftool.common import ExecFactoryPar
Hung-Te Lin0e0f9362015-11-18 18:18:05 +080026from cros.factory.gooftool.common import Shell
Peter Shihfdf17682017-05-26 11:38:39 +080027from cros.factory.gooftool.core import Gooftool
28from cros.factory.gooftool import crosfw
Peter Shihfdf17682017-05-26 11:38:39 +080029from cros.factory.gooftool import report_upload
Yong Hong65bda312018-12-13 20:05:58 +080030from cros.factory.gooftool import vpd
Hung-Te Lin604e0c22015-11-24 15:17:07 +080031from cros.factory.hwid.v3 import hwid_utils
Yong Hong863d3262017-10-30 16:23:34 +080032from cros.factory.probe.functions import chromeos_firmware
Wei-Han Chen2ebb92d2016-01-12 14:51:41 +080033from cros.factory.test.env import paths
Peter Shihfdf17682017-05-26 11:38:39 +080034from cros.factory.test import event_log
Wei-Han Chenaff56232016-04-16 09:17:59 +080035from cros.factory.test.rules import phase
Hung-Te Lin3f096842016-01-13 17:37:06 +080036from cros.factory.test.rules.privacy import FilterDict
Philip Chen6ada02c2019-11-04 19:41:54 +000037from cros.factory.test import state
Peter Shihfdf17682017-05-26 11:38:39 +080038from cros.factory.utils import argparse_utils
Hung-Te Lin03bf7ab2016-06-16 17:26:19 +080039from cros.factory.utils.argparse_utils import CmdArg
Hung-Te Lin03bf7ab2016-06-16 17:26:19 +080040from cros.factory.utils.argparse_utils import ParseCmdline
Wei-Han Chenb34bdff2019-09-26 13:07:50 +080041from cros.factory.utils.argparse_utils import VERBOSITY_CMD_ARG
Peter Shihfdf17682017-05-26 11:38:39 +080042from cros.factory.utils.debug_utils import SetupLogging
Jon Salz40b9f822014-07-25 16:39:55 +080043from cros.factory.utils import file_utils
Peter Shih67c7c0f2018-02-26 11:23:59 +080044from cros.factory.utils.process_utils import Spawn
Wei-Han Chena5c01a02016-04-23 19:27:19 +080045from cros.factory.utils import sys_utils
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +080046from cros.factory.utils import time_utils
Joel Kitchingd3bc2662014-12-16 16:03:32 -080047from cros.factory.utils.type_utils import Error
Tammo Spalink86a61c62012-05-25 15:10:35 +080048
Tammo Spalink5c699832012-07-03 17:50:39 +080049
Tammo Spalink5c699832012-07-03 17:50:39 +080050# TODO(tammo): Replace calls to sys.exit with raise Exit, and maybe
51# treat that specially (as a smoot exit, as opposed to the more
52# verbose output for generic Error).
53
Cheng-Yi Chiang9fc121c2014-01-27 11:23:22 +080054_global_gooftool = None
55_gooftool_lock = threading.Lock()
Philip Chen04fb90b2019-11-06 12:10:33 -080056_has_fpmcu = None
Tammo Spalink5c699832012-07-03 17:50:39 +080057
Hung-Te Lin56b18402015-01-16 14:52:30 +080058
Ricky Lianga70a1202013-03-15 15:03:17 +080059def GetGooftool(options):
Peter Shihfdf17682017-05-26 11:38:39 +080060 global _global_gooftool # pylint: disable=global-statement
Ricky Lianga70a1202013-03-15 15:03:17 +080061
Cheng-Yi Chiang9fc121c2014-01-27 11:23:22 +080062 if _global_gooftool is None:
63 with _gooftool_lock:
Shen-En Shihc5d15d62017-08-04 13:02:59 +080064 if _global_gooftool is None:
65 project = getattr(options, 'project', None)
66 hwdb_path = getattr(options, 'hwdb_path', None)
67 _global_gooftool = Gooftool(hwid_version=3, project=project,
68 hwdb_path=hwdb_path)
Cheng-Yi Chiang9fc121c2014-01-27 11:23:22 +080069
70 return _global_gooftool
Ricky Lianga70a1202013-03-15 15:03:17 +080071
Philip Chen04fb90b2019-11-06 12:10:33 -080072def HasFpmcu():
73 global _has_fpmcu # pylint: disable=global-statement
74
75 if _has_fpmcu is None:
76 FPMCU_PATH = '/dev/cros_fp'
Philip Chen04fb90b2019-11-06 12:10:33 -080077 has_cros_config_fpmcu = False
Philip Chencf6642b2019-12-02 19:38:59 -080078 cros_config_output = Shell(['cros_config', '/fingerprint', 'board'])
79 if cros_config_output.success and cros_config_output.stdout:
Philip Chen04fb90b2019-11-06 12:10:33 -080080 has_cros_config_fpmcu = True
81
Alex Chou5b071392020-08-13 09:45:14 +080082 if not os.path.exists(FPMCU_PATH) and has_cros_config_fpmcu:
Philip Chen04fb90b2019-11-06 12:10:33 -080083 raise Error('FPMCU found in cros_config but missing in %s.' % FPMCU_PATH)
Philip Chen04fb90b2019-11-06 12:10:33 -080084
Alex Chou5b071392020-08-13 09:45:14 +080085 _has_fpmcu = has_cros_config_fpmcu
Philip Chen04fb90b2019-11-06 12:10:33 -080086
87 return _has_fpmcu
Hung-Te Lin56b18402015-01-16 14:52:30 +080088
Ting Shen18a06382016-08-30 16:18:21 +080089def Command(cmd_name, *args, **kwargs):
You-Cheng Syu8fc2a602017-12-22 17:05:05 +080090 """Decorator for commands in gooftool.
Ting Shen18a06382016-08-30 16:18:21 +080091
92 This is similar to argparse_utils.Command, but all gooftool commands
93 can be waived during `gooftool finalize` or `gooftool verify` using
Wei-Han Chen60c5d332017-01-05 17:15:10 +080094 --waive_list or --skip_list option.
Ting Shen18a06382016-08-30 16:18:21 +080095 """
96 def Decorate(fun):
Wei-Han Chen60c5d332017-01-05 17:15:10 +080097 def CommandWithWaiveSkipCheck(options):
Ting Shen18a06382016-08-30 16:18:21 +080098 waive_list = vars(options).get('waive_list', [])
Wei-Han Chen60c5d332017-01-05 17:15:10 +080099 skip_list = vars(options).get('skip_list', [])
100 if phase.GetPhase() >= phase.PVT_DOGFOOD and (
101 waive_list != [] or skip_list != []):
Ting Shen18a06382016-08-30 16:18:21 +0800102 raise Error(
Wei-Han Chen60c5d332017-01-05 17:15:10 +0800103 'waive_list and skip_list should be empty for phase %s' %
104 phase.GetPhase())
Ting Shen18a06382016-08-30 16:18:21 +0800105
Wei-Han Chen60c5d332017-01-05 17:15:10 +0800106 if cmd_name not in skip_list:
107 try:
108 fun(options)
109 except Exception as e:
110 if cmd_name in waive_list:
111 logging.exception(e)
112 else:
113 raise
Ting Shen18a06382016-08-30 16:18:21 +0800114
115 return argparse_utils.Command(cmd_name, *args, **kwargs)(
Wei-Han Chen60c5d332017-01-05 17:15:10 +0800116 CommandWithWaiveSkipCheck)
Ting Shen18a06382016-08-30 16:18:21 +0800117 return Decorate
118
119
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800120@Command('write_hwid',
121 CmdArg('hwid', metavar='HWID', help='HWID string'))
Andy Chengc92e6f92012-11-20 16:55:53 +0800122def WriteHWID(options):
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800123 """Write specified HWID value into the system BB."""
Andy Cheng7a76cb82012-11-19 18:08:19 +0800124
Tammo Spalink95c43732012-07-25 15:57:14 -0700125 logging.info('writing hwid string %r', options.hwid)
Ricky Lianga70a1202013-03-15 15:03:17 +0800126 GetGooftool(options).WriteHWID(options.hwid)
Andy Cheng0465d132013-03-20 12:12:06 +0800127 event_log.Log('write_hwid', hwid=options.hwid)
Yilin Yang71e39412019-09-24 09:26:46 +0800128 print('Wrote HWID: %r' % options.hwid)
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800129
130
Yong Hongc3765412017-12-26 23:12:15 +0800131@Command('read_hwid')
132def ReadHWID(options):
133 """Read the HWID string from GBB."""
134
135 logging.info('reading the hwid string')
Yilin Yang71e39412019-09-24 09:26:46 +0800136 print(GetGooftool(options).ReadHWID())
Yong Hongc3765412017-12-26 23:12:15 +0800137
138
Yong Hong5408f652017-07-11 19:20:25 +0800139_project_cmd_arg = CmdArg(
140 '--project', metavar='PROJECT',
141 default=None, help='Project name to test.')
Ricky Liang53390232013-03-08 15:37:57 +0800142
Tammo Spalink8fab5312012-05-28 18:33:30 +0800143_hwdb_path_cmd_arg = CmdArg(
144 '--hwdb_path', metavar='PATH',
Yong Hong5c6dcd52017-12-27 11:05:01 +0800145 default=hwid_utils.GetDefaultDataPath(),
Tammo Spalink8fab5312012-05-28 18:33:30 +0800146 help='Path to the HWID database.')
147
Tammo Spalink95c43732012-07-25 15:57:14 -0700148_hwid_status_list_cmd_arg = CmdArg(
Hung-Te Lin56b18402015-01-16 14:52:30 +0800149 '--status', nargs='*', default=['supported'],
150 help='allow only HWIDs with these status values')
Tammo Spalink95c43732012-07-25 15:57:14 -0700151
Jon Salzce124fb2012-10-02 17:42:03 +0800152_probe_results_cmd_arg = CmdArg(
Yong Hong55050c12018-02-27 18:19:47 +0800153 '--probe_results', metavar='RESULTS.json',
154 help=('Output from "hwid probe" (used instead of probing this system).'))
Jon Salzce124fb2012-10-02 17:42:03 +0800155
Ricky Liang53390232013-03-08 15:37:57 +0800156_device_info_cmd_arg = CmdArg(
Ricky Liangf89f73a2013-03-19 05:00:24 +0800157 '--device_info', metavar='DEVICE_INFO.yaml', default=None,
You-Cheng Syu8fc2a602017-12-22 17:05:05 +0800158 help='A dict of device info to use instead of fetching from shopfloor '
Ricky Liang53390232013-03-08 15:37:57 +0800159 'server.')
160
Jon Salzce124fb2012-10-02 17:42:03 +0800161_hwid_cmd_arg = CmdArg(
162 '--hwid', metavar='HWID',
Ricky Lianga70a1202013-03-15 15:03:17 +0800163 help='HWID to verify (instead of the currently set HWID of this system).')
Jon Salzce124fb2012-10-02 17:42:03 +0800164
Yong Hong68a0e0d2017-12-20 19:06:54 +0800165_hwid_run_vpd_cmd_arg = CmdArg(
166 '--hwid-run-vpd', action='store_true',
167 help=('Specify the hwid utility to obtain the vpd data by running the '
168 '`vpd` commandline tool.'))
169
170_hwid_vpd_data_file_cmd_arg = CmdArg(
171 '--hwid-vpd-data-file', metavar='FILE.json', type=str, default=None,
172 help=('Specify the hwid utility to obtain the vpd data from the specified '
173 'file.'))
174
Cheng-Han Yang663763b2020-09-15 20:46:23 +0800175_no_write_protect_cmd_arg = CmdArg(
176 '--no_write_protect', action='store_true',
177 help='Do not enable firmware write protection.')
178
Bernie Thompson3c11c872013-07-22 18:22:45 -0700179_rma_mode_cmd_arg = CmdArg(
180 '--rma_mode', action='store_true',
181 help='Enable RMA mode, do not check for deprecated components.')
Tammo Spalink95c43732012-07-25 15:57:14 -0700182
Chih-Yu Huang714dbc42015-07-21 16:42:16 +0800183_cros_core_cmd_arg = CmdArg(
184 '--cros_core', action='store_true',
185 help='Finalize for ChromeOS Core devices (may add or remove few test '
Hung-Te Lin53c49402017-07-26 13:10:58 +0800186 'items. For example, registration codes or firmware bitmap '
Chih-Yu Huang714dbc42015-07-21 16:42:16 +0800187 'locale settings).')
188
Pin-Yen Lin215b7542020-05-05 09:45:37 +0800189_has_ec_pubkey_cmd_arg = CmdArg(
190 '--has_ec_pubkey', action='store_true', default=None,
191 help='The device has EC public key for EFS and need to run VerifyECKey.')
Yilun Lin599833f2017-12-22 14:07:46 +0800192
bowgotsai13820f42015-09-10 23:18:04 +0800193_enforced_release_channels_cmd_arg = CmdArg(
194 '--enforced_release_channels', nargs='*', default=None,
195 help='Enforced release image channels.')
196
Yilun Lin34f54802017-11-16 11:58:25 +0800197_ec_pubkey_path_cmd_arg = CmdArg(
198 '--ec_pubkey_path',
199 default=None,
200 help='Path to public key in vb2 format. Verify EC key with pubkey file.')
201
202_ec_pubkey_hash_cmd_arg = CmdArg(
203 '--ec_pubkey_hash',
204 default=None,
205 help='A string for public key hash. Verify EC key with the given hash.')
206
Hung-Te Lincdb96522016-04-15 16:51:10 +0800207_release_rootfs_cmd_arg = CmdArg(
208 '--release_rootfs', help='Location of release image rootfs partition.')
209
210_firmware_path_cmd_arg = CmdArg(
211 '--firmware_path', help='Location of firmware image partition.')
Ricky Liang43b879b2014-02-24 11:36:55 +0800212
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800213_shopfloor_url_args_cmd_arg = CmdArg(
214 '--shopfloor_url',
Earl Ou51182222016-09-09 12:16:48 +0800215 help='Shopfloor server url to be informed when wiping is done. '
216 'After wiping, a XML-RPC request will be sent to the '
217 'given url to indicate the completion of wiping.')
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800218
219_station_ip_cmd_arg = CmdArg(
220 '--station_ip',
221 help='IP of remote station')
222
223_station_port_cmd_arg = CmdArg(
224 '--station_port',
225 help='Port on remote station')
226
227_wipe_finish_token_cmd_arg = CmdArg(
228 '--wipe_finish_token',
229 help='Required token when notifying station after wipe finished')
230
Wei-Han Chenf3924112019-02-25 14:52:58 +0800231_keep_developer_mode_flag_after_clobber_state_cmd_arg = CmdArg(
232 # The argument name is super long because you should never use it by
233 # yourself when using command line tools.
234 '--keep_developer_mode_flag_after_clobber_state',
235 action='store_true', default=None,
236 help='After clobber-state, do not delete .developer_mode')
237
Ting Shen18a06382016-08-30 16:18:21 +0800238_waive_list_cmd_arg = CmdArg(
239 '--waive_list', nargs='*', default=[], metavar='SUBCMD',
You-Cheng Syu8fc2a602017-12-22 17:05:05 +0800240 help='A list of waived checks, separated by whitespace. '
241 'Each item should be a sub-command of gooftool. '
Ting Shen18a06382016-08-30 16:18:21 +0800242 'e.g. "gooftool verify --waive_list verify_tpm clear_gbb_flags".')
243
Wei-Han Chen60c5d332017-01-05 17:15:10 +0800244_skip_list_cmd_arg = CmdArg(
245 '--skip_list', nargs='*', default=[], metavar='SUBCMD',
You-Cheng Syu8fc2a602017-12-22 17:05:05 +0800246 help='A list of skipped checks, separated by whitespace. '
247 'Each item should be a sub-command of gooftool. '
Wei-Han Chen60c5d332017-01-05 17:15:10 +0800248 'e.g. "gooftool verify --skip_list verify_tpm clear_gbb_flags".')
249
Meng-Huan Yu7a4f0f52020-01-07 20:11:01 +0800250_test_umount_cmd_arg = CmdArg(
251 '--test_umount', action='store_true',
252 help='(For testing only) Only umount rootfs and stateful partition '
253 'instead of running full wiping and cutoff process.')
254
Wei-Han Cheneb4f9a22018-03-09 14:52:23 +0800255_rlz_embargo_end_date_offset_cmd_arg = CmdArg(
Kevin Line4c64de2019-11-22 15:28:34 +0800256 '--embargo_offset', type=int, default=7, choices=list(range(7, 15)),
Wei-Han Cheneb4f9a22018-03-09 14:52:23 +0800257 help='Change the offset of embargo end date, cannot less than 7 days or '
258 'more than 14 days.')
259
Marco Chena681b2e2018-08-31 11:41:41 +0800260_no_ectool_cmd_arg = CmdArg(
261 '--no_ectool', action='store_false', dest='has_ectool',
262 help='There is no ectool utility so tests rely on ectool should be '
263 'skipped.')
Tammo Spalink8fab5312012-05-28 18:33:30 +0800264
chuntsenaf1232f2019-03-20 15:45:54 +0800265_no_generate_mfg_date_cmd_arg = CmdArg(
266 '--no_generate_mfg_date', action='store_false', dest='generate_mfg_date',
267 help='Do not generate manufacturing date nor write mfg_date into VPD.')
268
Stimim Chenc9fbdfc2020-05-21 17:00:53 +0800269_enable_zero_touch_cmd_arg = CmdArg(
270 '--enable_zero_touch', action='store_true',
271 help='Set attested_device_id for zero-touch feature.')
272
chuntsenaf1232f2019-03-20 15:45:54 +0800273
Yilun Lin34f54802017-11-16 11:58:25 +0800274@Command(
275 'verify_ec_key',
276 _ec_pubkey_path_cmd_arg,
277 _ec_pubkey_hash_cmd_arg)
278def VerifyECKey(options):
279 """Verify EC key."""
280 return GetGooftool(options).VerifyECKey(
281 options.ec_pubkey_path, options.ec_pubkey_hash)
282
283
Philip Chen84c16262020-07-30 17:35:27 -0700284@Command('verify_fp_key')
285def VerifyFpKey(options):
286 """Verify fingerprint firmware key."""
287 return GetGooftool(options).VerifyFpKey()
288
289
Hung-Te Line1d80f62016-03-31 14:58:13 +0800290@Command('verify_keys',
Hung-Te Lincdb96522016-04-15 16:51:10 +0800291 _release_rootfs_cmd_arg,
292 _firmware_path_cmd_arg)
Peter Shihfdf17682017-05-26 11:38:39 +0800293def VerifyKeys(options):
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800294 """Verify keys in firmware and SSD match."""
Hung-Te Line1d80f62016-03-31 14:58:13 +0800295 return GetGooftool(options).VerifyKeys(
Hung-Te Lincdb96522016-04-15 16:51:10 +0800296 options.release_rootfs, options.firmware_path)
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800297
298
299@Command('set_fw_bitmap_locale')
Peter Shihfdf17682017-05-26 11:38:39 +0800300def SetFirmwareBitmapLocale(options):
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800301 """Use VPD locale value to set firmware bitmap default language."""
Andy Cheng7a76cb82012-11-19 18:08:19 +0800302
Ricky Lianga70a1202013-03-15 15:03:17 +0800303 (index, locale) = GetGooftool(options).SetFirmwareBitmapLocale()
Andy Cheng2582d292012-12-04 17:38:28 +0800304 logging.info('Firmware bitmap initial locale set to %d (%s).',
305 index, locale)
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800306
307
Hung-Te Line1d80f62016-03-31 14:58:13 +0800308@Command('verify_system_time',
Wei-Han Chen2790d2e2019-01-18 21:13:40 +0800309 _release_rootfs_cmd_arg,
310 _rma_mode_cmd_arg)
Peter Shihfdf17682017-05-26 11:38:39 +0800311def VerifySystemTime(options):
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800312 """Verify system time is later than release filesystem creation time."""
Andy Cheng7a76cb82012-11-19 18:08:19 +0800313
Wei-Han Chen2790d2e2019-01-18 21:13:40 +0800314 return GetGooftool(options).VerifySystemTime(options.release_rootfs,
315 rma_mode=options.rma_mode)
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800316
317
Hung-Te Line1d80f62016-03-31 14:58:13 +0800318@Command('verify_rootfs',
Hung-Te Lincdb96522016-04-15 16:51:10 +0800319 _release_rootfs_cmd_arg)
Peter Shihfdf17682017-05-26 11:38:39 +0800320def VerifyRootFs(options):
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800321 """Verify rootfs on SSD is valid by checking hash."""
Andy Cheng7a76cb82012-11-19 18:08:19 +0800322
Hung-Te Line1d80f62016-03-31 14:58:13 +0800323 return GetGooftool(options).VerifyRootFs(options.release_rootfs)
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800324
Hung-Te Lin56b18402015-01-16 14:52:30 +0800325
Cheng-Yi Chiang676b5292013-06-18 12:05:33 +0800326@Command('verify_tpm')
Peter Shihfdf17682017-05-26 11:38:39 +0800327def VerifyTPM(options):
Cheng-Yi Chiang676b5292013-06-18 12:05:33 +0800328 """Verify TPM is cleared."""
329
330 return GetGooftool(options).VerifyTPM()
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800331
Hung-Te Lin56b18402015-01-16 14:52:30 +0800332
Hung-Te Lindd708d42014-07-11 17:05:01 +0800333@Command('verify_me_locked')
Peter Shihfdf17682017-05-26 11:38:39 +0800334def VerifyManagementEngineLocked(options):
You-Cheng Syu461ec032017-03-06 15:56:58 +0800335 """Verify Management Engine is locked."""
Hung-Te Lindd708d42014-07-11 17:05:01 +0800336
337 return GetGooftool(options).VerifyManagementEngineLocked()
338
Hung-Te Lin56b18402015-01-16 14:52:30 +0800339
Marco Chena681b2e2018-08-31 11:41:41 +0800340@Command('verify_switch_wp',
341 _no_ectool_cmd_arg)
Peter Shihfdf17682017-05-26 11:38:39 +0800342def VerifyWPSwitch(options):
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800343 """Verify hardware write protection switch is enabled."""
Andy Cheng7a76cb82012-11-19 18:08:19 +0800344
Marco Chena681b2e2018-08-31 11:41:41 +0800345 GetGooftool(options).VerifyWPSwitch(options.has_ectool)
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800346
347
Hung-Te Lin53c49402017-07-26 13:10:58 +0800348@Command('verify_vpd')
349def VerifyVPD(options):
350 """Verify that VPD values are properly set.
Jon Salzadd90d32014-04-29 16:16:27 +0800351
Hung-Te Lin53c49402017-07-26 13:10:58 +0800352 Check if mandatory fields are set, and deprecated fields don't exist.
Jon Salzadd90d32014-04-29 16:16:27 +0800353 """
Hung-Te Lin53c49402017-07-26 13:10:58 +0800354 return GetGooftool(options).VerifyVPD()
Jon Salzadd90d32014-04-29 16:16:27 +0800355
356
bowgotsai13820f42015-09-10 23:18:04 +0800357@Command('verify_release_channel',
358 _enforced_release_channels_cmd_arg)
Peter Shihfdf17682017-05-26 11:38:39 +0800359def VerifyReleaseChannel(options):
bowgotsai529139c2015-05-30 01:39:49 +0800360 """Verify that release image channel is correct.
361
362 ChromeOS has four channels: canary, dev, beta and stable.
363 The last three channels support image auto-updates, checks
364 that release image channel is one of them.
365 """
bowgotsai13820f42015-09-10 23:18:04 +0800366 return GetGooftool(options).VerifyReleaseChannel(
367 options.enforced_release_channels)
bowgotsai529139c2015-05-30 01:39:49 +0800368
369
Wei-Han Chen0de7cfd2020-01-03 16:49:20 +0800370@Command('verify_cros_config')
371def VerifyCrosConfig(options):
372 """Verify entries in cros config make sense."""
373 return GetGooftool(options).VerifyCrosConfig()
374
375
Stimim Chenc9fbdfc2020-05-21 17:00:53 +0800376@Command('verify-sn-bits',
377 _enable_zero_touch_cmd_arg)
Stimim Chen8aaa2952020-05-20 13:04:24 +0800378def VerifySnBits(options):
Stimim Chenc9fbdfc2020-05-21 17:00:53 +0800379 if options.enable_zero_touch:
380 GetGooftool(options).VerifySnBits()
Stimim Chen8aaa2952020-05-20 13:04:24 +0800381
382
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800383@Command('write_protect')
Peter Shihfdf17682017-05-26 11:38:39 +0800384def EnableFwWp(options):
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800385 """Enable then verify firmware write protection."""
Peter Shihfdf17682017-05-26 11:38:39 +0800386 del options # Unused.
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800387
Yong Hongdad230a2017-08-30 22:25:19 +0800388 def WriteProtect(fw):
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800389 """Calculate protection size, then invoke flashrom.
390
Yong Hongdad230a2017-08-30 22:25:19 +0800391 The region (offset and size) to write protect may be different per chipset
392 and firmware layout, so we have to read the WP_RO section from FMAP to
393 decide that.
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800394 """
Hung-Te Lin7ea39e82012-07-31 18:39:33 +0800395 wp_section = 'WP_RO'
Hung-Te Lin7ea39e82012-07-31 18:39:33 +0800396
Yong Hongdad230a2017-08-30 22:25:19 +0800397 fmap_image = fw.GetFirmwareImage(
398 sections=(['FMAP'] if fw.target == crosfw.TARGET_MAIN else None))
399 if not fmap_image.has_section(wp_section):
400 raise Error('Could not find %s firmware section: %s' %
401 (fw.target.upper(), wp_section))
402
403 section_data = fw.GetFirmwareImage(
404 sections=[wp_section]).get_section_area(wp_section)
Peter Shihe6afab32018-09-11 17:16:48 +0800405 ro_offset, ro_size = section_data[0:2]
Yong Hongdad230a2017-08-30 22:25:19 +0800406
407 logging.debug('write protecting %s [off=%x size=%x]', fw.target.upper(),
Hung-Te Lin7ea39e82012-07-31 18:39:33 +0800408 ro_offset, ro_size)
Yong Hongdad230a2017-08-30 22:25:19 +0800409 crosfw.Flashrom(fw.target).EnableWriteProtection(ro_offset, ro_size)
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800410
Philip Chendbb06202019-11-05 17:24:26 -0800411 if HasFpmcu():
412 # TODO(b/143991572): Implement enable_fpmcu_write_protection in gooftool.
413 cmd = os.path.join(
414 paths.FACTORY_DIR, 'sh', 'enable_fpmcu_write_protection.sh')
415 cmd_result = Shell(cmd)
416 if not cmd_result.success:
417 raise Error(
418 'Failed to enable FPMCU write protection, stdout=%r, stderr=%r' %
419 (cmd_result.stdout, cmd_result.stderr))
420
Yong Hongdad230a2017-08-30 22:25:19 +0800421 WriteProtect(crosfw.LoadMainFirmware())
Andy Cheng0465d132013-03-20 12:12:06 +0800422 event_log.Log('wp', fw='main')
Hung-Te Lind3b124c2016-10-20 22:22:31 +0800423
Fei Shao21be8242020-04-13 16:57:51 +0800424 # Some EC (mostly PD) does not support "RO_NOW". Instead they will only set
Hung-Te Lind3b124c2016-10-20 22:22:31 +0800425 # "RO_AT_BOOT" when you request to enable RO (These platforms consider
426 # --wp-range with right range identical to --wp-enable), and requires a
427 # 'ectool reboot_ec RO at-shutdown; reboot' to let the RO take effect.
Hung-Te Lin0d10b562016-12-28 10:58:07 +0800428 # After reboot, "flashrom -p host --wp-status" will return protected range.
Hung-Te Lind3b124c2016-10-20 22:22:31 +0800429 # If you don't reboot, returned range will be (0, 0), and running command
430 # "ectool flashprotect" will not have RO_NOW.
Fei Shao21be8242020-04-13 16:57:51 +0800431 # generic_common.test_list.json provides "EnableECWriteProtect" test group
432 # which can be run individually before finalization. Try that out if you're
433 # having trouble enabling RO_NOW flag.
Hung-Te Lind3b124c2016-10-20 22:22:31 +0800434
Yong Hongdad230a2017-08-30 22:25:19 +0800435 for fw in [crosfw.LoadEcFirmware(), crosfw.LoadPDFirmware()]:
436 if fw.GetChipId() is None:
Hung-Te Lind3b124c2016-10-20 22:22:31 +0800437 logging.warning('%s not write protected (seems there is no %s flash).',
Yong Hongdad230a2017-08-30 22:25:19 +0800438 fw.target.upper(), fw.target.upper())
Hung-Te Lind3b124c2016-10-20 22:22:31 +0800439 continue
Yong Hongdad230a2017-08-30 22:25:19 +0800440 WriteProtect(fw)
441 event_log.Log('wp', fw=fw.target)
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800442
443
444@Command('clear_gbb_flags')
Peter Shihfdf17682017-05-26 11:38:39 +0800445def ClearGBBFlags(options):
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800446 """Zero out the GBB flags, in preparation for transition to release state.
447
448 No GBB flags are set in release/shipping state, but they are useful
Hung-Te Lin879cff42017-06-19 12:46:37 +0800449 for factory/development. See "futility gbb --flags" for details.
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800450 """
Andy Cheng7a76cb82012-11-19 18:08:19 +0800451
Ricky Lianga70a1202013-03-15 15:03:17 +0800452 GetGooftool(options).ClearGBBFlags()
Andy Cheng0465d132013-03-20 12:12:06 +0800453 event_log.Log('clear_gbb_flags')
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800454
455
Jon Salzaa3a30e2013-05-15 15:56:28 +0800456@Command('clear_factory_vpd_entries')
Peter Shihfdf17682017-05-26 11:38:39 +0800457def ClearFactoryVPDEntries(options):
Jon Salzaa3a30e2013-05-15 15:56:28 +0800458 """Clears factory.* items in the RW VPD."""
459 entries = GetGooftool(options).ClearFactoryVPDEntries()
460 event_log.Log('clear_factory_vpd_entries', entries=FilterDict(entries))
461
462
Mattias Nisslercca761b2015-04-15 21:53:04 +0200463@Command('generate_stable_device_secret')
Peter Shihfdf17682017-05-26 11:38:39 +0800464def GenerateStableDeviceSecret(options):
You-Cheng Syu461ec032017-03-06 15:56:58 +0800465 """Generates a fresh stable device secret and stores it in the RO VPD."""
Mattias Nisslercca761b2015-04-15 21:53:04 +0200466 GetGooftool(options).GenerateStableDeviceSecret()
467 event_log.Log('generate_stable_device_secret')
468
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800469
Cheng-Han Yang24d42d92020-08-09 04:53:53 +0800470@Command('cr50_set_ro_hash')
471def Cr50SetROHash(options):
472 GetGooftool(options).Cr50SetROHash()
473 event_log.Log('cr50_set_ro_hash')
474
Stimim Chenda9e62c2020-05-14 15:43:18 +0800475@Command('cr50_set_sn_bits_and_board_id',
476 _rma_mode_cmd_arg)
Yves Arrouyeb49b31e2019-03-06 21:51:52 -0800477def Cr50SetSnBitsAndBoardId(options):
Wei-Han Chen66357592020-01-14 15:15:37 +0800478 """Deprecated: use Cr50WriteFlashInfo instead."""
479 logging.warning('This function is renamed to Cr50WriteFlashInfo')
480 Cr50WriteFlashInfo(options)
481
482
Stimim Chen60f7bb22020-04-07 21:02:47 +0800483@Command('cr50_write_flash_info',
Stimim Chenda9e62c2020-05-14 15:43:18 +0800484 _rma_mode_cmd_arg,
Stimim Chenc9fbdfc2020-05-21 17:00:53 +0800485 _enable_zero_touch_cmd_arg)
Wei-Han Chen66357592020-01-14 15:15:37 +0800486def Cr50WriteFlashInfo(options):
Yves Arrouyeb49b31e2019-03-06 21:51:52 -0800487 """Set the serial number bits, board id and flags on the Cr50 chip."""
Stimim Chenc9fbdfc2020-05-21 17:00:53 +0800488 GetGooftool(options).Cr50WriteFlashInfo(
489 options.enable_zero_touch, options.rma_mode)
Wei-Han Chen66357592020-01-14 15:15:37 +0800490 event_log.Log('cr50_write_flash_info')
491
492
493@Command('cr50_write_whitelabel_flags')
494def Cr50WriteWhitelabelFlags(options):
495 GetGooftool(options).Cr50WriteWhitelabelFlags()
496 event_log.Log('cr50_write_whitelabel_flags')
Shen-En Shihd078a7c2017-08-04 13:33:49 +0800497
498
Marco Chen20c885d2018-10-04 17:22:03 +0800499@Command('cr50_disable_factory_mode')
Marco Chen44a666d2018-07-13 21:01:50 +0800500def Cr50DisableFactoryMode(options):
Cheng-Han Yang08333af2017-12-18 17:22:38 +0800501 """Reset Cr50 state back to default state after RMA."""
Marco Chen44a666d2018-07-13 21:01:50 +0800502 return GetGooftool(options).Cr50DisableFactoryMode()
Cheng-Han Yang08333af2017-12-18 17:22:38 +0800503
504
Cheng-Han Yang663763b2020-09-15 20:46:23 +0800505@Command('cr50_finalize',
506 _no_write_protect_cmd_arg,
507 _rma_mode_cmd_arg,
508 _enable_zero_touch_cmd_arg)
509def Cr50Finalize(options):
510 """Finalize steps for cr50."""
511 if options.no_write_protect:
512 logging.warning('SWWP is not enabled. Skip setting RO hash.')
513 elif options.rma_mode:
514 logging.warning('RMA mode. Skip setting RO hash.')
515 else:
516 Cr50SetROHash(options)
517 Cr50WriteFlashInfo(options)
518 Cr50DisableFactoryMode(options)
519
520
Earl Ou564a7872016-10-05 10:22:00 +0800521@Command('enable_release_partition',
522 CmdArg('--release_rootfs',
523 help=('path to the release rootfs device. If not specified, '
524 'the default (5th) partition will be used.')))
525def EnableReleasePartition(options):
526 """Enables a release image partition on the disk."""
527 GetGooftool(options).EnableReleasePartition(options.release_rootfs)
528
529
Shun-Hsing Oucdc64e12015-01-14 22:07:33 +0800530@Command('wipe_in_place',
531 CmdArg('--fast', action='store_true',
Shun-Hsing Ou8d3c40a2015-10-08 18:16:08 +0800532 help='use non-secure but faster wipe method.'),
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800533 _shopfloor_url_args_cmd_arg,
534 _station_ip_cmd_arg,
535 _station_port_cmd_arg,
Meng-Huan Yu7a4f0f52020-01-07 20:11:01 +0800536 _wipe_finish_token_cmd_arg,
537 _test_umount_cmd_arg)
Shun-Hsing Oucdc64e12015-01-14 22:07:33 +0800538def WipeInPlace(options):
539 """Start factory wipe directly without reboot."""
540
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800541 GetGooftool(options).WipeInPlace(options.fast,
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800542 options.shopfloor_url,
543 options.station_ip,
544 options.station_port,
Meng-Huan Yu7a4f0f52020-01-07 20:11:01 +0800545 options.wipe_finish_token,
546 options.test_umount)
Mattias Nisslercca761b2015-04-15 21:53:04 +0200547
Wei-Han Chen7dc6d132016-04-06 11:11:53 +0800548@Command('wipe_init',
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800549 CmdArg('--wipe_args', help='arguments for clobber-state'),
550 CmdArg('--state_dev', help='path to stateful partition device'),
551 CmdArg('--root_disk', help='path to primary device'),
552 CmdArg('--old_root', help='path to old root'),
Wei-Han Chen0a3320e2016-04-23 01:32:07 +0800553 _shopfloor_url_args_cmd_arg,
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800554 _release_rootfs_cmd_arg,
555 _station_ip_cmd_arg,
556 _station_port_cmd_arg,
Wei-Han Chenf3924112019-02-25 14:52:58 +0800557 _wipe_finish_token_cmd_arg,
Meng-Huan Yu7a4f0f52020-01-07 20:11:01 +0800558 _keep_developer_mode_flag_after_clobber_state_cmd_arg,
559 _test_umount_cmd_arg)
Wei-Han Chen7dc6d132016-04-06 11:11:53 +0800560def WipeInit(options):
Wei-Han Chenf3924112019-02-25 14:52:58 +0800561 GetGooftool(options).WipeInit(
562 options.wipe_args,
563 options.shopfloor_url,
564 options.state_dev,
565 options.release_rootfs,
566 options.root_disk,
567 options.old_root,
568 options.station_ip,
569 options.station_port,
570 options.wipe_finish_token,
Meng-Huan Yu7a4f0f52020-01-07 20:11:01 +0800571 options.keep_developer_mode_flag_after_clobber_state,
572 options.test_umount)
Wei-Han Chen7dc6d132016-04-06 11:11:53 +0800573
Stimim Chen8aaa2952020-05-20 13:04:24 +0800574
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800575@Command('verify',
Tammo Spalink95c43732012-07-25 15:57:14 -0700576 _hwid_status_list_cmd_arg,
Jon Salzce124fb2012-10-02 17:42:03 +0800577 _hwdb_path_cmd_arg,
Yong Hong5408f652017-07-11 19:20:25 +0800578 _project_cmd_arg,
Jon Salzce124fb2012-10-02 17:42:03 +0800579 _probe_results_cmd_arg,
Cheng-Yi Chiang406ad912013-11-14 16:51:33 +0800580 _hwid_cmd_arg,
Yong Hong68a0e0d2017-12-20 19:06:54 +0800581 _hwid_run_vpd_cmd_arg,
582 _hwid_vpd_data_file_cmd_arg,
Cheng-Han Yang663763b2020-09-15 20:46:23 +0800583 _no_write_protect_cmd_arg,
Chih-Yu Huang714dbc42015-07-21 16:42:16 +0800584 _rma_mode_cmd_arg,
bowgotsai13820f42015-09-10 23:18:04 +0800585 _cros_core_cmd_arg,
Pin-Yen Lin215b7542020-05-05 09:45:37 +0800586 _has_ec_pubkey_cmd_arg,
Yilun Lin34f54802017-11-16 11:58:25 +0800587 _ec_pubkey_path_cmd_arg,
588 _ec_pubkey_hash_cmd_arg,
Hung-Te Lincdb96522016-04-15 16:51:10 +0800589 _release_rootfs_cmd_arg,
590 _firmware_path_cmd_arg,
Ting Shen18a06382016-08-30 16:18:21 +0800591 _enforced_release_channels_cmd_arg,
Wei-Han Chen60c5d332017-01-05 17:15:10 +0800592 _waive_list_cmd_arg,
Marco Chena681b2e2018-08-31 11:41:41 +0800593 _skip_list_cmd_arg,
Stimim Chenc9fbdfc2020-05-21 17:00:53 +0800594 _no_ectool_cmd_arg,
595 _enable_zero_touch_cmd_arg)
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800596def Verify(options):
597 """Verifies if whole factory process is ready for finalization.
598
599 This routine performs all the necessary checks to make sure the
600 device is ready to be finalized, but does not modify state. These
601 checks include dev switch, firmware write protection switch, hwid,
602 system time, keys, and root file system.
603 """
Andy Cheng7a76cb82012-11-19 18:08:19 +0800604
Hung-Te Lin6d827542012-07-19 11:50:41 +0800605 if not options.no_write_protect:
Ricky Lianga70a1202013-03-15 15:03:17 +0800606 VerifyWPSwitch(options)
Hung-Te Lindd708d42014-07-11 17:05:01 +0800607 VerifyManagementEngineLocked(options)
Ting Shen129fa6f2016-09-02 12:22:24 +0800608 VerifyHWID(options)
Ricky Lianga70a1202013-03-15 15:03:17 +0800609 VerifySystemTime(options)
Pin-Yen Lin215b7542020-05-05 09:45:37 +0800610 if options.has_ec_pubkey:
Yilun Lin599833f2017-12-22 14:07:46 +0800611 VerifyECKey(options)
Philip Chen84c16262020-07-30 17:35:27 -0700612 if HasFpmcu():
613 VerifyFpKey(options)
Ricky Lianga70a1202013-03-15 15:03:17 +0800614 VerifyKeys(options)
615 VerifyRootFs(options)
Cheng-Yi Chiang676b5292013-06-18 12:05:33 +0800616 VerifyTPM(options)
Hung-Te Lin53c49402017-07-26 13:10:58 +0800617 VerifyVPD(options)
bowgotsai529139c2015-05-30 01:39:49 +0800618 VerifyReleaseChannel(options)
Wei-Han Chen0de7cfd2020-01-03 16:49:20 +0800619 VerifyCrosConfig(options)
Stimim Chen8aaa2952020-05-20 13:04:24 +0800620 VerifySnBits(options)
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800621
Hung-Te Lin56b18402015-01-16 14:52:30 +0800622
Jon Salzfe9036f2014-01-16 14:11:23 +0800623@Command('untar_stateful_files')
Hung-Te Lin388bce22014-06-03 19:56:40 +0800624def UntarStatefulFiles(unused_options):
Jon Salzfe9036f2014-01-16 14:11:23 +0800625 """Untars stateful files from stateful_files.tar.xz on stateful partition.
626
627 If that file does not exist (which should only be R30 and earlier),
628 this is a no-op.
629 """
Hung-Te Lin2333f3f2016-08-24 17:56:48 +0800630 # Path to stateful partition on device.
631 device_stateful_path = '/mnt/stateful_partition'
632 tar_file = os.path.join(device_stateful_path, 'stateful_files.tar.xz')
Jon Salzfe9036f2014-01-16 14:11:23 +0800633 if os.path.exists(tar_file):
Hung-Te Lin2333f3f2016-08-24 17:56:48 +0800634 Spawn(['tar', 'xf', tar_file], cwd=device_stateful_path,
Jon Salzfe9036f2014-01-16 14:11:23 +0800635 log=True, check_call=True)
636 else:
637 logging.warning('No stateful files at %s', tar_file)
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800638
Jon Salz40b9f822014-07-25 16:39:55 +0800639
640@Command('log_source_hashes')
Peter Shihfdf17682017-05-26 11:38:39 +0800641def LogSourceHashes(options):
Jon Salz40b9f822014-07-25 16:39:55 +0800642 """Logs hashes of source files in the factory toolkit."""
Peter Shihfdf17682017-05-26 11:38:39 +0800643 del options # Unused.
Jon Salze60307f2014-08-05 16:20:00 +0800644 # WARNING: The following line is necessary to validate the integrity
645 # of the factory software. Do not remove or modify it.
646 #
647 # 警告:此行会验证工厂软件的完整性,禁止删除或修改。
Wei-Han Chena5c01a02016-04-23 19:27:19 +0800648 factory_par = sys_utils.GetRunningFactoryPythonArchivePath()
649 if factory_par:
650 event_log.Log(
651 'source_hashes',
652 **file_utils.HashPythonArchive(factory_par))
653 else:
654 event_log.Log(
655 'source_hashes',
Peter Shihad166772017-05-31 11:36:17 +0800656 **file_utils.HashSourceTree(os.path.join(paths.FACTORY_DIR, 'py')))
Jon Salz40b9f822014-07-25 16:39:55 +0800657
658
Tammo Spalink86a61c62012-05-25 15:10:35 +0800659@Command('log_system_details')
Peter Shihfdf17682017-05-26 11:38:39 +0800660def LogSystemDetails(options):
Tammo Spalink86a61c62012-05-25 15:10:35 +0800661 """Write miscellaneous system details to the event log."""
Andy Cheng7a76cb82012-11-19 18:08:19 +0800662
Ricky Liang43b879b2014-02-24 11:36:55 +0800663 event_log.Log('system_details', **GetGooftool(options).GetSystemDetails())
Tammo Spalink86a61c62012-05-25 15:10:35 +0800664
665
Jon Salza88b83b2013-05-27 20:00:35 +0800666def CreateReportArchiveBlob(*args, **kwargs):
667 """Creates a report archive and returns it as a blob.
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800668
Jon Salza88b83b2013-05-27 20:00:35 +0800669 Args:
670 See CreateReportArchive.
Andy Cheng7a76cb82012-11-19 18:08:19 +0800671
Jon Salza88b83b2013-05-27 20:00:35 +0800672 Returns:
Yilin Yange02d5722019-10-23 11:07:36 +0800673 An xmlrpc.client.Binary object containing a .tar.xz file.
Jon Salza88b83b2013-05-27 20:00:35 +0800674 """
Wei-Han Chen47416612016-09-14 17:41:52 +0800675 report_archive = CreateReportArchive(*args, **kwargs)
676 try:
Yilin Yangf6994c22019-12-09 16:17:21 +0800677 return xmlrpc.client.Binary(
678 file_utils.ReadFile(report_archive, encoding=None))
Wei-Han Chen47416612016-09-14 17:41:52 +0800679 finally:
680 os.unlink(report_archive)
Jon Salza88b83b2013-05-27 20:00:35 +0800681
682
683def CreateReportArchive(device_sn=None, add_file=None):
684 """Creates a report archive in a temporary directory.
685
686 Args:
687 device_sn: The device serial number (optional).
688 add_file: A list of files to add (optional).
689
690 Returns:
691 Path to the archive.
692 """
Philip Chen6ada02c2019-11-04 19:41:54 +0000693 # Flush Testlog data to DATA_TESTLOG_DIR before creating a report archive.
694 result, reason = state.GetInstance().FlushTestlog(
695 uplink=False, local=True, timeout=10)
696 if not result:
697 logging.warning('Failed to flush testlog data: %s', reason)
698
Hung-Te Lin6bd16472012-06-20 16:26:47 +0800699 def NormalizeAsFileName(token):
700 return re.sub(r'\W+', '', token).strip()
Jon Salza88b83b2013-05-27 20:00:35 +0800701
702 target_name = '%s%s.tar.xz' % (
703 time.strftime('%Y%m%dT%H%M%SZ',
704 time.gmtime()),
Hung-Te Lin56b18402015-01-16 14:52:30 +0800705 ('' if device_sn is None else
706 '_' + NormalizeAsFileName(device_sn)))
Tammo Spalink86a61c62012-05-25 15:10:35 +0800707 target_path = os.path.join(gettempdir(), target_name)
Jon Salza88b83b2013-05-27 20:00:35 +0800708
Tammo Spalink86a61c62012-05-25 15:10:35 +0800709 # Intentionally ignoring dotfiles in EVENT_LOG_DIR.
Pi-Hsun Shih1f569a72019-12-26 11:23:56 +0800710 tar_cmd = 'cd %s ; tar cJf %s * -C /' % (event_log.EVENT_LOG_DIR, target_path)
Jongpil Jung23355a92019-12-31 14:38:29 +0900711 tar_files = [paths.FACTORY_LOG_PATH, paths.DATA_TESTLOG_DIR]
712 if add_file:
713 tar_files = tar_files + add_file
Pi-Hsun Shih1f569a72019-12-26 11:23:56 +0800714 for f in tar_files:
715 # Require absolute paths since we use -C / to change current directory to
716 # root.
717 if not f.startswith('/'):
718 raise Error('Not an absolute path: %s' % f)
719 if not os.path.exists(f):
720 raise Error('File does not exist: %s' % f)
721 tar_cmd += ' %s' % pipes.quote(f[1:])
Tammo Spalink86a61c62012-05-25 15:10:35 +0800722 cmd_result = Shell(tar_cmd)
Jon Salzff88c022012-11-03 12:19:58 +0800723
Hung-Te Lin3756c432020-01-16 11:30:46 +0800724 if cmd_result.status == 1:
725 # tar returns 1 when some files were changed during archiving,
726 # but that is expected for log files so should ignore such failure
727 # if the archive looks good.
Pi-Hsun Shih1f569a72019-12-26 11:23:56 +0800728 Spawn(['tar', 'tJf', target_path], check_call=True, log=True,
Jon Salzff88c022012-11-03 12:19:58 +0800729 ignore_stdout=True)
730 elif not cmd_result.success:
Tammo Spalink86a61c62012-05-25 15:10:35 +0800731 raise Error('unable to tar event logs, cmd %r failed, stderr: %r' %
732 (tar_cmd, cmd_result.stderr))
Jon Salzff88c022012-11-03 12:19:58 +0800733
Jon Salza88b83b2013-05-27 20:00:35 +0800734 return target_path
735
736_upload_method_cmd_arg = CmdArg(
737 '--upload_method', metavar='METHOD:PARAM',
738 help=('How to perform the upload. METHOD should be one of '
Kevin Line4c64de2019-11-22 15:28:34 +0800739 '{ftp, shopfloor, ftps, cpfe, smb}.'))
Cheng-Han Yang31a3bd92018-08-23 19:04:04 +0800740_upload_max_retry_times_arg = CmdArg(
741 '--upload_max_retry_times', type=int, default=0,
742 help='Number of tries to upload. 0 to retry infinitely.')
Cheng-Han Yang3d4b0c02018-08-23 18:24:14 +0800743_upload_retry_interval_arg = CmdArg(
744 '--upload_retry_interval', type=int, default=None,
Cheng-Han Yang31a3bd92018-08-23 19:04:04 +0800745 help='Retry interval in seconds.')
Cheng-Han Yangc1697e22018-08-24 15:22:39 +0800746_upload_allow_fail_arg = CmdArg(
747 '--upload_allow_fail', action='store_true',
748 help='Continue finalize if report upload fails.')
Jon Salza88b83b2013-05-27 20:00:35 +0800749_add_file_cmd_arg = CmdArg(
750 '--add_file', metavar='FILE', action='append',
751 help='Extra file to include in report (must be an absolute path)')
752
Hung-Te Lin56b18402015-01-16 14:52:30 +0800753
Jon Salza88b83b2013-05-27 20:00:35 +0800754@Command('upload_report',
755 _upload_method_cmd_arg,
Cheng-Han Yang31a3bd92018-08-23 19:04:04 +0800756 _upload_max_retry_times_arg,
Cheng-Han Yang3d4b0c02018-08-23 18:24:14 +0800757 _upload_retry_interval_arg,
Cheng-Han Yangc1697e22018-08-24 15:22:39 +0800758 _upload_allow_fail_arg,
Jon Salza88b83b2013-05-27 20:00:35 +0800759 _add_file_cmd_arg)
760def UploadReport(options):
761 """Create a report containing key device details."""
Yong Hong65bda312018-12-13 20:05:58 +0800762 ro_vpd = vpd.VPDTool().GetAllData(partition=vpd.VPD_READONLY_PARTITION_NAME)
Jon Salza88b83b2013-05-27 20:00:35 +0800763 device_sn = ro_vpd.get('serial_number', None)
764 if device_sn is None:
765 logging.warning('RO_VPD missing device serial number')
Chun-Ta Lin53cbbd52016-06-08 21:42:19 +0800766 device_sn = 'MISSING_SN_' + time_utils.TimedUUID()
chuntsena6da2be2019-08-14 17:11:55 +0800767 target_path = CreateReportArchive(device_sn, options.add_file)
Jon Salza88b83b2013-05-27 20:00:35 +0800768
Tammo Spalink86a61c62012-05-25 15:10:35 +0800769 if options.upload_method is None or options.upload_method == 'none':
770 logging.warning('REPORT UPLOAD SKIPPED (report left at %s)', target_path)
771 return
772 method, param = options.upload_method.split(':', 1)
Cheng-Han Yang3d4b0c02018-08-23 18:24:14 +0800773
774 if options.upload_retry_interval is not None:
775 retry_interval = options.upload_retry_interval
776 else:
777 retry_interval = report_upload.DEFAULT_RETRY_INTERVAL
778
Tammo Spalink86a61c62012-05-25 15:10:35 +0800779 if method == 'shopfloor':
You-Cheng Syuf0f4be12017-12-05 16:33:53 +0800780 report_upload.ShopFloorUpload(
781 target_path, param,
Cheng-Han Yang3d4b0c02018-08-23 18:24:14 +0800782 'GRT' if options.command_name == 'finalize' else None,
Cheng-Han Yang31a3bd92018-08-23 19:04:04 +0800783 max_retry_times=options.upload_max_retry_times,
Cheng-Han Yangc1697e22018-08-24 15:22:39 +0800784 retry_interval=retry_interval,
785 allow_fail=options.upload_allow_fail)
Tammo Spalink86a61c62012-05-25 15:10:35 +0800786 elif method == 'ftp':
Cheng-Han Yang3d4b0c02018-08-23 18:24:14 +0800787 report_upload.FtpUpload(target_path, 'ftp:' + param,
Cheng-Han Yang31a3bd92018-08-23 19:04:04 +0800788 max_retry_times=options.upload_max_retry_times,
Cheng-Han Yangc1697e22018-08-24 15:22:39 +0800789 retry_interval=retry_interval,
790 allow_fail=options.upload_allow_fail)
Tammo Spalink86a61c62012-05-25 15:10:35 +0800791 elif method == 'ftps':
Cheng-Han Yang3d4b0c02018-08-23 18:24:14 +0800792 report_upload.CurlUrlUpload(target_path, '--ftp-ssl-reqd ftp:%s' % param,
Cheng-Han Yang31a3bd92018-08-23 19:04:04 +0800793 max_retry_times=options.upload_max_retry_times,
Cheng-Han Yangc1697e22018-08-24 15:22:39 +0800794 retry_interval=retry_interval,
795 allow_fail=options.upload_allow_fail)
Tammo Spalink86a61c62012-05-25 15:10:35 +0800796 elif method == 'cpfe':
Cheng-Han Yang3d4b0c02018-08-23 18:24:14 +0800797 report_upload.CpfeUpload(target_path, pipes.quote(param),
Cheng-Han Yang31a3bd92018-08-23 19:04:04 +0800798 max_retry_times=options.upload_max_retry_times,
Cheng-Han Yangc1697e22018-08-24 15:22:39 +0800799 retry_interval=retry_interval,
800 allow_fail=options.upload_allow_fail)
Kevin Line4c64de2019-11-22 15:28:34 +0800801 elif method == 'smb':
802 # param should be in form: <dest_path>.
803 report_upload.SmbUpload(target_path, 'smb:' + param,
804 max_retry_times=options.upload_max_retry_times,
805 retry_interval=retry_interval,
806 allow_fail=options.upload_allow_fail)
Tammo Spalink86a61c62012-05-25 15:10:35 +0800807 else:
Peter Shihbf6f22b2018-02-26 14:05:28 +0800808 raise Error('unknown report upload method %r' % method)
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800809
810
811@Command('finalize',
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800812 CmdArg('--fast', action='store_true',
813 help='use non-secure but faster wipe method.'),
Yong Hongb2926bd2018-10-12 14:11:14 +0800814 _no_ectool_cmd_arg,
Shun-Hsing Oudb407d62015-11-11 11:03:59 +0800815 _shopfloor_url_args_cmd_arg,
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800816 _hwdb_path_cmd_arg,
Tammo Spalink95c43732012-07-25 15:57:14 -0700817 _hwid_status_list_cmd_arg,
Jon Salz65266432012-07-30 19:02:49 +0800818 _upload_method_cmd_arg,
Cheng-Han Yang31a3bd92018-08-23 19:04:04 +0800819 _upload_max_retry_times_arg,
Cheng-Han Yang3d4b0c02018-08-23 18:24:14 +0800820 _upload_retry_interval_arg,
Cheng-Han Yangc1697e22018-08-24 15:22:39 +0800821 _upload_allow_fail_arg,
Jon Salzce124fb2012-10-02 17:42:03 +0800822 _add_file_cmd_arg,
823 _probe_results_cmd_arg,
Cheng-Yi Chiang406ad912013-11-14 16:51:33 +0800824 _hwid_cmd_arg,
Yong Hong68a0e0d2017-12-20 19:06:54 +0800825 _hwid_run_vpd_cmd_arg,
826 _hwid_vpd_data_file_cmd_arg,
Cheng-Han Yang663763b2020-09-15 20:46:23 +0800827 _no_write_protect_cmd_arg,
Chih-Yu Huang714dbc42015-07-21 16:42:16 +0800828 _rma_mode_cmd_arg,
bowgotsai13820f42015-09-10 23:18:04 +0800829 _cros_core_cmd_arg,
Pin-Yen Lin215b7542020-05-05 09:45:37 +0800830 _has_ec_pubkey_cmd_arg,
Yilun Lin34f54802017-11-16 11:58:25 +0800831 _ec_pubkey_path_cmd_arg,
832 _ec_pubkey_hash_cmd_arg,
Hung-Te Lincdb96522016-04-15 16:51:10 +0800833 _release_rootfs_cmd_arg,
834 _firmware_path_cmd_arg,
Wei-Han Chenbe1355a2016-04-24 19:31:03 +0800835 _enforced_release_channels_cmd_arg,
836 _station_ip_cmd_arg,
837 _station_port_cmd_arg,
Ting Shen18a06382016-08-30 16:18:21 +0800838 _wipe_finish_token_cmd_arg,
Wei-Han Cheneb4f9a22018-03-09 14:52:23 +0800839 _rlz_embargo_end_date_offset_cmd_arg,
Wei-Han Chen60c5d332017-01-05 17:15:10 +0800840 _waive_list_cmd_arg,
chuntsenaf1232f2019-03-20 15:45:54 +0800841 _skip_list_cmd_arg,
Stimim Chenc9fbdfc2020-05-21 17:00:53 +0800842 _no_generate_mfg_date_cmd_arg,
843 _enable_zero_touch_cmd_arg)
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800844def Finalize(options):
845 """Verify system readiness and trigger transition into release state.
846
Jon Salzaa3a30e2013-05-15 15:56:28 +0800847 This routine does the following:
848 - Verifies system state (see verify command)
Jon Salzfe9036f2014-01-16 14:11:23 +0800849 - Untars stateful_files.tar.xz, if it exists, in the stateful partition, to
850 initialize files such as the CRX cache
Jon Salzaa3a30e2013-05-15 15:56:28 +0800851 - Modifies firmware bitmaps to match locale
852 - Clears all factory-friendly flags from the GBB
853 - Removes factory-specific entries from RW_VPD (factory.*)
854 - Enables firmware write protection (cannot rollback after this)
Marco Chenecee04f2019-02-15 22:24:24 +0800855 - Initialize Fpmcu entropy
Jon Salzaa3a30e2013-05-15 15:56:28 +0800856 - Uploads system logs & reports
Earl Ou51182222016-09-09 12:16:48 +0800857 - Wipes the testing kernel, rootfs, and stateful partition
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800858 """
Wei-Han Cheneb4f9a22018-03-09 14:52:23 +0800859 if not options.rma_mode:
860 # Write VPD values related to RLZ ping into VPD.
861 GetGooftool(options).WriteVPDForRLZPing(options.embargo_offset)
chuntsenaf1232f2019-03-20 15:45:54 +0800862 if options.generate_mfg_date:
863 GetGooftool(options).WriteVPDForMFGDate()
Cheng-Han Yang663763b2020-09-15 20:46:23 +0800864 Cr50Finalize(options)
Marco Chen9d0631c2018-08-31 10:52:44 +0800865 Verify(options)
Jon Salz40b9f822014-07-25 16:39:55 +0800866 LogSourceHashes(options)
Jon Salzfe9036f2014-01-16 14:11:23 +0800867 UntarStatefulFiles(options)
Chih-Yu Huang714dbc42015-07-21 16:42:16 +0800868 if options.cros_core:
869 logging.info('SetFirmwareBitmapLocale is skipped for ChromeOS Core device.')
870 else:
871 SetFirmwareBitmapLocale(options)
Jon Salzaa3a30e2013-05-15 15:56:28 +0800872 ClearFactoryVPDEntries(options)
Mattias Nisslercca761b2015-04-15 21:53:04 +0200873 GenerateStableDeviceSecret(options)
Shen-En Shih3e079b22017-09-11 05:43:09 -0700874 ClearGBBFlags(options)
Hung-Te Lin6d827542012-07-19 11:50:41 +0800875 if options.no_write_protect:
Pi-Hsun Shih1f569a72019-12-26 11:23:56 +0800876 logging.warning('WARNING: Firmware Write Protection is SKIPPED.')
Andy Cheng0465d132013-03-20 12:12:06 +0800877 event_log.Log('wp', fw='both', status='skipped')
Hung-Te Lin6d827542012-07-19 11:50:41 +0800878 else:
Wei-Han Chenba21f512016-10-14 18:52:33 +0800879 EnableFwWp(options)
Marco Chenecee04f2019-02-15 22:24:24 +0800880 FpmcuInitializeEntropy(options)
Jon Salza0f58e02012-05-29 19:33:39 +0800881 LogSystemDetails(options)
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800882 UploadReport(options)
Earl Ou51182222016-09-09 12:16:48 +0800883
884 event_log.Log('wipe_in_place')
885 wipe_args = []
Earl Ou51182222016-09-09 12:16:48 +0800886 if options.shopfloor_url:
887 wipe_args += ['--shopfloor_url', options.shopfloor_url]
888 if options.fast:
889 wipe_args += ['--fast']
890 if options.station_ip:
891 wipe_args += ['--station_ip', options.station_ip]
892 if options.station_port:
893 wipe_args += ['--station_port', options.station_port]
894 if options.wipe_finish_token:
895 wipe_args += ['--wipe_finish_token', options.wipe_finish_token]
896 ExecFactoryPar('gooftool', 'wipe_in_place', *wipe_args)
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800897
898
Ting Shen129fa6f2016-09-02 12:22:24 +0800899@Command('verify_hwid',
900 _probe_results_cmd_arg,
901 _hwdb_path_cmd_arg,
902 _hwid_cmd_arg,
Yong Hong68a0e0d2017-12-20 19:06:54 +0800903 _hwid_run_vpd_cmd_arg,
904 _hwid_vpd_data_file_cmd_arg,
Ting Shen129fa6f2016-09-02 12:22:24 +0800905 _rma_mode_cmd_arg)
906def VerifyHWID(options):
Ricky Liangc662be32013-12-24 11:50:23 +0800907 """A simple wrapper that calls out to HWID utils to verify version 3 HWID.
Ricky Liang53390232013-03-08 15:37:57 +0800908
Ricky Liangc662be32013-12-24 11:50:23 +0800909 This is mainly for Gooftool to verify v3 HWID during finalize. For testing
910 and development purposes, please use `hwid` command.
Ricky Liang53390232013-03-08 15:37:57 +0800911 """
Yong Hongada8e0e2018-01-04 16:36:21 +0800912 database = GetGooftool(options).db
Yong Hong68a0e0d2017-12-20 19:06:54 +0800913
Yong Hongada8e0e2018-01-04 16:36:21 +0800914 encoded_string = options.hwid or GetGooftool(options).ReadHWID()
915
916 probed_results = hwid_utils.GetProbedResults(infile=options.probe_results)
Yong Hong2c39bf22018-01-24 22:24:11 +0800917 device_info = hwid_utils.GetDeviceInfo()
Yong Hong65bda312018-12-13 20:05:58 +0800918 vpd_data = hwid_utils.GetVPDData(run_vpd=options.hwid_run_vpd,
919 infile=options.hwid_vpd_data_file)
Ricky Liang53390232013-03-08 15:37:57 +0800920
Hung-Te Lin11052952015-03-18 13:48:59 +0800921 event_log.Log('probed_results', probed_results=FilterDict(probed_results))
Yong Hong65bda312018-12-13 20:05:58 +0800922 event_log.Log('vpd', vpd=FilterDict(vpd_data))
Ricky Liang53390232013-03-08 15:37:57 +0800923
Yong Hong2c39bf22018-01-24 22:24:11 +0800924 hwid_utils.VerifyHWID(database, encoded_string, probed_results,
Yong Hong65bda312018-12-13 20:05:58 +0800925 device_info, vpd_data, options.rma_mode)
Ricky Liang53390232013-03-08 15:37:57 +0800926
Ricky Liangc662be32013-12-24 11:50:23 +0800927 event_log.Log('verified_hwid', hwid=encoded_string)
Ricky Liang53390232013-03-08 15:37:57 +0800928
929
henryhsu44d793a2013-07-20 00:07:38 +0800930@Command('get_firmware_hash',
Marco Chence70b132018-05-03 23:43:39 +0800931 CmdArg('--file', required=True, metavar='FILE', help='Firmware File.'))
henryhsu44d793a2013-07-20 00:07:38 +0800932def GetFirmwareHash(options):
henryhsuf6f835c2013-07-20 20:49:25 +0800933 """Get firmware hash from a file"""
henryhsu44d793a2013-07-20 00:07:38 +0800934 if os.path.exists(options.file):
Cheng-Han Yang2c668ae2018-04-18 22:31:07 +0800935 value_dict = chromeos_firmware.CalculateFirmwareHashes(options.file)
Yilin Yang879fbda2020-05-14 13:52:30 +0800936 for key, value in value_dict.items():
Yilin Yang71e39412019-09-24 09:26:46 +0800937 print(' %s: %s' % (key, value))
henryhsu44d793a2013-07-20 00:07:38 +0800938 else:
939 raise Error('File does not exist: %s' % options.file)
940
henryhsuf6f835c2013-07-20 20:49:25 +0800941
Philip Chen04fb90b2019-11-06 12:10:33 -0800942@Command('fpmcu_initialize_entropy')
Marco Chenecee04f2019-02-15 22:24:24 +0800943def FpmcuInitializeEntropy(options):
944 """Initialze entropy of FPMCU."""
Philip Chen04fb90b2019-11-06 12:10:33 -0800945
946 if HasFpmcu():
Marco Chenecee04f2019-02-15 22:24:24 +0800947 GetGooftool(options).FpmcuInitializeEntropy()
Philip Chen04fb90b2019-11-06 12:10:33 -0800948 else:
949 logging.info('No FPS on this board.')
Marco Chenecee04f2019-02-15 22:24:24 +0800950
951
Peter Shihfdf17682017-05-26 11:38:39 +0800952def main():
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800953 """Run sub-command specified by the command line args."""
Andy Cheng7a76cb82012-11-19 18:08:19 +0800954
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800955 options = ParseCmdline(
Ting Shen129fa6f2016-09-02 12:22:24 +0800956 'Perform Google required factory tests.',
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800957 CmdArg('-l', '--log', metavar='PATH',
958 help='Write logs to this file.'),
Jon Salza4bea382012-10-29 13:00:34 +0800959 CmdArg('--suppress-event-logs', action='store_true',
960 help='Suppress event logging.'),
Wei-Han Chenaff56232016-04-16 09:17:59 +0800961 CmdArg('--phase', default=None,
962 help=('override phase for phase checking (defaults to the current '
963 'as returned by the "factory phase" command)')),
Wei-Han Chenb34bdff2019-09-26 13:07:50 +0800964 VERBOSITY_CMD_ARG)
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800965 SetupLogging(options.verbosity, options.log)
Andy Cheng0465d132013-03-20 12:12:06 +0800966 event_log.SetGlobalLoggerDefaultPrefix('gooftool')
967 event_log.GetGlobalLogger().suppress = options.suppress_event_logs
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800968 logging.debug('gooftool options: %s', repr(options))
Wei-Han Chenaff56232016-04-16 09:17:59 +0800969
970 phase.OverridePhase(options.phase)
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800971 try:
972 logging.debug('GOOFTOOL command %r', options.command_name)
973 options.command(options)
974 logging.info('GOOFTOOL command %r SUCCESS', options.command_name)
Peter Shih6674ecf2018-03-29 14:04:57 +0800975 except Error as e:
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800976 logging.exception(e)
977 sys.exit('GOOFTOOL command %r ERROR: %s' % (options.command_name, e))
Peter Shih6674ecf2018-03-29 14:04:57 +0800978 except Exception as e:
Tammo Spalink9a96b8a2012-04-03 11:10:41 +0800979 logging.exception(e)
980 sys.exit('UNCAUGHT RUNTIME EXCEPTION %s' % e)
981
982
983if __name__ == '__main__':
Peter Shihfdf17682017-05-26 11:38:39 +0800984 main()