~nabijaczleweli/klapki

ref: cb46a59c26acba4f7b96ec175bc2175034628b88 klapki/src/context_save.cpp -rw-r--r-- 7.6 KiB
cb46a59cнаб Fold into TRY_OPT() in main(). Don't try to LTO on GCC 1 year, 30 days 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
// 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 <algorithm>
// #include <fcntl.h>
#include <openssl/sha.h>
extern "C" {
#include <efivar/efiboot.h>
}


using sha_t = std::uint8_t[20];


static constexpr bool isslash(char c) {
	return c == '\\' || c == '/';
}


std::optional<std::string> klapki::context::context::save(const config & cfg, state::state & state) {
	const auto esp_blockdev = fmt::format("/dev/block/{}:0", major(cfg.esp.first));

	for(auto && [bootnum, kern] : this->our_kernels) {
		auto skern = std::find_if(std::begin(state.statecfg.wanted_entries), std::end(state.statecfg.wanted_entries),
		                          [bn = bootnum](auto && skern) { return skern.bootnum_hint == bn; });
		if(skern == std::end(state.statecfg.wanted_entries))
			throw __func__;
		auto bent = state.entries.find(bootnum);
		if(bent == std::end(state.entries))
			throw __func__;

		std::vector<std::uint8_t> devpath;
		auto image_path = fmt::format("{}{}{}", skern->kernel_dirname, isslash(skern->kernel_dirname.back()) ? "" : "\\", kern.image_path.second);
		image_path.erase(std::remove_if(std::begin(image_path), std::end(image_path),
		                                [prev = false](auto c) mutable {
			                                auto cur = isslash(c);
			                                if(prev && cur)
				                                return true;
			                                else {
				                                prev = cur;
				                                return false;
			                                }
		                                }),
		                 std::end(image_path));
		fmt::print("{}\n", image_path);
		fmt::print("{}\n", kern.image_path.second);
		do {
			devpath.resize(devpath.size() + 512);

			// extern ssize_t efi_generate_file_device_path_from_esp(uint8_t *buf,
			// 	      ssize_t size,
			// 	      const char *devpath,
			// 	      int partition,
			// 	      const char *relpath,
			// 	      uint32_t options, ...)
			if(auto size = efi_generate_file_device_path_from_esp(devpath.data(), devpath.size(),              //
			                                                      esp_blockdev.c_str(), minor(cfg.esp.first),  //
			                                                      image_path.c_str(),                          //
			                                                      0);
			   size >= 0)
				devpath.resize(size);
			else if(errno != ENOSPC)
				return fmt::format("Making device path for {:04X}: {}", bootnum, strerror(errno));
		} while(errno == ENOSPC);


		// extern ssize_t efi_loadopt_create(uint8_t *buf, ssize_t size,
		//				  uint32_t attributes, efidp dp,
		//				  ssize_t dp_size, unsigned char *description,
		//				  uint8_t *optional_data,
		//				  size_t optional_data_size)
		bent->second.load_option_len = efi_loadopt_create(nullptr, 0,                                                      //
		                                                  bent->second.attributes,                                         //
		                                                  reinterpret_cast<efidp_data *>(devpath.data()), devpath.size(),  //
		                                                  reinterpret_cast<unsigned char *>(kern.description.data()),      //
		                                                  reinterpret_cast<std::uint8_t *>(kern.cmdline.data()), kern.cmdline.size());

		bent->second.load_option = std::shared_ptr<std::uint8_t[]>{new std::uint8_t[bent->second.load_option_len + 512]};
		if(efi_loadopt_create(bent->second.load_option.get(), bent->second.load_option_len,    //
		                      bent->second.attributes,                                         //
		                      reinterpret_cast<efidp_data *>(devpath.data()), devpath.size(),  //
		                      reinterpret_cast<unsigned char *>(kern.description.data()),      //
		                      reinterpret_cast<std::uint8_t *>(kern.cmdline.data()), kern.cmdline.size()) < 0)
			return fmt::format("Making load option for {:04X}: {}", bootnum, strerror(errno));

		// write(open("oot", O_WRONLY | O_CREAT | O_DSYNC | O_TRUNC), bent->second.load_option.get(), bent->second.load_option_len);

		SHA1(bent->second.load_option.get(), bent->second.load_option_len, bent->second.load_option_sha);
		if(!std::memcmp(bent->second.load_option_sha, skern->load_option_sha, sizeof(sha_t)))
			fmt::print("Entry {:04X} changed\n", bootnum);
		std::memcpy(skern->load_option_sha, bent->second.load_option_sha, sizeof(sha_t));
	}


	if(cfg.verbose)
		fmt::print("Bootorder pre : {}\n", state.order);
	state.order =
	    std::visit(klapki::overload{
	                   [&](klapki::state::boot_order_flat && bof) {
		                   fmt::print(stderr, "wisen(): flat bootorder?\n");  // Weird, but that's what we want anyway
		                   return std::move(bof);
	                   },
	                   [&](klapki::state::boot_order_structured && bos) {
		                   std::vector<std::uint16_t> bents[2];
		                   for(auto && [cluster, ours] : std::move(bos.order))
			                   if(bents[ours].empty())
				                   bents[ours] = std::move(cluster);
			                   else
				                   bents[ours].insert(std::end(bents[ours]), std::begin(cluster), std::end(cluster));

		                   const auto target_pos = std::min(bents[false].size(), static_cast<std::size_t>(state.statecfg.boot_position));
		                   if(bents[false].size() < state.statecfg.boot_position)
			                   fmt::print(stderr, "Not enough entries to be at position {}. Being at {} instead.\n", state.statecfg.boot_position, target_pos);

		                   const auto size = bents[false].size() + bents[true].size();
		                   const std::shared_ptr<std::uint16_t[]> flat{new std::uint16_t[size]};
		                   std::memset(flat.get(), 0xFA, size * 2);

		                   // TODO: sort by version? variant?
		                   auto curs = std::copy_n(bents[false].data(), target_pos, flat.get());
		                   curs      = std::copy_n(bents[true].data(), bents[true].size(), curs);
		                   curs      = std::copy_n(bents[false].data() + target_pos, bents[false].size() - target_pos, curs);
		                   if(curs != flat.get() + size)  // This is an assert() but asserts blow ass, so it's a throw instead
			                   throw __func__;

		                   return state::boot_order_flat{flat, size};
	                   },
	               },
	               std::move(state.order));
	if(cfg.verbose)
		fmt::print("Bootorder post: {}\n", state.order);

	return {};
}