~nabijaczleweli/klapki

ref: cb46a59c26acba4f7b96ec175bc2175034628b88 klapki/src/context_age.cpp -rw-r--r-- 6.7 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
165
166
167
168
169
// 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 "config.hpp"
#include "context.hpp"
#include "quickscope_wrapper.hpp"
#include <algorithm>
#include <stdlib.h>
extern "C" {
#include <efivar/efivar.h>
}


#define TRY(...)                                       \
	({                                                   \
		auto ret = __VA_ARGS__;                            \
		if(auto err = std::get_if<std::string>(&ret); err) \
			return std::move(*err);                          \
		std::move(std::get<0>(ret));                       \
	})


struct fresh_kernel {
	std::string_view version;
	std::pair<std::string_view, std::string_view> image;
	std::vector<std::pair<std::string_view, std::string_view>> initrds;
};

namespace {
	static std::variant<klapki::context::detail::bad_cow, std::string> unrelativise(const std::pair<std::string_view, std::string_view> & whom,
	                                                                                const char * version, const char * for_what) {
		if(whom.first[0] != '/') {
			fmt::print(stderr, "{} {} has relative path {}/{}", version, for_what, whom.first, whom.second);

			std::string reldir{whom.first};
			const auto dir = realpath(reldir.c_str(), nullptr);
			if(!dir) {
				fmt::print(stderr, "\n");
				return fmt::format("Getting realpath for {}: {}", reldir, strerror(errno));
			}
			klapki::quickscope_wrapper dir_deleter{[&] { std::free(dir); }};

			fmt::print(stderr, ", updating to {}/{}\n", dir, whom.second);
			return klapki::context::detail::bad_cow{std::string{dir}};
		} else
			return klapki::context::detail::bad_cow{whom.first};
	}

	/// Actually just find lowest unoccupied
	static std::variant<std::uint16_t, std::string> allocate_bootnum(const klapki::state::state & state) {
		std::uint16_t max{};
		if(auto found = adjacent_find(std::begin(state.entries), std::end(state.entries),
		                              [&](auto && prev, auto && next) {
			                              max = next.first;
			                              return next.first - prev.first != 1;
		                              });
		   found != std::end(state.entries))
			return static_cast<std::uint16_t>(found->first + 1);
		else if(max != 0xFFFF)
			return static_cast<std::uint16_t>(max + 1);
		else
			return "Out of boot entries";
	}

	static void append_bootorder_entry(klapki::state::boot_order_t & bord, std::uint16_t bootnum) {
		std::visit(klapki::overload{
		               [&](klapki::state::boot_order_flat &) { throw __func__; },  // can't (shouldn't) happen; not like we can do much with this
		               [&](klapki::state::boot_order_structured & bos) {
			               if(!bos.order.empty())
				               if(bos.order.back().second == true) {
					               bos.order.back().first.emplace_back(bootnum);
					               return;
				               }

			               bos.order.emplace_back(std::pair{std::vector{bootnum}, true});
		               },
		           },
		           bord);
	}

	static std::vector<klapki::state::nonbase_dirname_t> compact_initrd_dirs(std::string_view prev_dir,
	                                                                         std::vector<klapki::context::detail::bad_cow> initrd_dirs) {
		std::vector<klapki::state::nonbase_dirname_t> ret;
		ret.reserve(initrd_dirs.size());

		for(auto && idir : initrd_dirs) {
			if(idir.get() == prev_dir)
				ret.emplace_back();
			else
				ret.emplace_back(idir.get());

			prev_dir = idir.get();
		}

		return ret;
	}
}


std::optional<std::string> klapki::context::context::age(const config & cfg, state::state & state) {
	std::vector<fresh_kernel> fkerns;
	fkerns.swap(this->fresh_kernels);
	for(auto && fkern : std::move(fkerns)) {
		if(cfg.verbose)
			fmt::print("Aging fresh kernel {}…\n", fkern.version);

		const auto image_dir = TRY(unrelativise(fkern.image, fkern.version.data(), "image"));

		std::vector<detail::bad_cow> initrd_dirs_raw;
		initrd_dirs_raw.reserve(fkern.initrds.size());
		for(auto && initrd : fkern.initrds)
			initrd_dirs_raw.emplace_back(TRY(unrelativise(initrd, fkern.version.data(), "initrd")));
		const auto initrd_dirs = compact_initrd_dirs(image_dir.get(), std::move(initrd_dirs_raw));

		std::vector<std::pair<state::nonbase_dirname_t, std::string>> our_initrd_paths;
		our_initrd_paths.reserve(fkern.initrds.size());
		for(auto && initrd : fkern.initrds)
			our_initrd_paths.emplace_back(std::nullopt, initrd.second);

		// \base\version
		const auto efi_base    = fmt::format("{}{}\\", cfg.news_efi_dir(), fkern.version);
		const auto variant_cbk = [&](const char * var) -> std::variant<std::monostate, std::string> {
			const auto new_bootnum = TRY(allocate_bootnum(state));
			if(cfg.verbose) {
				if(var[0] == '\0')
					fmt::print("  Default variant");
				else
					fmt::print("  Variant {}", var);
				fmt::print(" assigned bootnum {:04X}\n", new_bootnum);
			}


			append_bootorder_entry(state.order, new_bootnum);
			state.statecfg.wanted_entries.emplace_back(
			    state::stated_config_entry{new_bootnum, {0xFF}, std::string{fkern.version}, var, std::string{image_dir.get()}, initrd_dirs});

			state.entries.emplace(new_bootnum,
			                      state::boot_entry{{}, 0, {0x00}, EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS});
			this->our_kernels.emplace(new_bootnum, our_kernel{"", "", {}, {efi_base, std::string{fkern.image.second}}, our_initrd_paths});
			// state::stated_config_entry{new_bootnum, {0xFF}, std::string{fkern.version}, var, efi_base, });

			return std::monostate{};
		};
		TRY(variant_cbk(""));
		for(auto && var : state.statecfg.variants)
			TRY(variant_cbk(var.c_str()));
	}

	return {};
}