• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/cuttlefish_config.h"
27 
28 using std::uint32_t;
29 
30 namespace cuttlefish {
31 
FileCrc(const std::string & path)32 static 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   std::vector<std::string> files = DirectoryContents(full_path);
49   for (auto it = files.begin(); it != files.end();) {
50     if (*it == "." || *it == "..") {
51       it = files.erase(it);
52     } else {
53       it++;
54     }
55   }
56   std::vector<std::future<uint32_t>> calculations;
57   for (auto& file : files) {
58     file = path + "/" + file; // mutate in place in files vector
59     calculations.emplace_back(
60         std::async(FileCrc, DefaultHostArtifactsPath(file)));
61   }
62   std::map<std::string, uint32_t> crcs;
63   for (int i = 0; i < files.size(); i++) {
64     crcs[files[i]] = calculations[i].get();
65   }
66   return crcs;
67 }
68 
HostToolsCrc()69 std::map<std::string, uint32_t> HostToolsCrc() {
70   auto bin_future = std::async(DirectoryCrc, "bin");
71   auto lib_future = std::async(DirectoryCrc, "lib64");
72   std::map<std::string, uint32_t> all_crcs;
73   for (auto const& [file, crc] : bin_future.get()) {
74     all_crcs[file] = crc;
75   }
76   for (auto const& [file, crc] : lib_future.get()) {
77     all_crcs[file] = crc;
78   }
79   return all_crcs;
80 }
81 
82 } // namespace cuttlefish
83