• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (C) 2019 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include <getopt.h>
16 #include <sysexits.h>
17 #include <unistd.h>
18 
19 #include <iostream>
20 #include <optional>
21 
22 #include <android-base/file.h>
23 #include <android-base/logging.h>
24 #include <android-base/unique_fd.h>
25 #include <liblp/builder.h>
26 #include <sparse/sparse.h>
27 
28 using android::base::borrowed_fd;
29 using android::base::unique_fd;
30 using android::fs_mgr::LpMetadata;
31 using android::fs_mgr::MetadataBuilder;
32 using android::fs_mgr::ReadMetadata;
33 using android::fs_mgr::UpdatePartitionTable;
34 using SparsePtr = std::unique_ptr<sparse_file, decltype(&sparse_file_destroy)>;
35 
36 std::optional<TemporaryDir> gTempDir;
37 
usage(const char * program)38 static int usage(const char* program) {
39     std::cerr << program << " - command-line tool for adding partitions to a super.img\n";
40     std::cerr << "\n";
41     std::cerr << "Usage:\n";
42     std::cerr << " " << program << " [options] SUPER PARTNAME PARTGROUP [IMAGE]\n";
43     std::cerr << "\n";
44     std::cerr << "  SUPER                         Path to the super image. It can be sparsed or\n"
45               << "                                unsparsed. If sparsed, it will be unsparsed\n"
46               << "                                temporarily and re-sparsed over the original\n"
47               << "                                file. This will consume extra space during the\n"
48               << "                                execution of " << program << ".\n";
49     std::cerr << "  PARTNAME                      Name of the partition to add.\n";
50     std::cerr << "  PARTGROUP                     Name of the partition group to use. If the\n"
51               << "                                partition can be updated over OTA, the group\n"
52               << "                                should match its updatable group.\n";
53     std::cerr << "  IMAGE                         If specified, the contents of the given image\n"
54               << "                                will be added to the super image. If the image\n"
55               << "                                is sparsed, it will be temporarily unsparsed.\n"
56               << "                                If no image is specified, the partition will\n"
57               << "                                be zero-sized.\n";
58     std::cerr << "\n";
59     std::cerr << "Extra options:\n";
60     std::cerr << "  --readonly                    The partition should be mapped read-only.\n";
61     std::cerr << "  --replace                     The partition contents should be replaced with\n"
62               << "                                the input image.\n";
63     std::cerr << "\n";
64     return EX_USAGE;
65 }
66 
67 enum class OptionCode : int {
68     kReadonly = 1,
69     kReplace = 2,
70 
71     // Special options.
72     kHelp = (int)'h',
73 };
74 
GetTemporaryDir()75 static std::string GetTemporaryDir() {
76     if (!gTempDir) {
77         gTempDir.emplace();
78         int saved_errno = errno;
79         if (access(gTempDir->path, F_OK) != 0) {
80             std::cerr << "Could not create temporary dir: " << gTempDir->path << ": "
81                       << strerror(saved_errno) << std::endl;
82             abort();
83         }
84     }
85     return gTempDir->path;
86 }
87 
88 class LocalSuperOpener final : public android::fs_mgr::PartitionOpener {
89   public:
LocalSuperOpener(const std::string & path,borrowed_fd fd)90     LocalSuperOpener(const std::string& path, borrowed_fd fd)
91         : local_super_(path), local_super_fd_(fd) {}
92 
Open(const std::string & partition_name,int flags) const93     unique_fd Open(const std::string& partition_name, int flags) const override {
94         if (partition_name == local_super_) {
95             return unique_fd{dup(local_super_fd_.get())};
96         }
97         return PartitionOpener::Open(partition_name, flags);
98     }
99 
100   private:
101     std::string local_super_;
102     borrowed_fd local_super_fd_;
103 };
104 
105 class SuperHelper final {
106   public:
SuperHelper(const std::string & super_path)107     explicit SuperHelper(const std::string& super_path) : super_path_(super_path) {}
108 
109     bool Open();
110     bool AddPartition(const std::string& partition_name, const std::string& group_name,
111                       uint32_t attributes, const std::string& image_path, bool replace);
112     bool Finalize();
113 
114   private:
115     bool OpenSuperFile();
116     bool UpdateSuper();
117     bool WritePartition(borrowed_fd fd, uint64_t file_size, const std::string& partition_name);
118     bool WriteExtent(borrowed_fd fd, uint64_t file_size, const LpMetadataExtent& extent);
119 
120     // Returns true if |fd| does not contain a sparsed file. If |fd| does
121     // contain a sparsed file, |temp_file| will contain the unsparsed output.
122     // If |fd| cannot be read or failed to unsparse, false is returned.
123     bool MaybeUnsparse(const std::string& file, borrowed_fd fd,
124                        std::optional<TemporaryFile>* temp_file, uint32_t* block_size = nullptr);
125 
126     std::string super_path_;
127     std::string abs_super_path_;
128     bool was_empty_ = false;
129     // fd for the super file, sparsed or temporarily unsparsed.
130     int super_fd_;
131     // fd for the super file if unsparsed.
132     unique_fd output_fd_;
133     // If the super file is sparse, this holds the temp unsparsed file.
134     std::optional<TemporaryFile> temp_super_;
135     uint32_t sparse_block_size_ = 0;
136     std::unique_ptr<LpMetadata> metadata_;
137     std::unique_ptr<MetadataBuilder> builder_;
138 };
139 
Open()140 bool SuperHelper::Open() {
141     if (!OpenSuperFile()) {
142         return false;
143     }
144 
145     was_empty_ = android::fs_mgr::IsEmptySuperImage(abs_super_path_);
146     if (was_empty_) {
147         metadata_ = android::fs_mgr::ReadFromImageFile(abs_super_path_);
148     } else {
149         metadata_ = android::fs_mgr::ReadMetadata(abs_super_path_, 0);
150     }
151     if (!metadata_) {
152         std::cerr << "Could not read super partition metadata for " << super_path_ << "\n";
153         return false;
154     }
155     builder_ = MetadataBuilder::New(*metadata_.get());
156     if (!builder_) {
157         std::cerr << "Could not create MetadataBuilder for " << super_path_ << "\n";
158         return false;
159     }
160     return true;
161 }
162 
AddPartition(const std::string & partition_name,const std::string & group_name,uint32_t attributes,const std::string & image_path,bool replace)163 bool SuperHelper::AddPartition(const std::string& partition_name, const std::string& group_name,
164                                uint32_t attributes, const std::string& image_path, bool replace) {
165     if (!image_path.empty() && was_empty_) {
166         std::cerr << "Cannot add a partition image to an empty super file.\n";
167         return false;
168     }
169 
170     if (replace) {
171         auto partition = builder_->FindPartition(partition_name);
172         if (!partition) {
173             std::cerr << "Could not find partition to replace: " << partition_name << "\n";
174             return false;
175         }
176         builder_->RemovePartition(partition_name);
177     }
178 
179     auto partition = builder_->AddPartition(partition_name, group_name, attributes);
180     if (!partition) {
181         std::cerr << "Could not add partition: " << partition_name << "\n";
182         return false;
183     }
184 
185     // Open the source image and get its file size so we can resize the
186     // partition.
187     int source_fd = -1;
188     uint64_t file_size;
189     unique_fd raw_image_fd;
190     std::optional<TemporaryFile> temp_image;
191     if (!image_path.empty()) {
192         raw_image_fd.reset(open(image_path.c_str(), O_RDONLY | O_CLOEXEC));
193         if (raw_image_fd < 0) {
194             std::cerr << "open failed: " << image_path << ": " << strerror(errno) << "\n";
195             return false;
196         }
197         if (!MaybeUnsparse(image_path, raw_image_fd, &temp_image)) {
198             return false;
199         }
200         source_fd = temp_image ? temp_image->fd : raw_image_fd.get();
201 
202         auto size = lseek(source_fd, 0, SEEK_END);
203         if (size < 0 || lseek(source_fd, 0, SEEK_SET) < 0) {
204             std::cerr << "lseek failed: " << image_path << ": " << strerror(errno) << "\n";
205             return false;
206         }
207         if (!builder_->ResizePartition(partition, size)) {
208             std::cerr << "Failed to set partition " << partition_name << " size to " << size
209                       << "bytes.\n";
210             return false;
211         }
212         file_size = (uint64_t)size;
213     }
214 
215     // Write the new metadata out. We do this by re-using the on-device flashing
216     // logic, and using the local file instead of a block device.
217     if (!UpdateSuper()) {
218         return false;
219     }
220 
221     // If no partition contents were specified, early return. Otherwise, we
222     // require a full super image to continue writing.
223     if (source_fd >= 0 && !WritePartition(source_fd, file_size, partition_name)) {
224         return false;
225     }
226     return true;
227 }
228 
OpenSuperFile()229 bool SuperHelper::OpenSuperFile() {
230     auto actual_path = super_path_;
231 
232     output_fd_.reset(open(actual_path.c_str(), O_RDWR | O_CLOEXEC));
233     if (output_fd_ < 0) {
234         std::cerr << "open failed: " << actual_path << ": " << strerror(errno) << "\n";
235         return false;
236     }
237     super_fd_ = output_fd_.get();
238 
239     if (!MaybeUnsparse(super_path_, super_fd_, &temp_super_, &sparse_block_size_)) {
240         return false;
241     }
242     if (temp_super_) {
243         actual_path = temp_super_->path;
244         super_fd_ = temp_super_->fd;
245     }
246 
247     // PartitionOpener will decorate relative paths with /dev/block/by-name
248     // so get an absolute path here.
249     if (!android::base::Realpath(actual_path, &abs_super_path_)) {
250         std::cerr << "realpath failed: " << actual_path << ": " << strerror(errno) << "\n";
251         return false;
252     }
253     return true;
254 }
255 
MaybeUnsparse(const std::string & file,borrowed_fd fd,std::optional<TemporaryFile> * temp_file,uint32_t * block_size)256 bool SuperHelper::MaybeUnsparse(const std::string& file, borrowed_fd fd,
257                                 std::optional<TemporaryFile>* temp_file,
258                                 uint32_t* block_size) {
259     SparsePtr sf(sparse_file_import(fd.get(), false, false), sparse_file_destroy);
260     if (!sf) {
261         return true;
262     }
263 
264     temp_file->emplace(GetTemporaryDir());
265     if ((*temp_file)->fd < 0) {
266         std::cerr << "mkstemp failed: " << strerror(errno) << "\n";
267         return false;
268     }
269 
270     std::cout << "Unsparsing " << file << "... " << std::endl;
271 
272     if (sparse_file_write(sf.get(), (*temp_file)->fd, false, false, false) != 0) {
273         std::cerr << "Could not write unsparsed file.\n";
274         return false;
275     }
276     if (block_size) {
277         *block_size = sparse_file_block_size(sf.get());
278     }
279     return true;
280 }
281 
UpdateSuper()282 bool SuperHelper::UpdateSuper() {
283     metadata_ = builder_->Export();
284     if (!metadata_) {
285         std::cerr << "Failed to export new metadata.\n";
286         return false;
287     }
288 
289     // Empty images get written at the very end.
290     if (was_empty_) {
291         return true;
292     }
293 
294     // Note: A/B devices have an extra metadata slot that is unused, so we cap
295     // the writes to the first two slots.
296     LocalSuperOpener opener(abs_super_path_, super_fd_);
297     uint32_t slots = std::min(metadata_->geometry.metadata_slot_count, (uint32_t)2);
298     for (uint32_t i = 0; i < slots; i++) {
299         if (!UpdatePartitionTable(opener, abs_super_path_, *metadata_.get(), i)) {
300             std::cerr << "Could not write new super partition metadata.\n";
301             return false;
302         }
303     }
304     return true;
305 }
306 
WritePartition(borrowed_fd fd,uint64_t file_size,const std::string & partition_name)307 bool SuperHelper::WritePartition(borrowed_fd fd, uint64_t file_size,
308                                  const std::string& partition_name) {
309     auto partition = android::fs_mgr::FindPartition(*metadata_.get(), partition_name);
310     if (!partition) {
311         std::cerr << "Could not find partition in metadata: " << partition_name << "\n";
312         return false;
313     }
314 
315     std::cout << "Writing data for partition " << partition_name << "..." << std::endl;
316     for (uint32_t i = 0; i < partition->num_extents; i++) {
317         auto extent_index = partition->first_extent_index + i;
318         const auto& extent = metadata_->extents[extent_index];
319         if (!WriteExtent(fd, file_size, extent)) {
320             return false;
321         }
322     }
323 
324     // Assert that the full file was written.
325     [[maybe_unused]] auto pos = lseek(fd.get(), 0, SEEK_CUR);
326     CHECK(pos >= 0 && (uint64_t)pos == file_size);
327     return true;
328 }
329 
WriteExtent(borrowed_fd fd,uint64_t file_size,const LpMetadataExtent & extent)330 bool SuperHelper::WriteExtent(borrowed_fd fd, uint64_t file_size, const LpMetadataExtent& extent) {
331     // Must be a linear extent, and there must only be one block device.
332     CHECK(extent.target_type == LP_TARGET_TYPE_LINEAR);
333     CHECK(extent.target_source == 0);
334 
335     auto pos = lseek(fd.get(), 0, SEEK_CUR);
336     if (pos < 0) {
337         std::cerr << "lseek failed: " << strerror(errno) << "\n";
338         return false;
339     }
340 
341     // Clamp the number of bytes to either remaining data in the file, or the
342     // size of this extent.
343     CHECK((uint64_t)pos <= file_size);
344     uint64_t bytes_remaining =
345             std::min(file_size - (uint64_t)pos, extent.num_sectors * LP_SECTOR_SIZE);
346 
347     // Reposition to the appropriate offset in super.
348     if (lseek(super_fd_, extent.target_data * LP_SECTOR_SIZE, SEEK_SET) < 0) {
349         std::cerr << "lseek failed: " << strerror(errno) << "\n";
350         return false;
351     }
352 
353     uint8_t buffer[4096];
354     while (bytes_remaining > 0) {
355         uint64_t bytes = std::min((uint64_t)sizeof(buffer), bytes_remaining);
356         if (!android::base::ReadFully(fd.get(), buffer, bytes)) {
357             std::cerr << "read failed: " << strerror(errno) << "\n";
358             return false;
359         }
360         if (!android::base::WriteFully(super_fd_, buffer, bytes)) {
361             std::cerr << "write failed: " << strerror(errno) << "\n";
362             return false;
363         }
364         bytes_remaining -= bytes;
365     }
366     return true;
367 }
368 
Truncate(borrowed_fd fd)369 static bool Truncate(borrowed_fd fd) {
370     if (ftruncate(fd.get(), 0) < 0) {
371         std::cerr << "truncate failed: " << strerror(errno) << "\n";
372         return false;
373     }
374     if (lseek(fd.get(), 0, SEEK_SET) < 0) {
375         std::cerr << "lseek failed: " << strerror(errno) << "\n";
376         return false;
377     }
378     return true;
379 }
380 
Finalize()381 bool SuperHelper::Finalize() {
382     if (was_empty_) {
383         if (!Truncate(super_fd_)) {
384             return false;
385         }
386         if (!android::fs_mgr::WriteToImageFile(super_fd_, *metadata_.get())) {
387             std::cerr << "Could not write image file.\n";
388             return false;
389         }
390     }
391 
392     // If the super image wasn't original sparsed, we don't have to do anything
393     // else.
394     if (!temp_super_) {
395         return true;
396     }
397 
398     // Otherwise, we have to sparse the temporary file. Find its length.
399     auto len = lseek(super_fd_, 0, SEEK_END);
400     if (len < 0 || lseek(super_fd_, 0, SEEK_SET < 0)) {
401         std::cerr << "lseek failed: " << strerror(errno) << "\n";
402         return false;
403     }
404 
405     SparsePtr sf(sparse_file_new(sparse_block_size_, len), sparse_file_destroy);
406     if (!sf) {
407         std::cerr << "Could not allocate sparse file.\n";
408         return false;
409     }
410     sparse_file_verbose(sf.get());
411 
412     std::cout << "Writing sparse super image... " << std::endl;
413     if (sparse_file_read(sf.get(), super_fd_, SPARSE_READ_MODE_NORMAL, false) != 0) {
414         std::cerr << "Could not import super partition for sparsing.\n";
415         return false;
416     }
417     if (!Truncate(output_fd_)) {
418         return false;
419     }
420     if (sparse_file_write(sf.get(), output_fd_, false, true, false)) {
421         return false;
422     }
423     return true;
424 }
425 
ErrorLogger(android::base::LogId,android::base::LogSeverity severity,const char *,const char *,unsigned int,const char * msg)426 static void ErrorLogger(android::base::LogId, android::base::LogSeverity severity, const char*,
427                         const char*, unsigned int, const char* msg) {
428     if (severity < android::base::WARNING) {
429         return;
430     }
431     std::cerr << msg << std::endl;
432 }
433 
main(int argc,char * argv[])434 int main(int argc, char* argv[]) {
435     struct option options[] = {
436             {"readonly", no_argument, nullptr, (int)OptionCode::kReadonly},
437             {"replace", no_argument, nullptr, (int)OptionCode::kReplace},
438             {nullptr, 0, nullptr, 0},
439     };
440 
441     bool readonly = false;
442     bool replace = false;
443 
444     int rv, index;
445     while ((rv = getopt_long(argc, argv, "h", options, &index)) != -1) {
446         switch ((OptionCode)rv) {
447             case OptionCode::kHelp:
448                 usage(argv[0]);
449                 return EX_OK;
450             case OptionCode::kReadonly:
451                 readonly = true;
452                 break;
453             case OptionCode::kReplace:
454                 replace = true;
455                 break;
456             default:
457                 return usage(argv[0]);
458         }
459     }
460 
461     if (optind + 3 > argc) {
462         std::cerr << "Missing required arguments.\n\n";
463         return usage(argv[0]);
464     }
465 
466     std::string super_path = argv[optind++];
467     std::string partition_name = argv[optind++];
468     std::string group_name = argv[optind++];
469     std::string image_path;
470 
471     if (optind < argc) {
472         image_path = argv[optind++];
473     }
474     if (optind != argc) {
475         std::cerr << "Unexpected arguments.\n\n";
476         return usage(argv[0]);
477     }
478 
479     // Suppress log spam from liblp.
480     android::base::SetLogger(ErrorLogger);
481 
482     SuperHelper super(super_path);
483     if (!super.Open()) {
484         return EX_SOFTWARE;
485     }
486 
487     uint32_t attributes = LP_PARTITION_ATTR_NONE;
488     if (readonly) {
489         attributes |= LP_PARTITION_ATTR_READONLY;
490     }
491     if (!super.AddPartition(partition_name, group_name, attributes, image_path, replace)) {
492         return EX_SOFTWARE;
493     }
494     if (!super.Finalize()) {
495         return EX_SOFTWARE;
496     }
497 
498     std::cout << "Done.\n";
499     return EX_OK;
500 }
501