File: statistics_provider_impl.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (737 lines) | stat: -rw-r--r-- 26,291 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromeos/ash/components/system/statistics_provider_impl.h"

#include <memory>
#include <string>
#include <string_view>
#include <type_traits>
#include <utility>

#include "ash/constants/ash_paths.h"
#include "ash/constants/ash_switches.h"
#include "base/check.h"
#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/containers/fixed_flat_map.h"
#include "base/files/file_util.h"
#include "base/json/json_file_value_serializer.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_functions.h"
#include "base/path_service.h"
#include "base/process/launch.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/system/sys_info.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/task_runner.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/threading/thread_restrictions.h"
#include "base/time/time.h"
#include "base/values.h"
#include "chromeos/ash/components/system/kiosk_oem_manifest_parser.h"

namespace ash::system {

namespace {

// Path to the tool used to get system info, and special values for the
// output of the tool.
const char kCrosSystemTool[] = "/usr/bin/crossystem";
const char kCrosSystemValueError[] = "(error)";

// Path to the tool to get VPD info.
const char kFilteredVpdTool[] = "/usr/sbin/dump_filtered_vpd";

// Exit codes for the dump_filtered_vpd tool.
enum class DumpVpdExitCodes : int {
  kValid = 0,
  kRoInvalid = 1,
  kRwInvalid = 2,
  kBothInvalid = kRoInvalid | kRwInvalid,
};

// The location of OEM manifest file used to trigger OOBE flow for kiosk mode.
const base::CommandLine::CharType kOemManifestFilePath[] =
    FILE_PATH_LITERAL("/usr/share/oem/oobe/manifest.json");

// File to get regional data from.
const char kCrosRegions[] = "/usr/share/misc/cros-regions.json";

const char kHardwareClassCrosSystemKey[] = "hwid";
const char kHardwareClassValueUnknown[] = "unknown";

const char kIsVmCrosSystemKey[] = "inside_vm";

// ChromeOS should allow debug features.
const char kIsCrosDebugCrosSystemKey[] = "cros_debug";

// Items in region dictionary.
const char kKeyboardsPath[] = "keyboards";
const char kLocalesPath[] = "locales";
const char kTimeZonesPath[] = "time_zones";
const char kKeyboardMechanicalLayoutPath[] = "keyboard_mechanical_layout";

// Timeout that we should wait for statistics to get loaded.
constexpr base::TimeDelta kLoadTimeout = base::Seconds(3);

// A default activation date for providing results in tests.
constexpr char kDefaultActivateDateStub[] = "2000-01";

constexpr char kStatisticLoadingTimeMetricNamePrefix[] =
    "ChromeOS.MachineStatistic.";

// Gets the list from the given `dictionary` by given `key`, and returns it as a
// string with all list values joined by ','. Returns nullopt if `key` is not
// found.
std::optional<std::string> JoinListValuesToString(
    const base::Value::Dict& dictionary,
    std::string_view key) {
  const base::Value::List* list_value = dictionary.FindList(key);
  if (list_value == nullptr) {
    return std::nullopt;
  }

  std::string buffer;
  bool first = true;
  for (const auto& v : *list_value) {
    const std::string* value = v.GetIfString();
    if (!value) {
      return std::nullopt;
    }

    if (first) {
      first = false;
    } else {
      buffer += ',';
    }

    buffer += *value;
  }

  return buffer;
}

// Gets the list from the given `dictionary` by given `key`, and returns the
// first value of the list as string. Returns nullopt if `key` is not found.
std::optional<std::string> GetFirstListValueAsString(
    const base::Value::Dict& dictionary,
    std::string_view key) {
  const base::Value::List* list_value = dictionary.FindList(key);
  if (list_value == nullptr || list_value->empty()) {
    return std::nullopt;
  }

  const std::string* value = list_value->begin()->GetIfString();
  if (value == nullptr) {
    return std::nullopt;
  }

  return *value;
}

std::optional<std::string> GetKeyboardLayoutFromRegionalData(
    const base::Value::Dict& region_dict) {
  return JoinListValuesToString(region_dict, kKeyboardsPath);
}

std::optional<std::string> GetKeyboardMechanicalLayoutFromRegionalData(
    const base::Value::Dict& region_dict) {
  const std::string* value =
      region_dict.FindString(kKeyboardMechanicalLayoutPath);
  if (value == nullptr) {
    return std::nullopt;
  }

  return *value;
}

std::optional<std::string> GetInitialTimezoneFromRegionalData(
    const base::Value::Dict& region_dict) {
  return GetFirstListValueAsString(region_dict, kTimeZonesPath);
}

std::optional<std::string> GetInitialLocaleFromRegionalData(
    const base::Value::Dict& region_dict) {
  return JoinListValuesToString(region_dict, kLocalesPath);
}

// Array mapping region keys to their extracting functions.
constexpr std::pair<const char*,
                    std::optional<std::string> (*)(const base::Value::Dict&)>
    kRegionKeysToExtractors[] = {
        {kInitialLocaleKey, &GetInitialLocaleFromRegionalData},
        {kKeyboardLayoutKey, &GetKeyboardLayoutFromRegionalData},
        {kKeyboardMechanicalLayoutKey,
         &GetKeyboardMechanicalLayoutFromRegionalData},
        {kInitialTimezoneKey, &GetInitialTimezoneFromRegionalData}};

base::FilePath GetFilePathIgnoreFailure(int key) {
  base::FilePath file_path;
  base::PathService::Get(key, &file_path);

  return file_path;
}

bool HasOemPrefix(std::string_view name) {
  return name.substr(0, 4) == "oem_";
}

StatisticsProviderImpl::StatisticsSources CreateDefaultSources() {
  StatisticsProviderImpl::StatisticsSources sources;
  sources.crossystem_tool = base::CommandLine(base::FilePath(kCrosSystemTool));
  sources.vpd_tool = base::CommandLine(base::FilePath(kFilteredVpdTool));
  sources.machine_info_filepath = GetFilePathIgnoreFailure(FILE_MACHINE_INFO);
  sources.oem_manifest_filepath = base::FilePath(kOemManifestFilePath);
  sources.cros_regions_filepath = base::FilePath(kCrosRegions);
  return sources;
}

// Maps machine statistic name to the MachineStatistic variant in
// tools/metrics/histograms/metadata/chromeos/histograms.xml.
std::string_view StatisticNameToMachineStatisticVariant(
    std::string_view statistic_name) {
  static constexpr auto kStatisticNameToVariant =
      base::MakeFixedFlatMap<std::string_view, std::string_view>({
          {kActivateDateKey, "ActivateDate"},
          {kBlockDevModeKey, "BlockDevmode"},
          {kCheckEnrollmentKey, "CheckEnrollment"},
          {kShouldSendRlzPingKey, "ShouldSendRlzPing"},
          {kRlzEmbargoEndDateKey, "RlzEmbargoEndDate"},
          {kCustomizationIdKey, "CustomizationId"},
          {kDevSwitchBootKey, "DevswBoot"},
          {kDockMacAddressKey, "DockMac"},
          {kEthernetMacAddressKey, "EthernetMac"},
          {kFirmwareWriteProtectCurrentKey, "WpswCur"},
          {kFirmwareTypeKey, "MainfwType"},
          {kHardwareClassKey, "HardwareClass"},
          {kIsVmKey, "IsVm"},
          {kIsCrosDebugKey, "IsCrosDebug"},
          {kMachineModelName, "ModelName"},
          {kMachineOemName, "OemName"},
          {kManufactureDateKey, "MfgDate"},
          {kOffersCouponCodeKey, "UbindAttribute"},
          {kOffersGroupCodeKey, "GbindAttribute"},
          {kRlzBrandCodeKey, "RlzBrandCode"},
          {kRegionKey, "Region"},
          {kSerialNumberKey, "SerialNumber"},
          {kFlexIdKey, "FlexId"},
          {kLegacySerialNumberKey, "LegacySerialNumber"},
          {kInitialLocaleKey, "InitialLocale"},
          {kInitialTimezoneKey, "InitialTimezone"},
          {kKeyboardLayoutKey, "KeyboardLayout"},
          {kKeyboardMechanicalLayoutKey, "KeyboardMechanicalLayout"},
          {kAttestedDeviceIdKey, "AttestedDeviceId"},
          {kDisplayProfilesKey, "DisplayProfiles"},
          {kOemCanExitEnterpriseEnrollmentKey, "OemCanExitEnrollment"},
          {kOemDeviceRequisitionKey, "OemDeviceRequisition"},
          {kOemIsEnterpriseManagedKey, "OemEnterpriseManaged"},
          {kOemKeyboardDrivenOobeKey, "OemKeyboardDrivenOobe"},
      });

  if (const auto it = kStatisticNameToVariant.find(statistic_name);
      it != kStatisticNameToVariant.end()) {
    return it->second;
  }

  LOG(WARNING) << "Unhandled statistic is recorded: " << statistic_name;
  return statistic_name;
}

void RecordStatisticsRequestLoadingTimeMetric(std::string_view statistic_name,
                                              base::TimeDelta loading_time) {
  // Loading time is expected to be 0 (when requested statistic is already
  // loaded), or up to short time of `kLoadTimeout`.
  const std::string metric_name = base::StrCat(
      {kStatisticLoadingTimeMetricNamePrefix,
       StatisticNameToMachineStatisticVariant(statistic_name), ".LoadingTime"});
  base::UmaHistogramTimes(metric_name, loading_time);
}

}  // namespace

StatisticsProviderImpl::StatisticsSources::StatisticsSources() = default;

StatisticsProviderImpl::StatisticsSources::~StatisticsSources() = default;

StatisticsProviderImpl::StatisticsSources::StatisticsSources(
    const StatisticsSources& other) = default;
StatisticsProviderImpl::StatisticsSources&
StatisticsProviderImpl::StatisticsSources::operator=(
    const StatisticsSources& other) = default;

StatisticsProviderImpl::StatisticsSources::StatisticsSources(
    StatisticsSources&& other) = default;
StatisticsProviderImpl::StatisticsSources&
StatisticsProviderImpl::StatisticsSources::operator=(
    StatisticsSources&& other) = default;

// static
std::unique_ptr<StatisticsProviderImpl>
StatisticsProviderImpl::CreateProviderForTesting(
    StatisticsSources testing_sources) {
  // Using `new` to access a non-public constructor.
  return base::WrapUnique(
      new StatisticsProviderImpl(std::move(testing_sources)));
}

StatisticsProviderImpl::StatisticsProviderImpl()
    : StatisticsProviderImpl(CreateDefaultSources()) {}

StatisticsProviderImpl::StatisticsProviderImpl(StatisticsSources sources)
    : sources_(std::move(sources)),
      loading_state_(LoadingState::kNotStarted),
      oem_manifest_loaded_(false),
      statistics_loaded_(base::WaitableEvent::ResetPolicy::MANUAL,
                         base::WaitableEvent::InitialState::NOT_SIGNALED) {}

StatisticsProviderImpl::~StatisticsProviderImpl() = default;

void StatisticsProviderImpl::StartLoadingMachineStatistics(
    bool load_oem_manifest) {
  CHECK(!HasLoadingStarted());
  loading_state_ = LoadingState::kStarted;

  VLOG(1) << "Started loading statistics. Load OEM Manifest: "
          << load_oem_manifest;

  // TaskPriority::USER_BLOCKING because this is on the critical path of
  // rendering the NTP on startup. https://crbug.com/831835
  base::ThreadPool::PostTask(
      FROM_HERE,
      {base::MayBlock(), base::TaskPriority::USER_BLOCKING,
       base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
      base::BindOnce(&StatisticsProviderImpl::LoadMachineStatistics,
                     base::Unretained(this), load_oem_manifest));
}

void StatisticsProviderImpl::ScheduleOnMachineStatisticsLoaded(
    base::OnceClosure callback) {
  {
    // It is important to hold `statistics_loaded_lock_` when checking the
    // `statistics_loaded_` event to make sure that its state doesn't change
    // before `callback` is added to `statistics_loaded_callbacks_`.
    base::AutoLock auto_lock(statistics_loaded_lock_);

    // Machine statistics are not loaded yet. Add `callback` to a list to be
    // scheduled once machine statistics are loaded.
    if (!statistics_loaded_.IsSignaled()) {
      statistics_loaded_callbacks_.emplace_back(
          std::move(callback), base::SequencedTaskRunner::GetCurrentDefault());
      return;
    }
  }

  // Machine statistics are loaded. Schedule `callback` immediately.
  base::SequencedTaskRunner::GetCurrentDefault()->PostTask(FROM_HERE,
                                                           std::move(callback));
}

std::optional<std::string_view> StatisticsProviderImpl::GetMachineStatistic(
    std::string_view name) {
  VLOG(1) << "Machine Statistic requested: " << name;
  if (!WaitForStatisticsLoaded(name)) {
    LOG(ERROR) << "GetMachineStatistic called before load started: " << name;
    return std::nullopt;
  }

  // Test region should override any other value.
  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kCrosRegion)) {
    if (const std::optional<std::string_view> region_result =
            GetRegionalInformation(name)) {
      return region_result;
    }
  }

  if (const auto iter = machine_info_.find(name); iter != machine_info_.end()) {
    return std::string_view(iter->second);
  }

  if (const std::optional<std::string_view> region_result =
          GetRegionalInformation(name)) {
    return region_result;
  }

  if (base::SysInfo::IsRunningOnChromeOS() &&
      (oem_manifest_loaded_ || !HasOemPrefix(name))) {
    VLOG(1) << "Requested statistic not found: " << name;
  }

  return std::nullopt;
}

StatisticsProviderImpl::FlagValue StatisticsProviderImpl::GetMachineFlag(
    std::string_view name) {
  VLOG(1) << "Machine Flag requested: " << name;
  if (!WaitForStatisticsLoaded(name)) {
    LOG(ERROR) << "GetMachineFlag called before load started: " << name;
    return FlagValue::kUnset;
  }

  if (const auto iter = machine_flags_.find(name);
      iter != machine_flags_.end()) {
    return iter->second ? FlagValue::kTrue : FlagValue::kFalse;
  }

  if (base::SysInfo::IsRunningOnChromeOS() &&
      (oem_manifest_loaded_ || !HasOemPrefix(name))) {
    VLOG(1) << "Requested machine flag not found: " << name;
  }

  return FlagValue::kUnset;
}

void StatisticsProviderImpl::Shutdown() {
  cancellation_flag_.Set();  // Cancel any pending loads
}

bool StatisticsProviderImpl::IsRunningOnVm() {
  if (!base::SysInfo::IsRunningOnChromeOS()) {
    return false;
  }
  return GetMachineStatistic(kIsVmKey) == kIsVmValueTrue;
}

bool StatisticsProviderImpl::IsCrosDebugMode() {
  if (!base::SysInfo::IsRunningOnChromeOS()) {
    return false;
  }
  return GetMachineStatistic(kIsCrosDebugKey) == kIsCrosDebugValueTrue;
}

StatisticsProvider::VpdStatus StatisticsProviderImpl::GetVpdStatus() const {
  return vpd_status_;
}

StatisticsProvider::LoadingState StatisticsProviderImpl::GetLoadingState()
    const {
  return loading_state_;
}

void StatisticsProviderImpl::SignalStatisticsLoaded() {
  decltype(statistics_loaded_callbacks_) local_statistics_loaded_callbacks;

  {
    base::AutoLock auto_lock(statistics_loaded_lock_);

    // Move all callbacks to a local variable.
    local_statistics_loaded_callbacks = std::move(statistics_loaded_callbacks_);

    // Prevent new callbacks from being added to `statistics_loaded_callbacks_`
    // and unblock pending WaitForStatisticsLoaded() calls.
    statistics_loaded_.Signal();

    VLOG(1) << "Finished loading statistics.";
  }

  // Schedule callbacks that were in `statistics_loaded_callbacks_`.
  for (auto& callback : local_statistics_loaded_callbacks) {
    callback.second->PostTask(FROM_HERE, std::move(callback.first));
  }
}

bool StatisticsProviderImpl::WaitForStatisticsLoaded(
    std::string_view statistic_name) {
  CHECK(HasLoadingStarted());
  if (statistics_loaded_.IsSignaled()) {
    RecordStatisticsRequestLoadingTimeMetric(
        statistic_name,
        /*loading_time=*/base::TimeDelta());
    return true;
  }

  // Block if the statistics are not loaded yet. Normally this shouldn't
  // happen except during OOBE.
  const base::Time start_time = base::Time::Now();
  base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope allow_wait;
  statistics_loaded_.TimedWait(kLoadTimeout);

  const base::TimeDelta dtime = base::Time::Now() - start_time;

  RecordStatisticsRequestLoadingTimeMetric(statistic_name, dtime);

  if (statistics_loaded_.IsSignaled()) {
    VLOG(1) << "Statistics loaded after waiting " << dtime.InMilliseconds()
            << "ms.";
    return true;
  }

  LOG(ERROR) << "Statistics not loaded after waiting " << dtime.InMilliseconds()
             << "ms.";
  return false;
}

void StatisticsProviderImpl::LoadMachineStatistics(bool load_oem_manifest) {
  // Run from the file task runner. StatisticsProviderImpl is a Singleton<> and
  // will not be destroyed until after threads have been stopped, so this test
  // is always safe.
  if (cancellation_flag_.IsSet()) {
    return;
  }

  LoadCrossystemTool();

  std::string crossystem_wpsw;

  if (base::SysInfo::IsRunningOnChromeOS()) {
    // If available, the key should be taken from machine info or VPD instead of
    // the tool. If not available, the tool's value will be restored.
    auto it = machine_info_.find(kFirmwareWriteProtectCurrentKey);
    if (it != machine_info_.end()) {
      crossystem_wpsw = it->second;
      machine_info_.erase(it);
    }
  }

  LoadMachineInfoFile();
  LoadVpd();

  // Ensure that the hardware class key is present with the expected
  // key name, and if it couldn't be retrieved, that the value is "unknown".
  std::string hardware_class = machine_info_[kHardwareClassCrosSystemKey];
  machine_info_[kHardwareClassKey] =
      !hardware_class.empty() ? hardware_class : kHardwareClassValueUnknown;

  if (base::SysInfo::IsRunningOnChromeOS()) {
    // By default, assume that this is *not* a VM. If crossystem is not present,
    // report that we are not in a VM.
    machine_info_[kIsVmKey] = kIsVmValueFalse;
    const auto is_vm_iter = machine_info_.find(kIsVmCrosSystemKey);
    if (is_vm_iter != machine_info_.end() &&
        is_vm_iter->second == kIsVmValueTrue) {
      machine_info_[kIsVmKey] = kIsVmValueTrue;
    }

    // By default, assume that this is *not* in debug mode. If crossystem is not
    // present, report that we are not in debug mode.
    machine_info_[kIsCrosDebugKey] = kIsCrosDebugValueFalse;
    const auto is_debug_iter = machine_info_.find(kIsCrosDebugCrosSystemKey);
    if (is_debug_iter != machine_info_.end() &&
        is_debug_iter->second == kIsCrosDebugValueTrue) {
      machine_info_[kIsCrosDebugKey] = kIsCrosDebugValueTrue;
    }

    // Use the write-protect value from crossystem only if it hasn't been loaded
    // from any other source, since the result of crossystem is less reliable
    // for this key.
    if (!base::Contains(machine_info_, kFirmwareWriteProtectCurrentKey) &&
        !crossystem_wpsw.empty()) {
      LOG(WARNING) << "wpsw_cur missing from machine_info, using value: "
                   << crossystem_wpsw;
      machine_info_[kFirmwareWriteProtectCurrentKey] = crossystem_wpsw;
    }

    // TODO(b/315929204): Remove temporary logging.
    if (machine_info_.find(kFirmwareWriteProtectCurrentKey) ==
        machine_info_.end()) {
      LOG(WARNING) << "Write-protect value unknown.";
    } else if (machine_info_[kFirmwareWriteProtectCurrentKey] != "1") {
      LOG(WARNING) << "Write-protect disabled.";
    }
  }

  if (load_oem_manifest) {
    // If kAppOemManifestFile switch is specified, load OEM Manifest file.
    base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
    if (command_line->HasSwitch(switches::kAppOemManifestFile)) {
      LoadOemManifestFromFile(
          command_line->GetSwitchValuePath(switches::kAppOemManifestFile));
    } else if (base::SysInfo::IsRunningOnChromeOS()) {
      LoadOemManifestFromFile(sources_.oem_manifest_filepath);
    }
  }

  // Set region from command line if present.
  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(switches::kCrosRegion)) {
    const std::string region =
        command_line->GetSwitchValueASCII(switches::kCrosRegion);
    machine_info_[kRegionKey] = region;
    VLOG(1) << "CrOS region set to '" << region << "'";
  }

  const auto it = machine_info_.find(kRegionKey);

  LoadRegionsFile(sources_.cros_regions_filepath,
                  it != machine_info_.end() ? it->second : "");

  loading_state_ = LoadingState::kFinished;
  SignalStatisticsLoaded();
}

void StatisticsProviderImpl::LoadCrossystemTool() {
  if (!base::SysInfo::IsRunningOnChromeOS()) {
    return;
  }

  NameValuePairsParser parser(&machine_info_);
  // Parse all of the key/value pairs from the crossystem tool.
  if (!parser.ParseNameValuePairsFromTool(sources_.crossystem_tool,
                                          NameValuePairsFormat::kCrossystem)) {
    LOG(ERROR) << "Errors parsing output from: "
               << sources_.crossystem_tool.GetProgram();
  }

  // Drop useless "(error)" values so they don't displace valid values
  // supplied later by other tools: https://crbug.com/844258
  parser.DeletePairsWithValue(kCrosSystemValueError);
}

void StatisticsProviderImpl::LoadMachineInfoFile() {
  if (!base::PathExists(sources_.machine_info_filepath)) {
    if (base::SysInfo::IsRunningOnChromeOS()) {
      // This is unexpected, since the file is supposed to always be populated
      // by write-machine-info script on ui start.
      LOG(ERROR) << "Missing machine info: " << sources_.machine_info_filepath;
      return;
    }

    // Use time value to create an unique stub serial because clashes of the
    // same serial for the same domain invalidate earlier enrollments. Persist
    // to disk to keep it constant across restarts (required for re-enrollment
    // testing).
    std::string stub_contents =
        "\"serial_number\"=\"stub_" +
        base::NumberToString(base::Time::Now().InMillisecondsSinceUnixEpoch()) +
        "\"\n";
    if (!base::WriteFile(sources_.machine_info_filepath, stub_contents)) {
      PLOG(ERROR) << "Error writing machine info stub "
                  << sources_.machine_info_filepath;
    }
  }

  // The machine-info file is generated only for OOBE and enterprise enrollment
  // and may not be present. See login-manager/init/machine-info.conf.
  NameValuePairsParser(&machine_info_)
      .ParseNameValuePairsFromFile(sources_.machine_info_filepath,
                                   NameValuePairsFormat::kMachineInfo);
}

void StatisticsProviderImpl::LoadVpd() {
  if (!base::SysInfo::IsRunningOnChromeOS()) {
    machine_info_[kActivateDateKey] = kDefaultActivateDateStub;
    vpd_status_ = VpdStatus::kInvalid;
    return;
  }

  NameValuePairsParser parser(&machine_info_);

  std::string output;
  int exit_code;
  if (!base::GetAppOutputWithExitCode(sources_.vpd_tool, &output, &exit_code)) {
    LOG(ERROR) << "Failed to run VPD tool: " << sources_.vpd_tool.GetProgram();
    vpd_status_ = VpdStatus::kInvalid;
    return;
  }
  if (!parser.ParseNameValuePairsFromString(output,
                                            NameValuePairsFormat::kVpdDump)) {
    LOG(ERROR) << "Errors parsing output from: "
               << sources_.vpd_tool.GetProgram();
    vpd_status_ = VpdStatus::kInvalid;
    return;
  }

  switch (exit_code) {
    case static_cast<int>(DumpVpdExitCodes::kValid):
      vpd_status_ = VpdStatus::kValid;
      break;
    case static_cast<int>(DumpVpdExitCodes::kRoInvalid):
      vpd_status_ = VpdStatus::kRoInvalid;
      break;
    case static_cast<int>(DumpVpdExitCodes::kRwInvalid):
      vpd_status_ = VpdStatus::kRwInvalid;
      break;
    case static_cast<int>(DumpVpdExitCodes::kBothInvalid):
      vpd_status_ = VpdStatus::kInvalid;
      break;
    default:
      vpd_status_ = VpdStatus::kInvalid;
      LOG(ERROR) << "Unexpected return code from: "
                 << sources_.vpd_tool.GetProgram() << ", " << exit_code;
      break;
  };

  VLOG(1) << "VPD dump exit status: " << exit_code;
}

void StatisticsProviderImpl::LoadOemManifestFromFile(
    const base::FilePath& file) {
  // Called from LoadMachineStatistics. Check cancellation_flag_ again here.
  if (cancellation_flag_.IsSet()) {
    return;
  }

  KioskOemManifestParser::Manifest oem_manifest;
  if (!KioskOemManifestParser::Load(file, &oem_manifest)) {
    LOG(WARNING) << "Unable to load OEM Manifest file: " << file.value();
    return;
  }
  machine_info_[kOemDeviceRequisitionKey] = oem_manifest.device_requisition;
  machine_flags_[kOemIsEnterpriseManagedKey] = oem_manifest.enterprise_managed;
  machine_flags_[kOemCanExitEnterpriseEnrollmentKey] =
      oem_manifest.can_exit_enrollment;
  machine_flags_[kOemKeyboardDrivenOobeKey] = oem_manifest.keyboard_driven_oobe;

  oem_manifest_loaded_ = true;
  VLOG(1) << "Loaded OEM Manifest statistics from " << file.value();
}

void StatisticsProviderImpl::LoadRegionsFile(const base::FilePath& filename,
                                             std::string_view region) {
  JSONFileValueDeserializer regions_file(filename);
  int regions_error_code = 0;
  std::string regions_error_message;
  std::unique_ptr<base::Value> json_value =
      regions_file.Deserialize(&regions_error_code, &regions_error_message);
  if (!json_value.get()) {
    if (base::SysInfo::IsRunningOnChromeOS()) {
      LOG(ERROR) << "Failed to load regions file '" << filename.value()
                 << "': error='" << regions_error_message << "'";
    }

    return;
  }
  if (!json_value->is_dict()) {
    LOG(ERROR) << "Bad regions file '" << filename.value()
               << "': not a dictionary.";
    return;
  }

  base::Value::Dict* region_dict = json_value->GetDict().FindDict(region);
  if (region_dict == nullptr) {
    LOG(ERROR) << "Bad regional data: '" << region << "' << not found.";
    return;
  }

  // Extract region keys from the dictionary with corresponding extractors.
  for (const auto& [key, extractor] : kRegionKeysToExtractors) {
    if (auto region_statistic = extractor(*region_dict)) {
      region_info_[key] = std::move(region_statistic.value());
    }
  }
}

std::optional<std::string_view> StatisticsProviderImpl::GetRegionalInformation(
    std::string_view name) const {
  if (!base::Contains(machine_info_, kRegionKey)) {
    return std::nullopt;
  }

  if (const auto iter = region_info_.find(name); iter != region_info_.end()) {
    return std::string_view(iter->second);
  }

  return std::nullopt;
}

bool StatisticsProviderImpl::HasLoadingStarted() const {
  return loading_state_ != LoadingState::kNotStarted;
}

}  // namespace ash::system