1 /*
2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "host/commands/cvd/server_command/start_impl.h"
18
19 #include <fstream>
20 #include <regex>
21
22 #include <android-base/strings.h>
23
24 #include "common/libs/utils/files.h"
25 #include "host/commands/cvd/common_utils.h"
26
27 namespace cuttlefish {
28 namespace cvd_start_impl {
29
30 /* Picks up the line starting with [*] GUEST_BUILD_FINGERPRINT:,
31 * and removes the "[*] GUEST_BUILD_FINGERPRINT:" part.
32 *
33 */
ExtractBuildIdLineValue(const std::string & home_dir)34 static Result<std::string> ExtractBuildIdLineValue(
35 const std::string& home_dir) {
36 std::string kernel_log_path =
37 ConcatToString(home_dir, "/cuttlefish_runtime/kernel.log");
38 if (!FileExists(kernel_log_path)) {
39 kernel_log_path =
40 ConcatToString(home_dir, "/cuttlefish_runtime_runtime/kernel.log");
41 }
42 std::ifstream kernel_log_file(kernel_log_path);
43 CF_EXPECT(kernel_log_file.is_open(),
44 "The " << kernel_log_path << " is not open.");
45 std::regex pattern("\\[\\s*[0-9]*\\.[0-9]+\\]\\s*GUEST_BUILD_FINGERPRINT:");
46 for (std::string line; std::getline(kernel_log_file, line);) {
47 std::smatch matched;
48 if (!std::regex_search(line, matched, pattern)) {
49 continue;
50 }
51 return matched.suffix().str();
52 }
53 auto err_message =
54 ConcatToString("The GUEST_BUILD_FINGERPRINT line is not found in the",
55 kernel_log_path, " file");
56 return CF_ERR(err_message);
57 }
58
ExtractBuildId(const std::string & home_dir)59 Result<std::string> ExtractBuildId(const std::string& home_dir) {
60 auto fingerprint_line_value = CF_EXPECT(ExtractBuildIdLineValue(home_dir));
61 /* format:
62 * <not sure>/target/build year/branch.id/who built it/when:target/??
63 *
64 * We need the branch followed by . followed by sort of Id part
65 */
66 std::vector<std::string> tokens =
67 android::base::Tokenize(fingerprint_line_value, "/");
68 CF_EXPECT(tokens.size() > 2);
69 return tokens.at(3);
70 }
71
72 } // namespace cvd_start_impl
73 } // namespace cuttlefish
74