blob: 86dbd62f60ee2fc94b5e70e2ff6cb168467d59ab [file] [log] [blame]
Elly Jones03cd6d72012-06-11 13:04:28 -04001// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Alex Vakulenko262be3f2014-07-30 15:25:50 -07005#include "debugd/src/log_tool.h"
Elly Jones03cd6d72012-06-11 13:04:28 -04006
Mike Frysinger020c2402020-12-16 05:40:53 -05007#include <glob.h>
Fletcher Woodruff07c28532019-01-24 11:08:53 -07008#include <grp.h>
9#include <inttypes.h>
Chinglin Yuaeb4ec72018-12-10 18:53:30 +080010#include <lzma.h>
Fletcher Woodruff07c28532019-01-24 11:08:53 -070011#include <pwd.h>
12#include <stdint.h>
13#include <sys/types.h>
14#include <unistd.h>
Ben Chan8e9f6d02017-09-26 23:04:21 -070015#include <memory>
Luis Hector Chavezfc2566f2018-09-13 15:00:36 -070016#include <string>
Fletcher Woodruff07c28532019-01-24 11:08:53 -070017#include <utility>
Ben Chana0011d82014-05-13 00:19:29 -070018#include <vector>
19
Ben Chanab93abf2017-01-24 13:32:51 -080020#include <base/base64.h>
Qijiang Fan713061e2021-03-08 15:45:12 +090021#include <base/check.h>
22#include <base/check_op.h>
Fletcher Woodruff07c28532019-01-24 11:08:53 -070023#include <base/files/file.h>
24#include <base/files/file_path.h>
Ben Chancd8fda42014-09-05 08:21:06 -070025#include <base/files/file_util.h>
Ahmed Fakhry21140cf2016-03-04 17:15:19 -080026#include <base/json/json_writer.h>
Elly Jones03cd6d72012-06-11 13:04:28 -040027#include <base/logging.h>
Ben Chan9953a592014-02-05 23:32:00 -080028#include <base/strings/string_split.h>
29#include <base/strings/string_util.h>
Luis Hector Chavezfc2566f2018-09-13 15:00:36 -070030#include <base/strings/stringprintf.h>
31#include <base/strings/utf_string_conversion_utils.h>
Ahmed Fakhry21140cf2016-03-04 17:15:19 -080032#include <base/values.h>
Elly Jones03cd6d72012-06-11 13:04:28 -040033
Rebecca Silbersteine78af402014-10-02 10:55:04 -070034#include <chromeos/dbus/service_constants.h>
Eric Carusocc7106c2017-04-27 14:22:42 -070035#include <shill/dbus-proxies.h>
Rebecca Silbersteine78af402014-10-02 10:55:04 -070036
Ben Chanaf125862017-02-08 23:11:18 -080037#include "debugd/src/constants.h"
Chinglin Yuaeb4ec72018-12-10 18:53:30 +080038#include "debugd/src/perf_tool.h"
Alex Vakulenko262be3f2014-07-30 15:25:50 -070039#include "debugd/src/process_with_output.h"
Elly Jones03cd6d72012-06-11 13:04:28 -040040
Ereth McKnight-MacNeilca3fff22021-01-21 23:31:40 -080041#include <brillo/files/safe_fd.h>
42#include <brillo/files/file_util.h>
Kartik Hegde1c4b97b2018-09-09 19:09:34 -060043#include "brillo/key_value_store.h"
44#include <brillo/osrelease_reader.h>
mhasank86c46c72020-08-13 15:36:29 -070045#include <brillo/cryptohome.h>
Kartik Hegde1c4b97b2018-09-09 19:09:34 -060046
Elly Jones03cd6d72012-06-11 13:04:28 -040047namespace debugd {
48
Elly Jones03cd6d72012-06-11 13:04:28 -040049using std::string;
Elly Jones03cd6d72012-06-11 13:04:28 -040050
Eric Caruso96d03d32017-04-25 18:01:17 -070051using Strings = std::vector<string>;
Elly Jones03cd6d72012-06-11 13:04:28 -040052
Ahmed Fakhry21140cf2016-03-04 17:15:19 -080053namespace {
54
Ben Chanaf125862017-02-08 23:11:18 -080055const char kRoot[] = "root";
56const char kShell[] = "/bin/sh";
Kartik Hegde1c4b97b2018-09-09 19:09:34 -060057constexpr char kLsbReleasePath[] = "/etc/lsb-release";
mhasank80cbe4d2020-04-02 22:46:08 -070058constexpr char kArcBugReportBackupFileName[] = "arc-bugreport.log";
mhasankd2b84882020-05-04 17:02:19 -070059constexpr char kArcBugReportBackupKey[] = "arc-bugreport-backup";
mhasank80cbe4d2020-04-02 22:46:08 -070060constexpr char kDaemonStoreBaseDir[] = "/run/daemon-store/debugd/";
Ahmed Fakhry21140cf2016-03-04 17:15:19 -080061
62// Minimum time in seconds needed to allow shill to test active connections.
63const int kConnectionTesterTimeoutSeconds = 5;
Ben Chanf6cd93a2012-10-14 19:37:00 -070064
Chinglin Yuaeb4ec72018-12-10 18:53:30 +080065// Default running perf for 2 seconds.
66constexpr const int kPerfDurationSecs = 2;
Chinglin Yu3c8d0a22019-02-20 11:32:52 +080067// TODO(chinglinyu) Remove after crbug/934702 is fixed.
68// The following description is added to 'perf-data' as a temporary solution
69// before the update of feedback disclosure to users is done in crbug/934702.
70constexpr const char kPerfDataDescription[] =
71 "perf-data contains performance profiling information about how much time "
72 "the system spends on various activities (program execution stack traces). "
73 "This might reveal some information about what system features and "
74 "resources are being used. The full detail of perf-data can be found in "
75 "the PerfDataProto protocol buffer message type in the chromium source "
76 "repository.\n";
Chinglin Yuaeb4ec72018-12-10 18:53:30 +080077
Eric Carusoa879fd92017-10-11 12:57:10 -070078#define CMD_KERNEL_MODULE_PARAMS(module_name) \
Tom Hughesd6c2d392020-08-24 18:12:11 -070079 "cd /sys/module/" #module_name "/parameters 2>/dev/null && grep -sH ^ *"
Eric Carusoa879fd92017-10-11 12:57:10 -070080
Fletcher Woodruff07c28532019-01-24 11:08:53 -070081using Log = LogTool::Log;
82constexpr Log::LogType kCommand = Log::kCommand;
83constexpr Log::LogType kFile = Log::kFile;
Mike Frysinger020c2402020-12-16 05:40:53 -050084constexpr Log::LogType kGlob = Log::kGlob;
mhasankaf5251d2020-04-29 18:53:03 -070085
86class ArcBugReportLog : public LogTool::Log {
87 public:
88 ArcBugReportLog()
89 : Log(kCommand,
90 "arc-bugreport",
91 "/usr/bin/nsenter -t1 -m /usr/sbin/android-sh -c "
92 "/system/bin/arc-bugreport",
93 kRoot,
94 kRoot,
95 10 * 1024 * 1024 /*10 MiB*/,
96 LogTool::Encoding::kUtf8) {}
97
98 virtual ~ArcBugReportLog() = default;
99};
mhasank80cbe4d2020-04-02 22:46:08 -0700100
Miriam Zimmermand91d8e72019-06-27 12:24:04 -0700101// NOTE: IF YOU ADD AN ENTRY TO THIS LIST, PLEASE:
102// * add a row to http://go/cros-feedback-audit and fill it out
Miriam Zimmerman4f142ba2020-06-01 14:15:21 -0700103// * email cros-telemetry@
Miriam Zimmermand91d8e72019-06-27 12:24:04 -0700104// (Eventually we'll have a better process, but for now please do this.)
Tom Hughesd6c2d392020-08-24 18:12:11 -0700105// clang-format off
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700106const std::vector<Log> kCommandLogs {
Mike Frysingerb0350992018-09-14 13:45:35 -0400107 // We need to enter init's mount namespace because it has /home/chronos
108 // mounted which is where the consent knob lives. We don't have that mount
109 // in our own mount namespace (by design). https://crbug.com/884249
Chris Morin853d3442019-04-01 21:35:13 -0700110 {kCommand, "CLIENT_ID", "/usr/bin/nsenter -t1 -m /usr/bin/metrics_client -i",
111 kRoot, kDebugfsGroup},
Nikolai Artemiev9a7c3a52021-03-09 12:31:25 +1100112 // The device type / form factor e.g. CHROMEBOOK, CHROMEBOX, etc.
113 {kCommand, "DEVICETYPE", "cros_config /hardware-properties form-factor"},
Kimiyuki Onaka3aab14e2021-02-22 13:13:07 +0900114 // We consistently use UTC in feedback reports.
115 {kCommand, "LOGDATE", "/bin/date --utc; /bin/date"},
Yusuke Sato27a31672019-04-29 15:26:37 -0700116 // We need to enter init's mount namespace to access /home/root. Also, we use
117 // neither ARC container's mount namespace (with android-sh) nor
118 // /opt/google/containers/android/rootfs/android-data/ so that we can get
119 // results even when the container is down.
120 {kCommand, "android_app_storage", "/usr/bin/nsenter -t1 -m "
121 "/bin/sh -c \"/usr/bin/du -h /home/root/*/android-data/data/\"",
122 kRoot, kDebugfsGroup},
Chris Morin853d3442019-04-01 21:35:13 -0700123 {kFile, "atrus_logs", "/var/log/atrus.log"},
124 {kFile, "authpolicy", "/var/log/authpolicy.log"},
Kimiyuki Onakafc372892020-11-24 23:28:20 +0900125#if USE_ARCVM
126 {kCommand, "arcvm_console_output", "/usr/bin/vm_pstore_dump", "crosvm",
Junichi Uekawace96c6d2021-03-12 09:34:10 +0900127 "crosvm", Log::kDefaultMaxBytes, LogTool::Encoding::kAutodetect,
128 true /* access_root_mount_ns */},
Kimiyuki Onakafc372892020-11-24 23:28:20 +0900129#endif // USE_ARCVM
Brian Norrisafc9f632019-05-09 14:08:28 -0700130 {kCommand, "bootstat_summary", "/usr/bin/bootstat_summary",
131 SandboxedProcess::kDefaultUser, SandboxedProcess::kDefaultGroup,
Junichi Uekawace96c6d2021-03-12 09:34:10 +0900132 Log::kDefaultMaxBytes, LogTool::Encoding::kAutodetect,
133 true /* access_root_mount_ns */},
Craig Hesling5c384b52019-04-20 15:18:06 -0700134 {kFile, "bio_crypto_init.LATEST",
135 "/var/log/bio_crypto_init/bio_crypto_init.LATEST"},
136 {kFile, "bio_crypto_init.PREVIOUS",
137 "/var/log/bio_crypto_init/bio_crypto_init.PREVIOUS"},
Chris Morin853d3442019-04-01 21:35:13 -0700138 {kFile, "biod.LATEST", "/var/log/biod/biod.LATEST"},
139 {kFile, "biod.PREVIOUS", "/var/log/biod/biod.PREVIOUS"},
Craig Hesling4c3891e2019-04-20 12:53:54 -0700140 {kFile, "bio_fw_updater.LATEST", "/var/log/biod/bio_fw_updater.LATEST"},
141 {kFile, "bio_fw_updater.PREVIOUS", "/var/log/biod/bio_fw_updater.PREVIOUS"},
Chris Morin853d3442019-04-01 21:35:13 -0700142 {kFile, "bios_info", "/var/log/bios_info.txt"},
143 {kCommand, "bios_log", "cat /sys/firmware/log "
144 "/proc/device-tree/chosen/ap-console-buffer 2>/dev/null"},
145 {kFile, "bios_times", "/var/log/bios_times.txt"},
Anand K Mistryccceb1e2020-01-16 14:00:49 +1100146 // Slow or non-responsive block devices could cause this command to stall. Use
147 // a timeout to prevent this command from blocking log fetching. This command
148 // is expected to take O(100ms) in the normal case.
149 {kCommand, "blkid", "timeout -s KILL 5s /sbin/blkid", kRoot, kRoot},
Chris Morin853d3442019-04-01 21:35:13 -0700150 {kFile, "buddyinfo", "/proc/buddyinfo"},
151 {kCommand, "cbi_info", "/usr/share/userfeedback/scripts/cbi_info", kRoot,
152 kRoot},
153 {kFile, "cheets_log", "/var/log/arc.log"},
154 {kFile, "clobber.log", "/var/log/clobber.log"},
155 {kFile, "clobber-state.log", "/var/log/clobber-state.log"},
Sonny Raobd3dc002020-05-27 21:40:35 -0700156 {kCommand, "chromeos-pgmem", "/usr/bin/chromeos-pgmem", kRoot, kRoot},
Chris Morin853d3442019-04-01 21:35:13 -0700157 {kFile, "chrome_system_log", "/var/log/chrome/chrome"},
158 {kFile, "chrome_system_log.PREVIOUS", "/var/log/chrome/chrome.PREVIOUS"},
Mike Frysinger32cdf3e2017-08-14 18:17:06 -0400159 // There might be more than one record, so grab them all.
160 // Plus, for <linux-3.19, it's named "console-ramoops", but for newer
161 // versions, it's named "console-ramoops-#".
Mike Frysinger020c2402020-12-16 05:40:53 -0500162 {kGlob, "console-ramoops", "/sys/fs/pstore/console-ramoops*"},
Chris Morin853d3442019-04-01 21:35:13 -0700163 {kFile, "cpuinfo", "/proc/cpuinfo"},
164 {kFile, "cr50_version", "/var/cache/cr50-version"},
Nicolas Boichatf3dd82d2020-09-07 15:11:15 +0800165 {kFile, "cros_ec.log", "/var/log/cros_ec.log",
166 SandboxedProcess::kDefaultUser, SandboxedProcess::kDefaultGroup,
167 Log::kDefaultMaxBytes, LogTool::Encoding::kUtf8},
168 {kFile, "cros_ec.previous", "/var/log/cros_ec.previous",
169 SandboxedProcess::kDefaultUser, SandboxedProcess::kDefaultGroup,
170 Log::kDefaultMaxBytes, LogTool::Encoding::kUtf8},
Chris Morin853d3442019-04-01 21:35:13 -0700171 {kFile, "cros_ec_panicinfo", "/sys/kernel/debug/cros_ec/panicinfo",
Nicolas Boichat28272d72020-09-03 09:10:44 +0800172 SandboxedProcess::kDefaultUser, kDebugfsGroup, Log::kDefaultMaxBytes,
173 LogTool::Encoding::kBase64},
Stephen Boydf00c5a02020-09-10 19:11:35 -0700174 {kCommand, "cros_ec_pdinfo",
175 "for port in 0 1 2 3 4 5 6 7 8; do "
176 "echo \"-----------\"; "
177 // stderr output just tells us it failed
178 "ectool usbpd \"${port}\" 2>/dev/null || break; "
179 "done", kRoot, kRoot},
Nicolas Boichatf3dd82d2020-09-07 15:11:15 +0800180 {kFile, "cros_fp.previous", "/var/log/cros_fp.previous",
181 SandboxedProcess::kDefaultUser, SandboxedProcess::kDefaultGroup,
182 Log::kDefaultMaxBytes, LogTool::Encoding::kUtf8},
183 {kFile, "cros_fp.log", "/var/log/cros_fp.log",
184 SandboxedProcess::kDefaultUser, SandboxedProcess::kDefaultGroup,
185 Log::kDefaultMaxBytes, LogTool::Encoding::kUtf8},
186 {kFile, "cros_ish.previous", "/var/log/cros_ish.previous",
187 SandboxedProcess::kDefaultUser, SandboxedProcess::kDefaultGroup,
188 Log::kDefaultMaxBytes, LogTool::Encoding::kUtf8},
189 {kFile, "cros_ish.log", "/var/log/cros_ish.log",
190 SandboxedProcess::kDefaultUser, SandboxedProcess::kDefaultGroup,
191 Log::kDefaultMaxBytes, LogTool::Encoding::kUtf8},
Nicolas Boichat579ccf32020-08-31 11:17:21 +0800192 {kFile, "cros_scp.previous", "/var/log/cros_scp.previous",
193 SandboxedProcess::kDefaultUser, SandboxedProcess::kDefaultGroup,
194 64 * 1024, LogTool::Encoding::kUtf8},
195 {kFile, "cros_scp.log", "/var/log/cros_scp.log",
196 SandboxedProcess::kDefaultUser, SandboxedProcess::kDefaultGroup,
197 64 * 1024, LogTool::Encoding::kUtf8},
David Munro0eb1ac32020-08-19 22:22:56 +1000198 {kCommand, "crosvm.log", "nsenter -t1 -m /bin/sh -c 'tail -n+1"
199 " /run/daemon-store/crosvm/*/log/*.log.1"
200 " /run/daemon-store/crosvm/*/log/*.log'", kRoot, kRoot},
Steven 'Steve' Kendall33f72192021-02-16 16:36:16 -0500201 // dmesg: add full timestamps to dmesg to match other logs.
Jorge Lucangeli Obesaf8f79c2020-11-13 08:54:55 -0500202 // 'dmesg' needs CAP_SYSLOG.
Stephen Boyd6d6cfad2020-09-22 15:13:18 -0700203 {kCommand, "dmesg", "TZ=UTC /bin/dmesg --raw --time-format iso",
204 kRoot, kRoot},
Mike Frysinger020c2402020-12-16 05:40:53 -0500205 {kGlob, "drm_gem_objects", "/sys/kernel/debug/dri/?/gem",
Stephen Boyda8287162020-07-30 18:07:53 -0700206 SandboxedProcess::kDefaultUser, kDebugfsGroup},
Mike Frysinger020c2402020-12-16 05:40:53 -0500207 {kGlob, "drm_state", "/sys/kernel/debug/dri/?/state",
Stephen Boyda8287162020-07-30 18:07:53 -0700208 SandboxedProcess::kDefaultUser, kDebugfsGroup},
Chris Morin853d3442019-04-01 21:35:13 -0700209 {kFile, "ec_info", "/var/log/ec_info.txt"},
Chris Morin853d3442019-04-01 21:35:13 -0700210 {kCommand, "edid-decode",
Stephen Boydaf3118b2020-08-11 11:42:22 -0700211 "for f in /sys/class/drm/card?-*/edid; do "
Chris Morin853d3442019-04-01 21:35:13 -0700212 "echo \"----------- ${f}\"; "
Chris Morin853d3442019-04-01 21:35:13 -0700213 // edid-decode's stderr output is redundant, so silence it.
Jeffrey Kardatzke9ba9f322019-08-29 10:23:14 -0700214 "edid-decode \"${f}\" 2>/dev/null; "
Chris Morin853d3442019-04-01 21:35:13 -0700215 "done"},
216 {kFile, "eventlog", "/var/log/eventlog.txt"},
Chris Morin853d3442019-04-01 21:35:13 -0700217 {kCommand, "font_info", "/usr/share/userfeedback/scripts/font_info"},
Mike Frysinger020c2402020-12-16 05:40:53 -0500218 {kGlob, "framebuffer", "/sys/kernel/debug/dri/?/framebuffer",
Kuo-Hsin Yang95296e12020-03-06 17:52:35 +0800219 SandboxedProcess::kDefaultUser, kDebugfsGroup},
Daniel Campello9f0b2b82020-10-23 11:01:01 -0600220 {kCommand, "fwupd_state", "/sbin/initctl emit fwupdtool-getdevices;"
221 "cat /var/lib/fwupd/state.json", kRoot, kRoot},
Chris Morin853d3442019-04-01 21:35:13 -0700222 {kCommand, "sensor_info", "/usr/share/userfeedback/scripts/sensor_info"},
223 {kFile, "hammerd", "/var/log/hammerd.log"},
224 {kCommand, "hardware_class", "/usr/bin/crossystem hwid"},
Yong Hong15e4b032020-03-05 15:41:31 +0800225 {kFile, "hardware_verification_report",
226 "/var/cache/hardware_verifier.result"},
Chris Morin853d3442019-04-01 21:35:13 -0700227 {kCommand, "hostname", "/bin/hostname"},
228 {kFile, "i915_gem_gtt", "/sys/kernel/debug/dri/0/i915_gem_gtt",
229 SandboxedProcess::kDefaultUser, kDebugfsGroup},
230 {kFile, "i915_gem_objects", "/sys/kernel/debug/dri/0/i915_gem_objects",
231 SandboxedProcess::kDefaultUser, kDebugfsGroup},
Chris Morin853d3442019-04-01 21:35:13 -0700232 {kCommand, "i915_error_state",
233 "/usr/bin/xz -c /sys/kernel/debug/dri/0/i915_error_state 2>/dev/null",
234 SandboxedProcess::kDefaultUser, kDebugfsGroup, Log::kDefaultMaxBytes,
Chris Morin790fd262019-04-03 20:29:36 -0700235 LogTool::Encoding::kBase64},
Evan Benn0e373cc2021-01-07 15:10:26 +1100236 {kFile, "amdgpu_gem_info", "/sys/kernel/debug/dri/0/amdgpu_gem_info",
237 SandboxedProcess::kDefaultUser, kDebugfsGroup},
238 {kFile, "amdgpu_gtt_mm", "/sys/kernel/debug/dri/0/amdgpu_gtt_mm",
239 SandboxedProcess::kDefaultUser, kDebugfsGroup},
240 {kFile, "amdgpu_vram_mm", "/sys/kernel/debug/dri/0/amdgpu_vram_mm",
241 SandboxedProcess::kDefaultUser, kDebugfsGroup},
Chris Morin853d3442019-04-01 21:35:13 -0700242 {kCommand, "ifconfig", "/bin/ifconfig -a"},
243 {kFile, "input_devices", "/proc/bus/input/devices"},
Eric Carusob1820c02017-08-24 15:39:56 -0700244 // Hardware capabilities of the wiphy device.
Alex Levine1c6d572019-09-17 14:45:33 -0700245 {kFile, "interrupts", "/proc/interrupts"},
Chris Morin853d3442019-04-01 21:35:13 -0700246 {kCommand, "iw_list", "/usr/sbin/iw list"},
Eric Carusoa879fd92017-10-11 12:57:10 -0700247#if USE_IWLWIFI_DUMP
Chris Morin853d3442019-04-01 21:35:13 -0700248 {kCommand, "iwlmvm_module_params", CMD_KERNEL_MODULE_PARAMS(iwlmvm)},
249 {kCommand, "iwlwifi_module_params", CMD_KERNEL_MODULE_PARAMS(iwlwifi)},
Eric Carusoa879fd92017-10-11 12:57:10 -0700250#endif // USE_IWLWIFI_DUMP
Daniel Winklerdf136012021-03-16 13:25:14 -0700251 {kCommand, "bt_usb_disconnects",
252 "/usr/libexec/debugd/helpers/bt_usb_disconnect_helper",
253 SandboxedProcess::kDefaultUser, kDebugfsGroup},
Mike Frysinger020c2402020-12-16 05:40:53 -0500254 {kGlob, "kernel-crashes", "/var/spool/crash/kernel.*.kcrash",
Mike Frysinger2abf7a12020-12-16 05:39:02 -0500255 SandboxedProcess::kDefaultUser, "crash-access"},
Anand K Mistryccceb1e2020-01-16 14:00:49 +1100256 {kCommand, "lsblk", "timeout -s KILL 5s lsblk -a", kRoot, kRoot,
Junichi Uekawace96c6d2021-03-12 09:34:10 +0900257 Log::kDefaultMaxBytes, LogTool::Encoding::kAutodetect,
258 true /* access_root_mount_ns */},
Chris Morin853d3442019-04-01 21:35:13 -0700259 {kCommand, "lsmod", "lsmod"},
Chris Morin853d3442019-04-01 21:35:13 -0700260 {kCommand, "lsusb", "lsusb && lsusb -t"},
Kuo-Hsin Yang66d89832020-02-10 17:22:28 +0800261 {kFile, "mali_memory", "/sys/kernel/debug/mali0/gpu_memory",
262 SandboxedProcess::kDefaultUser, kDebugfsGroup},
Chris Morin853d3442019-04-01 21:35:13 -0700263 {kFile, "memd.parameters", "/var/log/memd/memd.parameters"},
Mike Frysinger020c2402020-12-16 05:40:53 -0500264 {kGlob, "memd clips", "/var/log/memd/memd.clip*"},
Chris Morin853d3442019-04-01 21:35:13 -0700265 {kFile, "meminfo", "/proc/meminfo"},
266 {kCommand, "memory_spd_info",
267 // mosys may use 'i2c-dev', which may not be loaded yet.
268 "modprobe i2c-dev 2>/dev/null && mosys -l memory spd print all 2>/dev/null",
269 kRoot, kDebugfsGroup},
Simon Quecb63b9c2017-06-19 14:53:31 -0400270 // The sed command finds the EDID blob (starting the line after "value:") and
271 // replaces the serial number with all zeroes.
272 //
273 // The EDID is printed as a hex dump over several lines, each line containing
274 // the contents of 16 bytes. The first 16 bytes are broken down as follows:
275 // uint64_t fixed_pattern; // Always 00 FF FF FF FF FF FF 00.
276 // uint16_t manufacturer_id; // Manufacturer ID, encoded as PNP IDs.
277 // uint16_t product_code; // Manufacturer product code, little-endian.
278 // uint32_t serial_number; // Serial number, little-endian.
279 // Source: https://en.wikipedia.org/wiki/EDID#EDID_1.3_data_format
280 //
281 // The subsequent substitution command looks for the fixed pattern followed by
282 // two 32-bit fields (manufacturer + product, serial number). It replaces the
283 // latter field with 8 bytes of zeroes.
284 //
285 // TODO(crbug.com/731133): Remove the sed command once modetest itself can
286 // remove serial numbers.
Chris Morin853d3442019-04-01 21:35:13 -0700287 {kCommand, "modetest",
288 "(modetest; modetest -M evdi; modetest -M udl) | "
289 "sed -E '/EDID/ {:a;n;/value:/!ba;n;"
290 "s/(00f{12}00)([0-9a-f]{8})([0-9a-f]{8})/\\1\\200000000/}'",
291 kRoot, kRoot},
292 {kFile, "mount-encrypted", "/var/log/mount-encrypted.log"},
293 {kFile, "mountinfo", "/proc/1/mountinfo"},
294 {kCommand, "netlog",
Brian Norris72588462021-01-25 19:32:31 -0800295 "/usr/share/userfeedback/scripts/getmsgs /var/log/net.log",
296 SandboxedProcess::kDefaultUser, SandboxedProcess::kDefaultGroup,
297 Log::kDefaultMaxBytes, LogTool::Encoding::kUtf8},
Chris Morin853d3442019-04-01 21:35:13 -0700298 {kFile, "nvmap_iovmm", "/sys/kernel/debug/nvmap/iovmm/allocations",
299 SandboxedProcess::kDefaultUser, kDebugfsGroup},
300 {kCommand, "oemdata", "/usr/share/cros/oemdata.sh", kRoot, kRoot},
Kuo-Hsin Yanga69ecc62020-03-11 17:37:11 +0800301 {kFile, "pagetypeinfo", "/proc/pagetypeinfo", kRoot},
Daisuke Nojiri3c6e6a12017-02-17 14:21:28 -0800302 {kCommand, "pchg_info", "/usr/share/userfeedback/scripts/pchg_info",
303 kRoot, kRoot},
Jack Rosenthal3cf794a2020-02-19 13:32:56 -0700304 {kFile, "platform_identity_name",
305 "/run/chromeos-config/v1/identity/platform-name"},
306 {kFile, "platform_identity_model", "/run/chromeos-config/v1/name"},
307 {kFile, "platform_identity_sku", "/run/chromeos-config/v1/identity/sku-id"},
308 {kFile, "platform_identity_whitelabel_tag",
309 "/run/chromeos-config/v1/identity/whitelabel-tag"},
310 {kFile, "platform_identity_customization_id",
311 "/run/chromeos-config/v1/identity/customization-id"},
Chris Morin853d3442019-04-01 21:35:13 -0700312 {kCommand, "power_supply_info", "/usr/bin/power_supply_info"},
313 {kCommand, "power_supply_sysfs", "/usr/bin/print_sysfs_power_supply_data"},
314 {kFile, "powerd.LATEST", "/var/log/power_manager/powerd.LATEST"},
315 {kFile, "powerd.PREVIOUS", "/var/log/power_manager/powerd.PREVIOUS"},
316 {kFile, "powerd.out", "/var/log/powerd.out"},
317 {kFile, "powerwash_count", "/var/log/powerwash_count"},
Brian Norris4cde3d12019-04-16 10:10:34 -0700318 {kCommand, "ps", "/bin/ps auxZ"},
Mike Frysinger020c2402020-12-16 05:40:53 -0500319 {kGlob, "qcom_fw_info", "/sys/kernel/debug/qcom_socinfo/*/*",
Stephen Boyd57779f92020-12-15 23:24:31 -0800320 SandboxedProcess::kDefaultUser, kDebugfsGroup},
yusukes34171ba2017-04-27 15:46:01 -0700321 // /proc/slabinfo is owned by root and has 0400 permission.
Chris Morin853d3442019-04-01 21:35:13 -0700322 {kFile, "slabinfo", "/proc/slabinfo", kRoot, kRoot},
323 {kFile, "storage_info", "/var/log/storage_info.txt"},
324 {kCommand, "swap_info", "/usr/share/cros/init/swap.sh status 2>/dev/null",
325 SandboxedProcess::kDefaultUser, kDebugfsGroup},
326 {kCommand, "syslog",
327 "/usr/share/userfeedback/scripts/getmsgs /var/log/messages"},
328 {kCommand, "system_log_stats",
329 "echo 'BLOCK_SIZE=1024'; "
330 "find /var/log/ -type f -exec du --block-size=1024 {} + | sort -n -r",
331 kRoot, kRoot},
332 {kCommand, "threads", "/bin/ps -T axo pid,ppid,spid,pcpu,ni,stat,time,comm"},
333 {kFile, "tlsdate", "/var/log/tlsdate.log"},
Nick Sandersad5dc132019-11-15 15:59:42 -0800334 {kCommand, "top thread", "/usr/bin/top -Hbc -w128 -n 1 | head -n 40"},
335 {kCommand, "top memory",
336 "/usr/bin/top -o \"+%MEM\" -w128 -bcn 1 | head -n 57"},
Chris Morin853d3442019-04-01 21:35:13 -0700337 {kCommand, "touch_fw_version",
Stephen Boyddb9eb2f2020-08-11 11:25:41 -0700338 "grep -aE"
Chris Morin853d3442019-04-01 21:35:13 -0700339 " -e 'synaptics: Touchpad model'"
340 " -e 'chromeos-[a-z]*-touch-[a-z]*-update'"
341 " /var/log/messages | tail -n 20"},
342 {kCommand, "tpm-firmware-updater", "/usr/share/userfeedback/scripts/getmsgs "
343 "/var/log/tpm-firmware-updater.log"},
Mattias Nissler887dce22017-07-03 14:44:35 +0200344 // TODO(jorgelo,mnissler): Don't run this as root.
345 // On TPM 1.2 devices this will likely require adding a new user to the 'tss'
346 // group.
347 // On TPM 2.0 devices 'get_version_info' uses D-Bus and therefore can run as
348 // any user.
Chris Morin853d3442019-04-01 21:35:13 -0700349 {kCommand, "tpm_version", "/usr/sbin/tpm-manager get_version_info", kRoot,
350 kRoot},
Prashant Malani39ddecd2021-02-25 17:11:39 -0800351 // typecd logs average around 56K. VID/PIDs are obfuscated from the printed
352 // PD identity information.
353 {kFile, "typecd", "/var/log/typecd.log"},
Chris Morin853d3442019-04-01 21:35:13 -0700354 {kCommand, "atmel_ts_refs",
355 "/opt/google/touch/scripts/atmel_tools.sh ts r", kRoot, kRoot},
356 {kCommand, "atmel_tp_refs",
357 "/opt/google/touch/scripts/atmel_tools.sh tp r", kRoot, kRoot},
358 {kCommand, "atmel_ts_deltas",
359 "/opt/google/touch/scripts/atmel_tools.sh ts d", kRoot, kRoot},
360 {kCommand, "atmel_tp_deltas",
361 "/opt/google/touch/scripts/atmel_tools.sh tp d", kRoot, kRoot},
362 {kFile, "stateful_trim_state", "/var/lib/trim/stateful_trim_state"},
363 {kFile, "stateful_trim_data", "/var/lib/trim/stateful_trim_data"},
364 {kFile, "ui_log", "/var/log/ui/ui.LATEST"},
365 {kCommand, "uname", "/bin/uname -a"},
366 {kCommand, "update_engine.log",
367 "cat $(ls -1tr /var/log/update_engine | tail -5 | sed"
368 " s.^./var/log/update_engine/.)"},
Chris Morinca152712019-05-03 13:17:28 -0700369 {kFile, "upstart", "/var/log/upstart.log"},
Chris Morin853d3442019-04-01 21:35:13 -0700370 {kCommand, "uptime", "/usr/bin/cut -d' ' -f1 /proc/uptime"},
Prashant Malani9704ed02021-02-10 16:19:22 -0800371 {kCommand, "usb4 devices", "/usr/libexec/debugd/helpers/usb4_devinfo_helper",
Prashant Malanic8a37122021-05-26 14:09:05 -0700372 kRoot, kDebugfsGroup},
Chris Morin853d3442019-04-01 21:35:13 -0700373 {kFile, "verified boot", "/var/log/debug_vboot_noisy.log"},
374 {kFile, "vmlog.1.LATEST", "/var/log/vmlog/vmlog.1.LATEST"},
375 {kFile, "vmlog.1.PREVIOUS", "/var/log/vmlog/vmlog.1.PREVIOUS"},
376 {kFile, "vmlog.LATEST", "/var/log/vmlog/vmlog.LATEST"},
377 {kFile, "vmlog.PREVIOUS", "/var/log/vmlog/vmlog.PREVIOUS"},
378 {kFile, "vmstat", "/proc/vmstat"},
379 {kFile, "vpd_2.0", "/var/log/vpd_2.0.txt"},
Chris Morin853d3442019-04-01 21:35:13 -0700380 {kCommand, "zram new stats names",
381 "echo orig_size compr_size used_total limit used_max zero_pages migrated"},
382 {kFile, "zram new stats values", "/sys/block/zram0/mm_stat"},
Junichi Uekawa2da60872021-04-01 10:12:16 +0900383 {kCommand, "zram block device stat names",
384 "echo read_ios read_merges read_sectors read_ticks write_ios "
385 "write_merges write_sectors write_ticks in_flight io_ticks "
386 "time_in_queue discard_ios dicard_merges discard_sectors discard_ticks "
387 "flush_ios flush_ticks"},
388 {kFile, "zram block device stat", "/sys/block/zram0/stat"},
Chris Morin853d3442019-04-01 21:35:13 -0700389 {kFile, "cros_tp version", "/sys/class/chromeos/cros_tp/version"},
390 {kCommand, "cros_tp console", "/usr/sbin/ectool --name=cros_tp console",
391 kRoot, kRoot},
392 {kCommand, "cros_tp frame", "/usr/sbin/ectool --name=cros_tp tpframeget",
393 kRoot, kRoot},
394 {kCommand, "crostini", "/usr/bin/cicerone_client --get_info"},
Sean Paulbfc5c422020-07-24 11:03:51 -0400395 // TODO(seanpaul): Once we've finished moving over to the upstream tracefs
396 // implementation, remove drm_trace_legacy. Tracked in
397 // b/163580546.
398 {kFile, "drm_trace_legacy", "/sys/kernel/debug/dri/trace",
399 SandboxedProcess::kDefaultUser, kDebugfsGroup},
400 {kFile, "drm_trace", "/sys/kernel/debug/tracing/instances/drm/trace",
Sean Paul5ce118f2019-12-05 08:41:32 -0500401 SandboxedProcess::kDefaultUser, kDebugfsGroup},
Elly Jones03cd6d72012-06-11 13:04:28 -0400402 // Stuff pulled out of the original list. These need access to the running X
403 // session, which we'd rather not give to debugd, or return info specific to
404 // the current session (in the setsid(2) sense), which is not useful for
405 // debugd
Chris Morin853d3442019-04-01 21:35:13 -0700406 // {kCommand, "env", "set"},
407 // {kCommand, "setxkbmap", "/usr/bin/setxkbmap -print -query"},
408 // {kCommand, "xrandr", "/usr/bin/xrandr --verbose}
Elly Jones533c7c42012-08-10 15:07:05 -0400409};
Tom Hughesd6c2d392020-08-24 18:12:11 -0700410// clang-format on
Elly Jones533c7c42012-08-10 15:07:05 -0400411
Arowa Suliman3bc729c2021-03-09 13:25:00 -0800412const std::vector<Log> kCommandLogsVerbose{
Arowa Suliman19ef6332021-04-09 17:23:16 -0700413 // PCI config space accesses are limited without CAP_SYS_ADMIN.
414 {kCommand, "lspci_verbose", "/usr/sbin/lspci -vvvnn", kRoot, kRoot},
Arowa Suliman3bc729c2021-03-09 13:25:00 -0800415};
416
417const std::vector<Log> kCommandLogsShort{
418 {kCommand, "lspci", "/usr/sbin/lspci"},
419};
420
Junichi Uekawaba686c82020-09-01 16:24:24 +0900421// Extra logs are logs such as netstat and logcat which should appear in
422// chrome://system but not in feedback reports. Open sockets may have privacy
423// implications, and logcat is already incorporated via arc-bugreport.
424//
Tom Hughesd6c2d392020-08-24 18:12:11 -0700425// clang-format off
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700426const std::vector<Log> kExtraLogs {
Ben Chan36e42282014-02-12 22:32:34 -0800427#if USE_CELLULAR
Chris Morin853d3442019-04-01 21:35:13 -0700428 {kCommand, "mm-status", "/usr/bin/modem status"},
Steven Bennettsde2bb162021-05-24 16:26:44 -0700429 {kCommand, "mm-esim-status", "/usr/bin/modem esim status"},
Ben Chan36e42282014-02-12 22:32:34 -0800430#endif // USE_CELLULAR
Chris Morin853d3442019-04-01 21:35:13 -0700431 {kCommand, "network-devices", "/usr/bin/connectivity show devices"},
432 {kCommand, "network-services", "/usr/bin/connectivity show services"},
Jeffrey Kardatzke36791f22019-07-11 11:53:22 -0700433 {kCommand, "wifi_status_no_anonymize",
434 "/usr/bin/network_diag --wifi-internal --no-log"},
Chris Morin253a2b02019-04-12 16:04:25 -0700435 // --processes requires root.
436 {kCommand, "netstat",
437 "/sbin/ss --all --query inet --numeric --processes", kRoot, kRoot},
Kansho Nishida6ae546f2019-08-13 17:14:58 +0900438 {kCommand, "logcat",
439 "/usr/bin/nsenter -t1 -m /usr/sbin/android-sh -c '/system/bin/logcat -d'",
Chris Morin253a2b02019-04-12 16:04:25 -0700440 kRoot, kRoot, Log::kDefaultMaxBytes, LogTool::Encoding::kUtf8},
Elly Jones533c7c42012-08-10 15:07:05 -0400441};
Tom Hughesd6c2d392020-08-24 18:12:11 -0700442// clang-format on
Elly Jones533c7c42012-08-10 15:07:05 -0400443
Tom Hughesd6c2d392020-08-24 18:12:11 -0700444// clang-format off
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700445const std::vector<Log> kFeedbackLogs {
Will Donnellyac905142021-02-16 09:52:06 -0800446 {kGlob, "iwlwifi_firmware_version",
447 "/sys/kernel/debug/iwlwifi/*/iwlmvm/fw_ver", kRoot, kRoot},
448 {kCommand, "iwlwifi_sysasserts",
449 "croslog --show-cursor=false --identifier=kernel --priority=err"
450 " --grep='iwlwifi.*ADVANCED_SYSASSERT' | tail -n 3"},
451 {kCommand, "iwlwifi_sysasserts_count",
452 "croslog --show-cursor=false --identifier=kernel --priority=err"
453 " --grep='iwlwifi.*ADVANCED_SYSASSERT' | wc -l"},
Ben Chan36e42282014-02-12 22:32:34 -0800454#if USE_CELLULAR
Chris Morin853d3442019-04-01 21:35:13 -0700455 {kCommand, "mm-status", "/usr/bin/modem status-feedback"},
Steven Bennettsde2bb162021-05-24 16:26:44 -0700456 {kCommand, "mm-esim-status", "/usr/bin/modem esim status_feedback"},
Ben Chan36e42282014-02-12 22:32:34 -0800457#endif // USE_CELLULAR
Chris Morin853d3442019-04-01 21:35:13 -0700458 {kCommand, "network-devices",
459 "/usr/bin/connectivity show-feedback devices"},
460 {kCommand, "network-services",
461 "/usr/bin/connectivity show-feedback services"},
Will Donnellyac905142021-02-16 09:52:06 -0800462 {kCommand, "shill_connection_diagnostic",
463 "croslog --show-cursor=false --identifier=shill"
464 " --grep='Connection issue:' | tail -n 3"},
465 {kCommand, "wifi_connection_attempts",
466 "croslog --show-cursor=false --identifier=kernel"
467 " --grep='(authenticate|associate) with' | wc -l"},
468 {kCommand, "wifi_connection_timeouts",
469 "croslog --show-cursor=false --identifier=kernel"
470 " --grep='(authentication|association).*timed out' | wc -l"},
471 {kCommand, "wifi_driver_errors",
472 "croslog --show-cursor=false --identifier=kernel --priority=err"
473 " --grep='(iwlwifi|mwifiex|ath10k)' | tail -n 3"},
474 {kCommand, "wifi_driver_errors_count",
475 "croslog --show-cursor=false --identifier=kernel --priority=err"
476 " --grep='(iwlwifi|mwifiex|ath10k)' | wc -l"},
Jeffrey Kardatzke36791f22019-07-11 11:53:22 -0700477 {kCommand, "wifi_status",
478 "/usr/bin/network_diag --wifi-internal --no-log --anonymize"},
Elly Jones03cd6d72012-06-11 13:04:28 -0400479};
Tom Hughesd6c2d392020-08-24 18:12:11 -0700480// clang-format on
Elly Jones03cd6d72012-06-11 13:04:28 -0400481
Jeffrey Kardatzkee3ec6fd2019-08-05 12:25:17 -0700482// Fills |dictionary| with the contents of the logs in |logs|.
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700483void GetLogsInDictionary(const std::vector<Log>& logs,
hscham2311cc22020-10-28 12:13:10 +0900484 base::Value* dictionary) {
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700485 for (const Log& log : logs) {
hscham2311cc22020-10-28 12:13:10 +0900486 dictionary->SetStringKey(log.GetName(), log.GetLogData());
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800487 }
488}
489
490// Serializes the |dictionary| into the file with the given |fd| in a JSON
491// format.
hscham2311cc22020-10-28 12:13:10 +0900492void SerializeLogsAsJSON(const base::Value& dictionary,
Eric Caruso0b241882018-04-04 13:43:46 -0700493 const base::ScopedFD& fd) {
Eric Caruso96d03d32017-04-25 18:01:17 -0700494 string logs_json;
Tom Hughesd6c2d392020-08-24 18:12:11 -0700495 base::JSONWriter::WriteWithOptions(
496 dictionary, base::JSONWriter::OPTIONS_PRETTY_PRINT, &logs_json);
Eric Caruso0b241882018-04-04 13:43:46 -0700497 base::WriteFileDescriptor(fd.get(), logs_json.c_str(), logs_json.size());
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800498}
499
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700500bool GetNamedLogFrom(const string& name,
501 const std::vector<Log>& logs,
Elly Jones533c7c42012-08-10 15:07:05 -0400502 string* result) {
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700503 for (const Log& log : logs) {
504 if (name == log.GetName()) {
505 *result = log.GetLogData();
Elly Jones533c7c42012-08-10 15:07:05 -0400506 return true;
507 }
508 }
509 *result = "<invalid log name>";
510 return false;
Elly Jones03cd6d72012-06-11 13:04:28 -0400511}
512
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700513void GetLogsFrom(const std::vector<Log>& logs, LogTool::LogMap* map) {
514 for (const Log& log : logs)
515 (*map)[log.GetName()] = log.GetLogData();
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800516}
517
Kartik Hegde1c4b97b2018-09-09 19:09:34 -0600518void GetLsbReleaseInfo(LogTool::LogMap* map) {
519 const base::FilePath lsb_release(kLsbReleasePath);
520 brillo::KeyValueStore store;
521 if (!store.Load(lsb_release)) {
522 // /etc/lsb-release might not be present (cros deploying a new
523 // configuration or no fields set at all). Just print a debug
524 // message and continue.
525 DLOG(INFO) << "Could not load fields from " << lsb_release.value();
526 } else {
527 for (const auto& key : store.GetKeys()) {
Nikolai Artemiev9a7c3a52021-03-09 12:31:25 +1100528 // The DEVICETYPE from /etc/lsb-release may not be correct on some
529 // unibuild devices, so filter it out. The correct DEVICETYPE is
530 // logged separately using an entry in kCommandLogs that invokes
531 // `cros_config /hardware-properties form-factor`
532 if (key != "DEVICETYPE") {
533 std::string value;
534 store.GetString(key, &value);
535 (*map)[key] = value;
536 }
Kartik Hegde1c4b97b2018-09-09 19:09:34 -0600537 }
538 }
539}
540
541void GetOsReleaseInfo(LogTool::LogMap* map) {
542 brillo::OsReleaseReader reader;
543 reader.Load();
544 for (const auto& key : reader.GetKeys()) {
545 std::string value;
546 reader.GetString(key, &value);
547 (*map)["os-release " + key] = value;
548 }
549}
550
551void PopulateDictionaryValue(const LogTool::LogMap& map,
hscham2311cc22020-10-28 12:13:10 +0900552 base::Value* dictionary) {
Kartik Hegde1c4b97b2018-09-09 19:09:34 -0600553 for (const auto& kv : map) {
hscham2311cc22020-10-28 12:13:10 +0900554 dictionary->SetStringKey(kv.first, kv.second);
Kartik Hegde1c4b97b2018-09-09 19:09:34 -0600555 }
556}
557
Chinglin Yuaeb4ec72018-12-10 18:53:30 +0800558bool CompressXzBuffer(const std::vector<uint8_t>& in_buffer,
559 std::vector<uint8_t>* out_buffer) {
560 size_t out_size = lzma_stream_buffer_bound(in_buffer.size());
561 out_buffer->resize(out_size);
562 size_t out_pos = 0;
563
564 lzma_ret ret = lzma_easy_buffer_encode(
565 LZMA_PRESET_DEFAULT, LZMA_CHECK_CRC64, nullptr, in_buffer.data(),
566 in_buffer.size(), out_buffer->data(), &out_pos, out_size);
567
568 if (ret != LZMA_OK) {
569 out_buffer->clear();
570 return false;
571 }
572
573 out_buffer->resize(out_pos);
574 return true;
575}
576
577void GetPerfData(LogTool::LogMap* map) {
578 // Run perf to collect system-wide performance profile when user triggers
579 // feedback report. Perf runs at sampling frequency of ~500 hz (499 is used
580 // to avoid sampling periodic system activities), with callstack in each
581 // sample (-g).
582 std::vector<std::string> perf_args = {
Tom Hughesd6c2d392020-08-24 18:12:11 -0700583 "perf", "record", "-a", "-g", "-F", "499",
Chinglin Yuaeb4ec72018-12-10 18:53:30 +0800584 };
585 std::vector<uint8_t> perf_data;
586 int32_t status;
587
588 debugd::PerfTool perf_tool;
589 if (!perf_tool.GetPerfOutput(kPerfDurationSecs, perf_args, &perf_data,
590 nullptr, &status, nullptr))
591 return;
592
593 // XZ compress the profile data.
594 std::vector<uint8_t> perf_data_xz;
595 if (!CompressXzBuffer(perf_data, &perf_data_xz))
596 return;
597
598 // Base64 encode the compressed data.
599 std::string perf_data_str(reinterpret_cast<const char*>(perf_data_xz.data()),
600 perf_data_xz.size());
Tom Hughesd6c2d392020-08-24 18:12:11 -0700601 (*map)["perf-data"] = std::string(kPerfDataDescription) +
602 LogTool::EncodeString(std::move(perf_data_str),
603 LogTool::Encoding::kBase64);
Chinglin Yuaeb4ec72018-12-10 18:53:30 +0800604}
605
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800606} // namespace
607
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700608Log::Log(Log::LogType type,
609 std::string name,
610 std::string data,
611 std::string user,
612 std::string group,
613 int64_t max_bytes,
Brian Norrisafc9f632019-05-09 14:08:28 -0700614 LogTool::Encoding encoding,
615 bool access_root_mount_ns)
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700616 : type_(type),
617 name_(name),
618 data_(data),
619 user_(user),
620 group_(group),
621 max_bytes_(max_bytes),
Brian Norrisafc9f632019-05-09 14:08:28 -0700622 encoding_(encoding),
623 access_root_mount_ns_(access_root_mount_ns) {}
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700624
625std::string Log::GetName() const {
626 return name_;
627}
628
629std::string Log::GetLogData() const {
630 // The reason this code uses a switch statement on a type enum rather than
631 // using inheritance/virtual dispatch is so that all of the Log objects can
632 // be constructed statically. Switching to heap allocated subclasses of Log
633 // makes the code that declares all of the log entries much more verbose
634 // and harder to understand.
Chris Morin790fd262019-04-03 20:29:36 -0700635 std::string output;
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700636 switch (type_) {
637 case kCommand:
Chris Morin790fd262019-04-03 20:29:36 -0700638 output = GetCommandLogData();
639 break;
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700640 case kFile:
Chris Morin790fd262019-04-03 20:29:36 -0700641 output = GetFileLogData();
642 break;
Mike Frysinger020c2402020-12-16 05:40:53 -0500643 case kGlob:
644 output = GetGlobLogData();
645 break;
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700646 default:
Mike Frysingerdf3be7f2020-12-16 03:17:42 -0500647 DCHECK(false) << "unknown log type";
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700648 return "<unknown log type>";
649 }
Chris Morin790fd262019-04-03 20:29:36 -0700650
651 if (output.empty())
652 return "<empty>";
653
654 return LogTool::EncodeString(std::move(output), encoding_);
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700655}
656
657// TODO(ellyjones): sandbox. crosbug.com/35122
658std::string Log::GetCommandLogData() const {
Mike Frysingerdf3be7f2020-12-16 03:17:42 -0500659 DCHECK_EQ(type_, kCommand);
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700660 if (type_ != kCommand)
661 return "<log type mismatch>";
662 std::string tailed_cmdline =
663 base::StringPrintf("%s | tail -c %" PRId64, data_.c_str(), max_bytes_);
664 ProcessWithOutput p;
665 if (minijail_disabled_for_test_)
666 p.set_use_minijail(false);
667 if (!user_.empty() && !group_.empty())
668 p.SandboxAs(user_, group_);
Brian Norrisafc9f632019-05-09 14:08:28 -0700669 if (access_root_mount_ns_)
670 p.AllowAccessRootMountNamespace();
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700671 if (!p.Init())
672 return "<not available>";
673 p.AddArg(kShell);
674 p.AddStringOption("-c", tailed_cmdline);
675 if (p.Run())
676 return "<not available>";
677 std::string output;
678 p.GetOutput(&output);
Chris Morin790fd262019-04-03 20:29:36 -0700679 return output;
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700680}
681
Mike Frysinger020c2402020-12-16 05:40:53 -0500682// static
683std::string Log::GetFileData(const base::FilePath& path,
684 int64_t max_bytes,
685 const std::string& user,
686 const std::string& group) {
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700687 uid_t old_euid = geteuid();
Mike Frysinger020c2402020-12-16 05:40:53 -0500688 uid_t new_euid = UidForUser(user);
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700689 gid_t old_egid = getegid();
Mike Frysinger020c2402020-12-16 05:40:53 -0500690 gid_t new_egid = GidForGroup(group);
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700691
692 if (new_euid == -1 || new_egid == -1) {
693 return "<not available>";
694 }
695
696 // Make sure to set group first, since if we set user first we lose root
697 // and therefore the ability to set our effective gid to arbitrary gids.
698 if (setegid(new_egid)) {
699 PLOG(ERROR) << "Failed to set effective group id to " << new_egid;
700 return "<not available>";
701 }
702 if (seteuid(new_euid)) {
703 PLOG(ERROR) << "Failed to set effective user id to " << new_euid;
704 if (setegid(old_egid))
705 PLOG(ERROR) << "Failed to restore effective group id to " << old_egid;
706 return "<not available>";
707 }
708
709 std::string contents;
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700710 // Handle special files that don't properly report length/allow lseek.
711 if (base::FilePath("/dev").IsParent(path) ||
712 base::FilePath("/proc").IsParent(path) ||
713 base::FilePath("/sys").IsParent(path)) {
714 if (!base::ReadFileToString(path, &contents))
715 contents = "<not available>";
Mike Frysinger020c2402020-12-16 05:40:53 -0500716 if (contents.size() > max_bytes)
717 contents.erase(0, contents.size() - max_bytes);
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700718 } else {
719 base::File file(path, base::File::FLAG_OPEN | base::File::FLAG_READ);
720 if (!file.IsValid()) {
721 contents = "<not available>";
722 } else {
723 int64_t length = file.GetLength();
Mike Frysinger020c2402020-12-16 05:40:53 -0500724 if (length > max_bytes) {
725 file.Seek(base::File::FROM_END, -max_bytes);
726 length = max_bytes;
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700727 }
728 std::vector<char> buf(length);
729 int read = file.ReadAtCurrentPos(buf.data(), buf.size());
730 if (read < 0) {
731 PLOG(ERROR) << "Could not read from file " << path.value();
732 } else {
733 contents = std::string(buf.begin(), buf.begin() + read);
734 }
735 }
736 }
737
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700738 // Make sure we restore our old euid/egid before returning.
739 if (seteuid(old_euid))
740 PLOG(ERROR) << "Failed to restore effective user id to " << old_euid;
741
742 if (setegid(old_egid))
743 PLOG(ERROR) << "Failed to restore effective group id to " << old_egid;
744
Chris Morin790fd262019-04-03 20:29:36 -0700745 return contents;
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700746}
747
Mike Frysinger020c2402020-12-16 05:40:53 -0500748std::string Log::GetFileLogData() const {
749 DCHECK_EQ(type_, kFile);
750 if (type_ != kFile)
751 return "<log type mismatch>";
752
753 return GetFileData(base::FilePath(data_), max_bytes_, user_, group_);
754}
755
756std::string Log::GetGlobLogData() const {
757 DCHECK_EQ(type_, kGlob);
758 if (type_ != kGlob)
759 return "<log type mismatch>";
760
761 // NB: base::FileEnumerator requires a directory to walk, and a pattern to
762 // match against each result. Here we accept full paths with globs in them.
763 glob_t g;
764 // NB: Feel free to add GLOB_BRACE if a user comes up.
765 int gret = glob(data_.c_str(), 0, nullptr, &g);
766 if (gret == GLOB_NOMATCH) {
767 globfree(&g);
768 return "<no matches>";
769 } else if (gret) {
770 globfree(&g);
771 PLOG(ERROR) << "glob " << data_ << " failed";
772 return "<not available>";
773 }
774
775 // The results array will hold 2 entries per file: the filename, and the
776 // results of reading that file.
777 size_t output_size = 0;
778 std::vector<std::string> results;
779 results.reserve(g.gl_pathc * 2);
780
781 for (size_t pathc = 0; pathc < g.gl_pathc; ++pathc) {
782 const base::FilePath path(g.gl_pathv[pathc]);
783 std::string contents = GetFileData(path, max_bytes_, user_, group_);
784 // NB: The 3 represents the bytes we add in the output string below.
785 output_size += path.value().size() + contents.size() + 3;
786 results.push_back(path.value());
787 results.push_back(contents);
788 }
789 globfree(&g);
790
791 // Combine the results into a single string. We have a header with the
792 // filename followed by that file's contents. Very basic format.
793 std::string output;
794 output.reserve(output_size);
795 for (auto iter = results.begin(); iter != results.end(); ++iter) {
796 output += *iter + ":\n";
797 ++iter;
798 output += *iter + "\n";
799 }
800
801 return output;
802}
803
Fletcher Woodruff07c28532019-01-24 11:08:53 -0700804void Log::DisableMinijailForTest() {
805 minijail_disabled_for_test_ = true;
806}
807
808// static
809uid_t Log::UidForUser(const std::string& user) {
810 struct passwd entry;
811 struct passwd* result;
812 std::vector<char> buf(1024);
813 getpwnam_r(user.c_str(), &entry, &buf[0], buf.size(), &result);
814 if (!result) {
815 LOG(ERROR) << "User not found: " << user;
816 return -1;
817 }
818 return entry.pw_uid;
819}
820
821// static
822gid_t Log::GidForGroup(const std::string& group) {
823 struct group entry;
824 struct group* result;
825 std::vector<char> buf(1024);
826 getgrnam_r(group.c_str(), &entry, &buf[0], buf.size(), &result);
827 if (!result) {
828 LOG(ERROR) << "Group not found: " << group;
829 return -1;
830 }
831 return entry.gr_gid;
832}
833
mhasankaf5251d2020-04-29 18:53:03 -0700834LogTool::LogTool(
835 scoped_refptr<dbus::Bus> bus,
836 std::unique_ptr<org::chromium::CryptohomeInterfaceProxyInterface>
837 cryptohome_proxy,
838 std::unique_ptr<LogTool::Log> arc_bug_report_log,
839 const base::FilePath& daemon_store_base_dir)
840 : bus_(bus),
841 cryptohome_proxy_(std::move(cryptohome_proxy)),
842 arc_bug_report_log_(std::move(arc_bug_report_log)),
843 daemon_store_base_dir_(daemon_store_base_dir) {}
mhasank80cbe4d2020-04-02 22:46:08 -0700844
mhasank4f599d32020-04-09 22:07:35 -0700845LogTool::LogTool(scoped_refptr<dbus::Bus> bus)
mhasankaf5251d2020-04-29 18:53:03 -0700846 : LogTool(bus,
847 std::make_unique<org::chromium::CryptohomeInterfaceProxy>(bus),
848 std::make_unique<ArcBugReportLog>(),
849 base::FilePath(kDaemonStoreBaseDir)) {}
mhasank4f599d32020-04-09 22:07:35 -0700850
mhasank7186aae2020-09-16 20:06:00 -0700851bool LogTool::IsUserHashValid(const std::string& userhash) {
852 return brillo::cryptohome::home::IsSanitizedUserName(userhash) &&
853 base::PathExists(daemon_store_base_dir_.Append(userhash));
854}
855
Fletcher Woodruff70f27232019-01-24 11:41:34 -0700856void LogTool::CreateConnectivityReport(bool wait_for_results) {
Rebecca Silbersteine78af402014-10-02 10:55:04 -0700857 // Perform ConnectivityTrial to report connection state in feedback log.
Ben Chan8e9f6d02017-09-26 23:04:21 -0700858 auto shill = std::make_unique<org::chromium::flimflam::ManagerProxy>(bus_);
Rebecca Silbersteine78af402014-10-02 10:55:04 -0700859 // Give the connection trial time to test the connection and log the results
860 // before collecting the logs for feedback.
861 // TODO(silberst): Replace the simple approach of a single timeout with a more
862 // coordinated effort.
Fletcher Woodruff70f27232019-01-24 11:41:34 -0700863 if (shill && shill->CreateConnectivityReport(nullptr) && wait_for_results)
Eric Carusocc7106c2017-04-27 14:22:42 -0700864 sleep(kConnectionTesterTimeoutSeconds);
Rebecca Silbersteine78af402014-10-02 10:55:04 -0700865}
866
Eric Carusoc93a15c2017-04-24 16:15:12 -0700867string LogTool::GetLog(const string& name) {
Elly Jones533c7c42012-08-10 15:07:05 -0400868 string result;
Tom Hughesd6c2d392020-08-24 18:12:11 -0700869 GetNamedLogFrom(name, kCommandLogs, &result) ||
Arowa Suliman3bc729c2021-03-09 13:25:00 -0800870 GetNamedLogFrom(name, kCommandLogsShort, &result) ||
Tom Hughesd6c2d392020-08-24 18:12:11 -0700871 GetNamedLogFrom(name, kExtraLogs, &result) ||
872 GetNamedLogFrom(name, kFeedbackLogs, &result);
Elly Jones533c7c42012-08-10 15:07:05 -0400873 return result;
874}
875
Eric Carusof9091f82017-04-28 14:18:59 -0700876LogTool::LogMap LogTool::GetAllLogs() {
Fletcher Woodruff70f27232019-01-24 11:41:34 -0700877 CreateConnectivityReport(false);
Elly Jones533c7c42012-08-10 15:07:05 -0400878 LogMap result;
Arowa Suliman3bc729c2021-03-09 13:25:00 -0800879 GetLogsFrom(kCommandLogsShort, &result);
Ben Chancf7d6412017-08-10 22:30:09 -0700880 GetLogsFrom(kCommandLogs, &result);
881 GetLogsFrom(kExtraLogs, &result);
Kartik Hegde1c4b97b2018-09-09 19:09:34 -0600882 GetLsbReleaseInfo(&result);
883 GetOsReleaseInfo(&result);
Elly Jones533c7c42012-08-10 15:07:05 -0400884 return result;
885}
886
Brian Norrisca4fc042018-04-03 00:24:26 -0700887LogTool::LogMap LogTool::GetAllDebugLogs() {
Fletcher Woodruff70f27232019-01-24 11:41:34 -0700888 CreateConnectivityReport(true);
Brian Norrisca4fc042018-04-03 00:24:26 -0700889 LogMap result;
Arowa Suliman3bc729c2021-03-09 13:25:00 -0800890 GetLogsFrom(kCommandLogsShort, &result);
Brian Norrisca4fc042018-04-03 00:24:26 -0700891 GetLogsFrom(kCommandLogs, &result);
892 GetLogsFrom(kExtraLogs, &result);
mhasankd2b84882020-05-04 17:02:19 -0700893 result[arc_bug_report_log_->GetName()] = GetArcBugReport("", nullptr);
Kartik Hegde1c4b97b2018-09-09 19:09:34 -0600894 GetLsbReleaseInfo(&result);
895 GetOsReleaseInfo(&result);
Brian Norrisca4fc042018-04-03 00:24:26 -0700896 return result;
897}
898
mhasank4f599d32020-04-09 22:07:35 -0700899void LogTool::GetBigFeedbackLogs(const base::ScopedFD& fd,
900 const std::string& username) {
Fletcher Woodruff70f27232019-01-24 11:41:34 -0700901 CreateConnectivityReport(true);
Chinglin Yuaeb4ec72018-12-10 18:53:30 +0800902 LogMap map;
903 GetPerfData(&map);
hscham2311cc22020-10-28 12:13:10 +0900904 base::Value dictionary(base::Value::Type::DICTIONARY);
Arowa Suliman3bc729c2021-03-09 13:25:00 -0800905 GetLogsInDictionary(kCommandLogsVerbose, &dictionary);
Jeffrey Kardatzkee3ec6fd2019-08-05 12:25:17 -0700906 GetLogsInDictionary(kCommandLogs, &dictionary);
907 GetLogsInDictionary(kFeedbackLogs, &dictionary);
mhasankd2b84882020-05-04 17:02:19 -0700908 bool is_backup;
909 std::string arc_bug_report = GetArcBugReport(username, &is_backup);
hscham2311cc22020-10-28 12:13:10 +0900910 dictionary.SetStringKey(kArcBugReportBackupKey,
911 (is_backup ? "true" : "false"));
912 dictionary.SetStringKey(arc_bug_report_log_->GetName(), arc_bug_report);
Kartik Hegde1c4b97b2018-09-09 19:09:34 -0600913 GetLsbReleaseInfo(&map);
914 GetOsReleaseInfo(&map);
915 PopulateDictionaryValue(map, &dictionary);
Ahmed Fakhry21140cf2016-03-04 17:15:19 -0800916 SerializeLogsAsJSON(dictionary, fd);
917}
918
mhasank4f599d32020-04-09 22:07:35 -0700919std::string GetSanitizedUsername(
920 org::chromium::CryptohomeInterfaceProxyInterface* cryptohome_proxy,
mhasankaf5251d2020-04-29 18:53:03 -0700921 const std::string& username) {
mhasank4f599d32020-04-09 22:07:35 -0700922 if (username.empty()) {
923 return std::string();
924 }
925
926 std::string sanitized_username;
927 brillo::ErrorPtr error;
928 if (!cryptohome_proxy->GetSanitizedUsername(username, &sanitized_username,
929 &error)) {
930 LOG(ERROR) << "Failed to call GetSanitizedUsername, error: "
931 << error->GetMessage();
932 return std::string();
933 }
934
935 return sanitized_username;
936}
937
mhasankd2b84882020-05-04 17:02:19 -0700938std::string LogTool::GetArcBugReport(const std::string& username,
939 bool* is_backup) {
940 if (is_backup) {
941 *is_backup = true;
942 }
mhasank4f599d32020-04-09 22:07:35 -0700943 std::string userhash =
944 GetSanitizedUsername(cryptohome_proxy_.get(), username);
945
946 std::string contents;
947 if (userhash.empty() ||
948 arc_bug_report_backups_.find(userhash) == arc_bug_report_backups_.end() ||
Ereth McKnight-MacNeilca3fff22021-01-21 23:31:40 -0800949 !base::ReadFileToString(daemon_store_base_dir_.Append(userhash).Append(
950 kArcBugReportBackupFileName),
mhasank4f599d32020-04-09 22:07:35 -0700951 &contents)) {
952 // If |userhash| was not empty, but was not found in the backup set
953 // or the file did not exist, attempt to delete the file.
954 if (!userhash.empty()) {
mhasank40a80482020-09-09 17:44:24 -0700955 DeleteArcBugReportBackup(username);
mhasank4f599d32020-04-09 22:07:35 -0700956 }
mhasankd2b84882020-05-04 17:02:19 -0700957 if (is_backup) {
958 *is_backup = false;
959 }
mhasankaf5251d2020-04-29 18:53:03 -0700960 contents = arc_bug_report_log_->GetLogData();
mhasank4f599d32020-04-09 22:07:35 -0700961 }
962
963 return contents;
964}
965
mhasank7186aae2020-09-16 20:06:00 -0700966void LogTool::BackupArcBugReport(const std::string& username) {
mhasank80cbe4d2020-04-02 22:46:08 -0700967 DLOG(INFO) << "Backing up ARC bug report";
968
mhasank40a80482020-09-09 17:44:24 -0700969 const std::string userhash =
mhasank7186aae2020-09-16 20:06:00 -0700970 GetSanitizedUsername(cryptohome_proxy_.get(), username);
971 if (!IsUserHashValid(userhash)) {
972 LOG(ERROR) << "Invalid userhash '" << userhash << "'";
973 return;
974 }
mhasank40a80482020-09-09 17:44:24 -0700975
Ereth McKnight-MacNeilca3fff22021-01-21 23:31:40 -0800976 brillo::SafeFD backupDir(
977 brillo::SafeFD::Root()
978 .first.OpenExistingDir(daemon_store_base_dir_.Append(userhash))
979 .first);
980 if (!backupDir.is_valid()) {
981 LOG(ERROR) << "Failed to open ARC bug report backup dir at "
982 << daemon_store_base_dir_.Append(userhash).value();
983 return;
984 }
985
986 brillo::SafeFD backupFile(
987 brillo::OpenOrRemakeFile(&backupDir, kArcBugReportBackupFileName).first);
988 if (!backupFile.is_valid()) {
989 LOG(ERROR) << "Failed to open ARC bug report file at "
990 << daemon_store_base_dir_.Append(userhash)
991 .Append(kArcBugReportBackupFileName)
992 .value();
993 return;
994 }
995
mhasankaf5251d2020-04-29 18:53:03 -0700996 const std::string logData = arc_bug_report_log_->GetLogData();
Ereth McKnight-MacNeilca3fff22021-01-21 23:31:40 -0800997
998 if (backupFile.Write(logData.c_str(), logData.length()) ==
999 brillo::SafeFD::Error::kNoError) {
mhasank4f599d32020-04-09 22:07:35 -07001000 arc_bug_report_backups_.insert(userhash);
1001 } else {
mhasank7186aae2020-09-16 20:06:00 -07001002 PLOG(ERROR) << "Failed to back up ARC bug report";
mhasank80cbe4d2020-04-02 22:46:08 -07001003 }
1004}
1005
mhasank7186aae2020-09-16 20:06:00 -07001006void LogTool::DeleteArcBugReportBackup(const std::string& username) {
mhasank80cbe4d2020-04-02 22:46:08 -07001007 DLOG(INFO) << "Deleting the ARC bug report backup";
1008
mhasank40a80482020-09-09 17:44:24 -07001009 const std::string userhash =
mhasank7186aae2020-09-16 20:06:00 -07001010 GetSanitizedUsername(cryptohome_proxy_.get(), username);
1011 if (!IsUserHashValid(userhash)) {
1012 LOG(ERROR) << "Invalid userhash '" << userhash << "'";
1013 return;
1014 }
mhasank40a80482020-09-09 17:44:24 -07001015
Ereth McKnight-MacNeilca3fff22021-01-21 23:31:40 -08001016 brillo::SafeFD backupDir(
1017 brillo::SafeFD::Root()
1018 .first.OpenExistingDir(daemon_store_base_dir_.Append(userhash))
1019 .first);
1020 if (!backupDir.is_valid()) {
1021 LOG(ERROR) << "Failed to open ARC bug report backup dir at "
1022 << daemon_store_base_dir_.Append(userhash).value();
1023 return;
1024 }
1025
mhasank4f599d32020-04-09 22:07:35 -07001026 arc_bug_report_backups_.erase(userhash);
Ereth McKnight-MacNeilca3fff22021-01-21 23:31:40 -08001027
Muhammad Hasan Khanea172832021-04-01 13:39:30 -07001028 if (base::PathExists(daemon_store_base_dir_.Append(userhash).Append(
1029 kArcBugReportBackupFileName)) &&
1030 backupDir.Unlink(kArcBugReportBackupFileName) !=
1031 brillo::SafeFD::Error::kNoError) {
Ereth McKnight-MacNeilca3fff22021-01-21 23:31:40 -08001032 PLOG(ERROR) << "Failed to delete ARC bug report backup at "
1033 << daemon_store_base_dir_.Append(userhash)
1034 .Append(kArcBugReportBackupFileName)
1035 .value();
mhasank80cbe4d2020-04-02 22:46:08 -07001036 }
1037}
1038
Jeffrey Kardatzkee3ec6fd2019-08-05 12:25:17 -07001039void LogTool::GetJournalLog(const base::ScopedFD& fd) {
Chris Morin790fd262019-04-03 20:29:36 -07001040 Log journal(kCommand, "journal.export", "journalctl -n 10000 -o export",
1041 "syslog", "syslog", 10 * 1024 * 1024, LogTool::Encoding::kBinary);
Jeffrey Kardatzkee3ec6fd2019-08-05 12:25:17 -07001042 std::string output = journal.GetLogData();
Chris Morin790fd262019-04-03 20:29:36 -07001043 base::WriteFileDescriptor(fd.get(), output.data(), output.size());
1044}
1045
Luis Hector Chavezfc2566f2018-09-13 15:00:36 -07001046// static
Tom Hughesd6c2d392020-08-24 18:12:11 -07001047string LogTool::EncodeString(string value, LogTool::Encoding source_encoding) {
Chris Morin790fd262019-04-03 20:29:36 -07001048 if (source_encoding == LogTool::Encoding::kBinary)
1049 return value;
1050
Luis Hector Chavezfc2566f2018-09-13 15:00:36 -07001051 if (source_encoding == LogTool::Encoding::kAutodetect) {
1052 if (base::IsStringUTF8(value))
1053 return value;
Chris Morin790fd262019-04-03 20:29:36 -07001054 source_encoding = LogTool::Encoding::kBase64;
Luis Hector Chavezfc2566f2018-09-13 15:00:36 -07001055 }
1056
1057 if (source_encoding == LogTool::Encoding::kUtf8) {
1058 string output;
1059 const char* src = value.data();
1060 int32_t src_len = static_cast<int32_t>(value.length());
1061
1062 output.reserve(value.size());
1063 for (int32_t char_index = 0; char_index < src_len; char_index++) {
1064 uint32_t code_point;
1065 if (!base::ReadUnicodeCharacter(src, src_len, &char_index, &code_point) ||
1066 !base::IsValidCharacter(code_point)) {
1067 // Replace invalid characters with U+FFFD REPLACEMENT CHARACTER.
1068 code_point = 0xFFFD;
1069 }
1070 base::WriteUnicodeCharacter(code_point, &output);
1071 }
1072 return output;
Luis Hector Chavezfc2566f2018-09-13 15:00:36 -07001073 }
Chris Morin853d3442019-04-01 21:35:13 -07001074
1075 base::Base64Encode(value, &value);
1076 return "<base64>: " + value;
Luis Hector Chavezfc2566f2018-09-13 15:00:36 -07001077}
1078
Ben Chana0011d82014-05-13 00:19:29 -07001079} // namespace debugd