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 std::vector<std::future<uint32_t>> calculations;
52 calculations.reserve(files.size());
53 for (auto& file : files) {
54 file = path + "/" + file; // mutate in place in files vector
55 calculations.emplace_back(
56 std::async(FileCrc, DefaultHostArtifactsPath(file)));
57 }
58 std::map<std::string, uint32_t> crcs;
59 for (int i = 0; i < files.size(); i++) {
60 crcs[files[i]] = calculations[i].get();
61 }
62 return crcs;
63 }
64
HostToolsCrc()65 std::map<std::string, uint32_t> HostToolsCrc() {
66 auto bin_future = std::async(DirectoryCrc, "bin");
67 auto lib_future = std::async(DirectoryCrc, "lib64");
68 std::map<std::string, uint32_t> all_crcs;
69 for (auto const& [file, crc] : bin_future.get()) {
70 all_crcs[file] = crc;
71 }
72 for (auto const& [file, crc] : lib_future.get()) {
73 all_crcs[file] = crc;
74 }
75 return all_crcs;
76 }
77
78 } // namespace cuttlefish
79