1 //
2 // Copyright (C) 2020 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 #include "host/libs/config/host_tools_version.h"
17
18 #include <algorithm>
19 #include <fstream>
20 #include <future>
21 #include <vector>
22
23 #include <zlib.h>
24
25 #include "common/libs/utils/files.h"
26 #include "host/libs/config/config_utils.h"
27
28 using std::uint32_t;
29
30 namespace cuttlefish {
31
FileCrc(const std::string & path)32 uint32_t FileCrc(const std::string& path) {
33 uint32_t crc = crc32(0, (unsigned char*) path.c_str(), path.size());
34 std::ifstream file_stream(path, std::ifstream::binary);
35 std::vector<char> data(1024, 0);
36 while (file_stream) {
37 file_stream.read(data.data(), data.size());
38 crc = crc32(crc, (unsigned char*) data.data(), file_stream.gcount());
39 }
40 return crc;
41 }
42
DirectoryCrc(const std::string & path)43 static std::map<std::string, uint32_t> DirectoryCrc(const std::string& path) {
44 auto full_path = DefaultHostArtifactsPath(path);
45 if (!DirectoryExists(full_path)) {
46 return {};
47 }
48 auto files_result = DirectoryContents(full_path);
49 CHECK(files_result.ok()) << files_result.error().FormatForEnv();
50 std::vector<std::string> files = std::move(*files_result);
51 for (auto it = files.begin(); it != files.end();) {
52 if (*it == "." || *it == "..") {
53 it = files.erase(it);
54 } else {
55 it++;
56 }
57 }
58 std::vector<std::future<uint32_t>> calculations;
59 calculations.reserve(files.size());
60 for (auto& file : files) {
61 file = path + "/" + file; // mutate in place in files vector
62 calculations.emplace_back(
63 std::async(FileCrc, DefaultHostArtifactsPath(file)));
64 }
65 std::map<std::string, uint32_t> crcs;
66 for (int i = 0; i < files.size(); i++) {
67 crcs[files[i]] = calculations[i].get();
68 }
69 return crcs;
70 }
71
HostToolsCrc()72 std::map<std::string, uint32_t> HostToolsCrc() {
73 auto bin_future = std::async(DirectoryCrc, "bin");
74 auto lib_future = std::async(DirectoryCrc, "lib64");
75 std::map<std::string, uint32_t> all_crcs;
76 for (auto const& [file, crc] : bin_future.get()) {
77 all_crcs[file] = crc;
78 }
79 for (auto const& [file, crc] : lib_future.get()) {
80 all_crcs[file] = crc;
81 }
82 return all_crcs;
83 }
84
85 } // namespace cuttlefish
86