~nabijaczleweli/klapki

ref: cb46a59c26acba4f7b96ec175bc2175034628b88 klapki/src/state.cpp -rw-r--r-- 6.4 KiB
cb46a59cнаб Fold into TRY_OPT() in main(). Don't try to LTO on GCC 1 year, 4 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
// The MIT License (MIT)

// Copyright (c) 2020 наб <nabijaczleweli@nabijaczleweli.xyz>

// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


#include "state.hpp"
#include "efi.hpp"
#include <cstdlib>
#include <fmt/format.h>
#include <memory>
#include <optional>
extern "C" {
#include <efivar/efivar.h>
// Doesn't include efivar.h:
#include <efivar/efivar-guids.h>
}


template <class F>
static int iterate_efi_vars(F && func) {
	int status;
	efi_guid_t * iter_guid = nullptr;
	char * iter_name       = nullptr;

	while((status = efi_get_next_variable_name(&iter_guid, &iter_name)))
		func(*iter_guid, iter_name);

	if(status < 0)
		return errno;
	return 0;
}

static bool operator==(const efi_guid_t & lhs, const efi_guid_t & rhs) noexcept {
	return !memcmp(&lhs, &rhs, sizeof(efi_guid_t));
}

static bool is_boot_entry(const efi_guid_t & guid, const char * name) noexcept {
	return guid == efi_guid_global && !std::strncmp(name, "Boot", 4) && std::strlen(name) == 8 &&  //
	       std::isxdigit(name[4]) && std::isxdigit(name[5]) && std::isxdigit(name[6]) && std::isxdigit(name[7]);
}

static bool is_boot_order(const efi_guid_t & guid, const char * name) noexcept {
	return guid == efi_guid_global && !std::strcmp(name, "BootOrder");
}

static bool is_our_config(const efi_guid_t & guid, const char * name, const char * us) noexcept {
	return guid == klapki::efi_guid_klapki && !std::strcmp(name, us);
}

template <class F>
static int get_efi_data(const efi_guid_t & guid, const char * name, F && func) {
	std::uint8_t * raw_data{};
	std::size_t size{};
	std::uint32_t attr{};
	if(int res = efi_get_variable(guid, name, &raw_data, &size, &attr))
		return res;

	std::shared_ptr<std::uint8_t[]> data(raw_data, std::free);
	return func(std::move(data), size, attr);
}

static int get_boot_order(klapki::state::boot_order_flat & bord) {
	return get_efi_data(efi_guid_global, "BootOrder", [&](auto && data, auto size, auto) {
		// endianness?
		bord.order     = std::reinterpret_pointer_cast<std::uint16_t[]>(data);
		bord.order_cnt = size / 2;
		return 0;
	});
}

static int get_boot_entry(std::map<std::uint16_t, klapki::state::boot_entry> & bents, std::uint16_t num) {
	// TODO: sprintf() and avoid an allocation instead?
	return get_efi_data(efi_guid_global, fmt::format("Boot{:04X}", num).c_str(), [&](auto && data, auto size, auto attr) {
		bents.emplace(num, klapki::state::boot_entry{std::move(data), size, {}, attr});
		return 0;
	});
}

static int get_our_config(klapki::state::stated_config & statecfg, const char * us) {
	return get_efi_data(klapki::efi_guid_klapki, us,
	                    // TODO: error recovery; flag to ignore? force?
	                    [&](auto && data, auto size, auto) { return klapki::state::stated_config::parse(statecfg, data.get(), size); });
}


std::variant<klapki::state::state, std::string> klapki::state::state::load(const char * argv0, const char * us) {
	if(!efi_variables_supported())
		return fmt::format("{}: EFI not supported?", argv0);


	std::vector<std::uint16_t> boot_entries;
	bool have_boot_order = false;
	bool have_our_config = false;

	if(int res = iterate_efi_vars([&](auto && guid, auto name) {
		   char id_guid_[36 + 2 + 1];
		   auto id_guid = id_guid_;
		   efi_guid_to_id_guid(&guid, &id_guid);
		   // fmt::print("{}\t\t{}\t\t{}\n", id_guid, guid == efi_guid_global, name);

		   if(is_boot_entry(guid, name))
			   boot_entries.emplace_back(std::strtoul(name + std::strlen("Boot"), nullptr, 16));
		   else if(is_boot_order(guid, name))
			   have_boot_order = true;
		   else if(is_our_config(guid, name, us))
			   have_our_config = true;
	   }))
		return fmt::format("{}: klapki::state::state::load(): iteration: {}", argv0, strerror(res));  // No threads here, and we avoid a strerror_r() clusterfuck


	boot_order_flat bord{};
	if(have_boot_order) {
		if(int res = get_boot_order(bord))
			return fmt::format("{}: klapki::state::state::load(): getting BootOrder: {}", argv0, strerror(res));
	} else
		fmt::print(stderr, "{}: no BootOrder?\n", argv0);


	std::map<std::uint16_t, boot_entry> entries;
	for(auto bent : boot_entries)
		if(int res = get_boot_entry(entries, bent))
			return fmt::format("{}: klapki::state::state::load(): getting Boot{:04X}: {}", argv0, bent, strerror(res));


	stated_config statecfg{};
	if(have_our_config) {
		if(int res = get_our_config(statecfg, us))
			return fmt::format("{}: klapki::state::state::load(): getting {}-{}: {}", argv0, efi_guid_klapki_s, us, strerror(res));
	} else
		fmt::print(stderr, "{}: no config for this host ({}) found; going to the top\n", argv0, us);

	return state{std::move(bord), std::move(entries), std::move(statecfg)};
}


bool klapki::state::stated_config_entry::operator==(const klapki::state::stated_config_entry & other) const noexcept {
	return this->bootnum_hint == other.bootnum_hint &&                                   //
	       !std::memcmp(this->load_option_sha, other.load_option_sha, sizeof(sha_t)) &&  //
	       this->version == other.version &&                                             //
	       this->variant == other.variant &&                                             //
	       this->kernel_dirname == other.kernel_dirname &&                               //
	       this->initrd_dirnames == other.initrd_dirnames;
}

bool klapki::state::stated_config::operator==(const klapki::state::stated_config & other) const noexcept {
	return this->boot_position == other.boot_position && this->variants == other.variants && this->wanted_entries == other.wanted_entries;
}