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 
17 #include <inttypes.h>
18 
19 #include <android-base/stringprintf.h>
20 #include <kver/kernel_release.h>
21 
22 namespace android::kver {
23 
24 #define KERNEL_RELEASE_PRINT_FORMAT \
25   "%" PRIu64 ".%" PRIu64 ".%" PRIu64 "-android%" PRIu64 "-%" PRIu64
26 #define KERNEL_RELEASE_SCAN_FORMAT KERNEL_RELEASE_PRINT_FORMAT "%n"
27 
28 // Not taking a string_view because sscanf requires null-termination.
29 std::optional<KernelRelease> KernelRelease::Parse(const std::string& s, bool allow_suffix) {
30   if (s.size() > std::numeric_limits<int>::max()) return std::nullopt;
31   int nchars = -1;
32   KernelRelease ret;
33   auto scan_res = sscanf(s.c_str(), KERNEL_RELEASE_SCAN_FORMAT, &ret.kmi_version_.version_,
34                          &ret.kmi_version_.patch_level_, &ret.sub_level_,
35                          &ret.kmi_version_.release_, &ret.kmi_version_.gen_, &nchars);
36   if (scan_res != 5) return std::nullopt;
37   if (nchars < 0) return std::nullopt;
38   // If !allow_suffix, ensure the whole string is consumed.
39   if (!allow_suffix && nchars != s.size()) return std::nullopt;
40   return ret;
41 }
42 
43 std::string KernelRelease::string() const {
44   return android::base::StringPrintf(KERNEL_RELEASE_PRINT_FORMAT, version(), patch_level(),
45                                      sub_level(), android_release(), generation());
46 }
47 
48 std::tuple<uint64_t, uint64_t, uint64_t> KernelRelease::kernel_version_tuple() const {
49   return std::make_tuple(version(), patch_level(), sub_level());
50 }
51 
52 }  // namespace android::kver
53