xref: /rk3399_rockchip-uboot/lib/avb/libavb/avb_slot_verify.c (revision 258d2dcb26879538abc00fc64a8a34c45c046465)
1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Permission is hereby granted, free of charge, to any person
5  * obtaining a copy of this software and associated documentation
6  * files (the "Software"), to deal in the Software without
7  * restriction, including without limitation the rights to use, copy,
8  * modify, merge, publish, distribute, sublicense, and/or sell copies
9  * of the Software, and to permit persons to whom the Software is
10  * furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be
13  * included in all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
19  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
20  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  */
24 #include <common.h>
25 #include <sysmem.h>
26 #include <android_avb/avb_slot_verify.h>
27 #include <android_avb/avb_chain_partition_descriptor.h>
28 #include <android_avb/avb_cmdline.h>
29 #include <android_avb/avb_footer.h>
30 #include <android_avb/avb_hash_descriptor.h>
31 #include <android_avb/avb_hashtree_descriptor.h>
32 #include <android_avb/avb_kernel_cmdline_descriptor.h>
33 #include <android_avb/avb_sha.h>
34 #include <android_avb/avb_util.h>
35 #include <android_avb/avb_vbmeta_image.h>
36 #include <android_avb/avb_version.h>
37 
38 /* Maximum number of partitions that can be loaded with avb_slot_verify(). */
39 #define MAX_NUMBER_OF_LOADED_PARTITIONS 32
40 
41 /* Maximum number of vbmeta images that can be loaded with avb_slot_verify(). */
42 #define MAX_NUMBER_OF_VBMETA_IMAGES 32
43 
44 /* Maximum size of a vbmeta image - 64 KiB. */
45 #define VBMETA_MAX_SIZE (64 * 1024)
46 
47 static AvbSlotVerifyResult initialize_persistent_digest(
48     AvbOps* ops,
49     const char* part_name,
50     const char* persistent_value_name,
51     size_t digest_size,
52     const uint8_t* initial_digest,
53     uint8_t* out_digest);
54 
55 /* Helper function to see if we should continue with verification in
56  * allow_verification_error=true mode if something goes wrong. See the
57  * comments for the avb_slot_verify() function for more information.
58  */
59 static inline bool result_should_continue(AvbSlotVerifyResult result) {
60   switch (result) {
61     case AVB_SLOT_VERIFY_RESULT_ERROR_OOM:
62     case AVB_SLOT_VERIFY_RESULT_ERROR_IO:
63     case AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA:
64     case AVB_SLOT_VERIFY_RESULT_ERROR_UNSUPPORTED_VERSION:
65     case AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT:
66       return false;
67 
68     case AVB_SLOT_VERIFY_RESULT_OK:
69     case AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION:
70     case AVB_SLOT_VERIFY_RESULT_ERROR_ROLLBACK_INDEX:
71     case AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED:
72       return true;
73   }
74 
75   return false;
76 }
77 
78 static AvbSlotVerifyResult load_full_partition(AvbOps* ops,
79                                                const char* part_name,
80                                                uint64_t image_size,
81                                                uint8_t** out_image_buf,
82                                                bool* out_image_preloaded,
83                                                int allow_verification_error) {
84   size_t part_num_read;
85   AvbIOResult io_ret;
86 
87   /* Make sure that we do not overwrite existing data. */
88   avb_assert(*out_image_buf == NULL);
89   avb_assert(!*out_image_preloaded);
90 
91   /* We are going to implicitly cast image_size from uint64_t to size_t in the
92    * following code, so we need to make sure that the cast is safe. */
93   if (image_size != (size_t)(image_size)) {
94     avb_errorv(part_name, ": Partition size too large to load.\n", NULL);
95     return AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
96   }
97 
98   /* Try use a preloaded one. */
99   if (ops->get_preloaded_partition != NULL) {
100     io_ret = ops->get_preloaded_partition(
101         ops, part_name, image_size, out_image_buf, &part_num_read,
102 	allow_verification_error);
103     if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
104       return AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
105     } else if (io_ret != AVB_IO_RESULT_OK) {
106       avb_errorv(part_name, ": Error loading data from partition.\n", NULL);
107       return AVB_SLOT_VERIFY_RESULT_ERROR_IO;
108     }
109 
110     if (*out_image_buf != NULL) {
111       if (part_num_read != image_size) {
112         avb_errorv(part_name, ": Read incorrect number of bytes.\n", NULL);
113         return AVB_SLOT_VERIFY_RESULT_ERROR_IO;
114       }
115       *out_image_preloaded = true;
116     }
117   }
118 
119   /* Allocate and copy the partition. */
120   if (!*out_image_preloaded) {
121     *out_image_buf = sysmem_alloc(MEM_AVB_ANDROID, image_size);
122     if (*out_image_buf == NULL) {
123       return AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
124     }
125 
126     io_ret = ops->read_from_partition(ops,
127                                       part_name,
128                                       0 /* offset */,
129                                       image_size,
130                                       *out_image_buf,
131                                       &part_num_read);
132     if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
133       return AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
134     } else if (io_ret != AVB_IO_RESULT_OK) {
135       avb_errorv(part_name, ": Error loading data from partition.\n", NULL);
136       return AVB_SLOT_VERIFY_RESULT_ERROR_IO;
137     }
138     if (part_num_read != image_size) {
139       avb_errorv(part_name, ": Read incorrect number of bytes.\n", NULL);
140       return AVB_SLOT_VERIFY_RESULT_ERROR_IO;
141     }
142   }
143 
144   return AVB_SLOT_VERIFY_RESULT_OK;
145 }
146 
147 /* Reads a persistent digest stored as a named persistent value corresponding to
148  * the given |part_name|. The value is returned in |out_digest| which must point
149  * to |expected_digest_size| bytes. If there is no digest stored for |part_name|
150  * it can be initialized by providing a non-NULL |initial_digest| of length
151  * |expected_digest_size|. This automatic initialization will only occur if the
152  * device is currently locked. The |initial_digest| may be NULL.
153  *
154  * Returns AVB_SLOT_VERIFY_RESULT_OK on success, otherwise returns an
155  * AVB_SLOT_VERIFY_RESULT_ERROR_* error code.
156  *
157  * If the value does not exist, is not supported, or is not populated, and
158  * |initial_digest| is NULL, returns
159  * AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA. If |expected_digest_size| does
160  * not match the stored digest size, also returns
161  * AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA.
162  */
163 static AvbSlotVerifyResult read_persistent_digest(AvbOps* ops,
164                                                   const char* part_name,
165                                                   size_t expected_digest_size,
166                                                   const uint8_t* initial_digest,
167                                                   uint8_t* out_digest) {
168   char* persistent_value_name = NULL;
169   AvbIOResult io_ret = AVB_IO_RESULT_OK;
170   size_t stored_digest_size = 0;
171 
172   if (ops->read_persistent_value == NULL) {
173     avb_errorv(part_name, ": Persistent values are not implemented.\n", NULL);
174     return AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
175   }
176   persistent_value_name =
177       avb_strdupv(AVB_NPV_PERSISTENT_DIGEST_PREFIX, part_name, NULL);
178   if (persistent_value_name == NULL) {
179     return AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
180   }
181 
182   io_ret = ops->read_persistent_value(ops,
183                                       persistent_value_name,
184                                       expected_digest_size,
185                                       out_digest,
186                                       &stored_digest_size);
187 
188   // If no such named persistent value exists and an initial digest value was
189   // given, initialize the named persistent value with the given digest. If
190   // initialized successfully, this will recurse into this function but with a
191   // NULL initial_digest.
192   if (io_ret == AVB_IO_RESULT_ERROR_NO_SUCH_VALUE && initial_digest) {
193     AvbSlotVerifyResult ret =
194         initialize_persistent_digest(ops,
195                                      part_name,
196                                      persistent_value_name,
197                                      expected_digest_size,
198                                      initial_digest,
199                                      out_digest);
200     avb_free(persistent_value_name);
201     return ret;
202   }
203   avb_free(persistent_value_name);
204 
205   if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
206     return AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
207   } else if (io_ret == AVB_IO_RESULT_ERROR_NO_SUCH_VALUE) {
208     // Treat a missing persistent value as a verification error, which is
209     // ignoreable, rather than a metadata error which is not.
210     avb_errorv(part_name, ": Persistent digest does not exist.\n", NULL);
211     return AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION;
212   } else if (io_ret == AVB_IO_RESULT_ERROR_INVALID_VALUE_SIZE ||
213              io_ret == AVB_IO_RESULT_ERROR_INSUFFICIENT_SPACE) {
214     avb_errorv(
215         part_name, ": Persistent digest is not of expected size.\n", NULL);
216     return AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
217   } else if (io_ret != AVB_IO_RESULT_OK) {
218     avb_errorv(part_name, ": Error reading persistent digest.\n", NULL);
219     return AVB_SLOT_VERIFY_RESULT_ERROR_IO;
220   } else if (expected_digest_size != stored_digest_size) {
221     avb_errorv(
222         part_name, ": Persistent digest is not of expected size.\n", NULL);
223     return AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
224   }
225   return AVB_SLOT_VERIFY_RESULT_OK;
226 }
227 
228 static AvbSlotVerifyResult initialize_persistent_digest(
229     AvbOps* ops,
230     const char* part_name,
231     const char* persistent_value_name,
232     size_t digest_size,
233     const uint8_t* initial_digest,
234     uint8_t* out_digest) {
235   AvbSlotVerifyResult ret;
236   AvbIOResult io_ret = AVB_IO_RESULT_OK;
237   bool is_device_unlocked = true;
238 
239   io_ret = ops->read_is_device_unlocked(ops, &is_device_unlocked);
240   if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
241     return AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
242   } else if (io_ret != AVB_IO_RESULT_OK) {
243     avb_error("Error getting device lock state.\n");
244     return AVB_SLOT_VERIFY_RESULT_ERROR_IO;
245   }
246 
247   if (is_device_unlocked) {
248     avb_debugv(part_name,
249                ": Digest does not exist, device unlocked so not initializing "
250                "digest.\n",
251                NULL);
252     return AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION;
253   }
254 
255   // Device locked; initialize digest with given initial value.
256   avb_debugv(part_name,
257              ": Digest does not exist, initializing persistent digest.\n",
258              NULL);
259   io_ret = ops->write_persistent_value(
260       ops, persistent_value_name, digest_size, initial_digest);
261   if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
262     return AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
263   } else if (io_ret != AVB_IO_RESULT_OK) {
264     avb_errorv(part_name, ": Error initializing persistent digest.\n", NULL);
265     return AVB_SLOT_VERIFY_RESULT_ERROR_IO;
266   }
267 
268   // To ensure that the digest value was written successfully - and avoid a
269   // scenario where the digest is simply 'initialized' on every verify - recurse
270   // into read_persistent_digest to read back the written value. The NULL
271   // initial_digest ensures that this will not recurse again.
272   ret = read_persistent_digest(ops, part_name, digest_size, NULL, out_digest);
273   if (ret != AVB_SLOT_VERIFY_RESULT_OK) {
274     avb_errorv(part_name,
275                ": Reading back initialized persistent digest failed!\n",
276                NULL);
277   }
278   return ret;
279 }
280 
281 static AvbSlotVerifyResult load_and_verify_hash_partition(
282     AvbOps* ops,
283     const char* const* requested_partitions,
284     const char* ab_suffix,
285     bool allow_verification_error,
286     const AvbDescriptor* descriptor,
287     AvbSlotVerifyData* slot_data) {
288   AvbHashDescriptor hash_desc;
289   const uint8_t* desc_partition_name = NULL;
290   const uint8_t* desc_salt;
291   const uint8_t* desc_digest;
292   char part_name[AVB_PART_NAME_MAX_SIZE];
293   AvbSlotVerifyResult ret;
294   AvbIOResult io_ret;
295   uint8_t* image_buf = NULL;
296   bool image_preloaded = false;
297   uint8_t* digest;
298   size_t digest_len;
299   const char* found;
300   uint64_t image_size;
301   size_t expected_digest_len = 0;
302   uint8_t expected_digest_buf[AVB_SHA512_DIGEST_SIZE];
303   const uint8_t* expected_digest = NULL;
304 
305   if (!avb_hash_descriptor_validate_and_byteswap(
306           (const AvbHashDescriptor*)descriptor, &hash_desc)) {
307     ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
308     goto out;
309   }
310 
311   desc_partition_name =
312       ((const uint8_t*)descriptor) + sizeof(AvbHashDescriptor);
313   desc_salt = desc_partition_name + hash_desc.partition_name_len;
314   desc_digest = desc_salt + hash_desc.salt_len;
315 
316   if (!avb_validate_utf8(desc_partition_name, hash_desc.partition_name_len)) {
317     avb_error("Partition name is not valid UTF-8.\n");
318     ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
319     goto out;
320   }
321 
322   /* Don't bother loading or validating unless the partition was
323    * requested in the first place.
324    */
325   found = avb_strv_find_str(requested_partitions,
326                             (const char*)desc_partition_name,
327                             hash_desc.partition_name_len);
328   if (found == NULL) {
329     ret = AVB_SLOT_VERIFY_RESULT_OK;
330     goto out;
331   }
332 
333   if ((hash_desc.flags & AVB_HASH_DESCRIPTOR_FLAGS_DO_NOT_USE_AB) != 0) {
334     /* No ab_suffix, just copy the partition name as is. */
335     if (hash_desc.partition_name_len >= AVB_PART_NAME_MAX_SIZE) {
336       avb_error("Partition name does not fit.\n");
337       ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
338       goto out;
339     }
340     avb_memcpy(part_name, desc_partition_name, hash_desc.partition_name_len);
341     part_name[hash_desc.partition_name_len] = '\0';
342   } else if (hash_desc.digest_len == 0 && avb_strlen(ab_suffix) != 0) {
343     /* No ab_suffix allowed for partitions without a digest in the descriptor
344      * because these partitions hold data unique to this device and are not
345      * updated using an A/B scheme.
346      */
347     avb_error("Cannot use A/B with a persistent digest.\n");
348     ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
349     goto out;
350   } else {
351     /* Add ab_suffix to the partition name. */
352     if (!avb_str_concat(part_name,
353                         sizeof part_name,
354                         (const char*)desc_partition_name,
355                         hash_desc.partition_name_len,
356                         ab_suffix,
357                         avb_strlen(ab_suffix))) {
358       avb_error("Partition name and suffix does not fit.\n");
359       ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
360       goto out;
361     }
362   }
363 
364   /* If we're allowing verification errors then hash_desc.image_size
365    * may no longer match what's in the partition... so in this case
366    * just load the entire partition.
367    *
368    * For example, this can happen if a developer does 'fastboot flash
369    * boot /path/to/new/and/bigger/boot.img'. We want this to work
370    * since it's such a common workflow.
371    */
372   image_size = hash_desc.image_size;
373   if (allow_verification_error) {
374     io_ret = ops->get_size_of_partition(ops, part_name, &image_size);
375     if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
376       ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
377       goto out;
378     } else if (io_ret != AVB_IO_RESULT_OK) {
379       avb_errorv(part_name, ": Error determining partition size.\n", NULL);
380       ret = AVB_SLOT_VERIFY_RESULT_ERROR_IO;
381       goto out;
382     }
383     avb_debugv(part_name, ": Loading entire partition.\n", NULL);
384   }
385 
386   ret = load_full_partition(
387       ops, part_name, image_size, &image_buf, &image_preloaded,
388       allow_verification_error);
389   if (ret != AVB_SLOT_VERIFY_RESULT_OK) {
390     goto out;
391   }
392   // Although only one of the type might be used, we have to defined the
393   // structure here so that they would live outside the 'if/else' scope to be
394   // used later.
395   AvbSHA256Ctx sha256_ctx;
396   AvbSHA512Ctx sha512_ctx;
397   size_t image_size_to_hash = hash_desc.image_size;
398   // If we allow verification error and the whole partition is smaller than
399   // image size in hash descriptor, we just hash the whole partition.
400   if (image_size_to_hash > image_size) {
401     image_size_to_hash = image_size;
402   }
403   if (avb_strcmp((const char*)hash_desc.hash_algorithm, "sha256") == 0) {
404     avb_sha256_init(&sha256_ctx);
405     avb_sha256_update(&sha256_ctx, desc_salt, hash_desc.salt_len);
406     avb_sha256_update(&sha256_ctx, image_buf, image_size_to_hash);
407     digest = avb_sha256_final(&sha256_ctx);
408     digest_len = AVB_SHA256_DIGEST_SIZE;
409   } else if (avb_strcmp((const char*)hash_desc.hash_algorithm, "sha512") == 0) {
410     avb_sha512_init(&sha512_ctx);
411     avb_sha512_update(&sha512_ctx, desc_salt, hash_desc.salt_len);
412     avb_sha512_update(&sha512_ctx, image_buf, image_size_to_hash);
413     digest = avb_sha512_final(&sha512_ctx);
414     digest_len = AVB_SHA512_DIGEST_SIZE;
415   } else {
416     avb_errorv(part_name, ": Unsupported hash algorithm.\n", NULL);
417     ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
418     goto out;
419   }
420 
421   if (hash_desc.digest_len == 0) {
422     /* Expect a match to a persistent digest. */
423     avb_debugv(part_name, ": No digest, using persistent digest.\n", NULL);
424     expected_digest_len = digest_len;
425     expected_digest = expected_digest_buf;
426     avb_assert(expected_digest_len <= sizeof(expected_digest_buf));
427     /* Pass |digest| as the |initial_digest| so devices not yet initialized get
428      * initialized to the current partition digest.
429      */
430     ret = read_persistent_digest(
431         ops, part_name, digest_len, digest, expected_digest_buf);
432     if (ret != AVB_SLOT_VERIFY_RESULT_OK) {
433       goto out;
434     }
435   } else {
436     /* Expect a match to the digest in the descriptor. */
437     expected_digest_len = hash_desc.digest_len;
438     expected_digest = desc_digest;
439   }
440 
441   if (digest_len != expected_digest_len) {
442     avb_errorv(
443         part_name, ": Digest in descriptor not of expected size.\n", NULL);
444     ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
445     goto out;
446   }
447 
448   if (avb_safe_memcmp(digest, expected_digest, digest_len) != 0) {
449     avb_errorv(part_name,
450                ": Hash of data does not match digest in descriptor.\n",
451                NULL);
452     ret = AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION;
453     goto out;
454   }
455 
456   ret = AVB_SLOT_VERIFY_RESULT_OK;
457 
458 out:
459 
460   /* If it worked and something was loaded, copy to slot_data. */
461   if ((ret == AVB_SLOT_VERIFY_RESULT_OK || result_should_continue(ret)) &&
462       image_buf != NULL) {
463     AvbPartitionData* loaded_partition;
464     if (slot_data->num_loaded_partitions == MAX_NUMBER_OF_LOADED_PARTITIONS) {
465       avb_errorv(part_name, ": Too many loaded partitions.\n", NULL);
466       ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
467       goto fail;
468     }
469     loaded_partition =
470         &slot_data->loaded_partitions[slot_data->num_loaded_partitions++];
471     loaded_partition->partition_name = avb_strdup(found);
472     loaded_partition->data_size = image_size;
473     loaded_partition->data = image_buf;
474     loaded_partition->preloaded = image_preloaded;
475     image_buf = NULL;
476   }
477 
478 fail:
479   if (image_buf != NULL && !image_preloaded) {
480     sysmem_free((phys_addr_t)image_buf);
481   }
482   return ret;
483 }
484 
485 static AvbSlotVerifyResult load_requested_partitions(
486     AvbOps* ops,
487     const char* const* requested_partitions,
488     const char* ab_suffix,
489     AvbSlotVerifyData* slot_data) {
490   AvbSlotVerifyResult ret;
491   uint8_t* image_buf = NULL;
492   bool image_preloaded = false;
493   size_t n;
494 
495   for (n = 0; requested_partitions[n] != NULL; n++) {
496     char part_name[AVB_PART_NAME_MAX_SIZE];
497     AvbIOResult io_ret;
498     uint64_t image_size;
499     AvbPartitionData* loaded_partition;
500 
501     if (!avb_str_concat(part_name,
502                         sizeof part_name,
503                         requested_partitions[n],
504                         avb_strlen(requested_partitions[n]),
505                         ab_suffix,
506                         avb_strlen(ab_suffix))) {
507       avb_error("Partition name and suffix does not fit.\n");
508       ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
509       goto out;
510     }
511 
512     io_ret = ops->get_size_of_partition(ops, part_name, &image_size);
513     if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
514       ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
515       goto out;
516     } else if (io_ret != AVB_IO_RESULT_OK) {
517       avb_errorv(part_name, ": Error determining partition size.\n", NULL);
518       ret = AVB_SLOT_VERIFY_RESULT_ERROR_IO;
519       goto out;
520     }
521     avb_debugv(part_name, ": Loading entire partition.\n", NULL);
522 
523     ret = load_full_partition(
524         ops, part_name, image_size, &image_buf, &image_preloaded, 1);
525     if (ret != AVB_SLOT_VERIFY_RESULT_OK) {
526       goto out;
527     }
528 
529     /* Move to slot_data. */
530     if (slot_data->num_loaded_partitions == MAX_NUMBER_OF_LOADED_PARTITIONS) {
531       avb_errorv(part_name, ": Too many loaded partitions.\n", NULL);
532       ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
533       goto out;
534     }
535     loaded_partition =
536         &slot_data->loaded_partitions[slot_data->num_loaded_partitions++];
537     loaded_partition->partition_name = avb_strdup(requested_partitions[n]);
538     if (loaded_partition->partition_name == NULL) {
539       ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
540       goto out;
541     }
542     loaded_partition->data_size = image_size;
543     loaded_partition->data = image_buf; /* Transferring the owner. */
544     loaded_partition->preloaded = image_preloaded;
545     image_buf = NULL;
546     image_preloaded = false;
547   }
548 
549   ret = AVB_SLOT_VERIFY_RESULT_OK;
550 
551 out:
552   /* Free the current buffer if any. */
553   if (image_buf != NULL && !image_preloaded) {
554     sysmem_free((phys_addr_t)image_buf);
555   }
556   /* Buffers that are already saved in slot_data will be handled by the caller
557    * even on failure. */
558   return ret;
559 }
560 
561 static AvbSlotVerifyResult load_and_verify_vbmeta(
562     AvbOps* ops,
563     const char* const* requested_partitions,
564     const char* ab_suffix,
565     AvbSlotVerifyFlags flags,
566     bool allow_verification_error,
567     AvbVBMetaImageFlags toplevel_vbmeta_flags,
568     int rollback_index_location,
569     const char* partition_name,
570     size_t partition_name_len,
571     const uint8_t* expected_public_key,
572     size_t expected_public_key_length,
573     AvbSlotVerifyData* slot_data,
574     AvbAlgorithmType* out_algorithm_type,
575     AvbCmdlineSubstList* out_additional_cmdline_subst) {
576   char full_partition_name[AVB_PART_NAME_MAX_SIZE];
577   AvbSlotVerifyResult ret;
578   AvbIOResult io_ret;
579   uint64_t vbmeta_offset;
580   size_t vbmeta_size;
581   uint8_t* vbmeta_buf = NULL;
582   size_t vbmeta_num_read;
583   AvbVBMetaVerifyResult vbmeta_ret;
584   const uint8_t* pk_data;
585   size_t pk_len;
586   AvbVBMetaImageHeader vbmeta_header;
587   uint64_t stored_rollback_index;
588   const AvbDescriptor** descriptors = NULL;
589   size_t num_descriptors;
590   size_t n;
591   bool is_main_vbmeta;
592   bool look_for_vbmeta_footer;
593   AvbVBMetaData* vbmeta_image_data = NULL;
594 
595   ret = AVB_SLOT_VERIFY_RESULT_OK;
596 
597   avb_assert(slot_data != NULL);
598 
599   /* Since we allow top-level vbmeta in 'boot', use
600    * rollback_index_location to determine whether we're the main
601    * vbmeta struct.
602    */
603   is_main_vbmeta = false;
604   if (rollback_index_location == 0) {
605     if ((flags & AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION) == 0) {
606       is_main_vbmeta = true;
607     }
608   }
609 
610   /* Don't use footers for vbmeta partitions ('vbmeta' or
611    * 'vbmeta_<partition_name>').
612    */
613   look_for_vbmeta_footer = true;
614   if (avb_strncmp(partition_name, "vbmeta", avb_strlen("vbmeta")) == 0) {
615     look_for_vbmeta_footer = false;
616   }
617 
618   if (!avb_validate_utf8((const uint8_t*)partition_name, partition_name_len)) {
619     avb_error("Partition name is not valid UTF-8.\n");
620     ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
621     goto out;
622   }
623 
624   /* Construct full partition name e.g. system_a. */
625   if (!avb_str_concat(full_partition_name,
626                       sizeof full_partition_name,
627                       partition_name,
628                       partition_name_len,
629                       ab_suffix,
630                       avb_strlen(ab_suffix))) {
631     avb_error("Partition name and suffix does not fit.\n");
632     ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
633     goto out;
634   }
635 
636   /* If we're loading from the main vbmeta partition, the vbmeta struct is in
637    * the beginning. Otherwise we may have to locate it via a footer... if no
638    * footer is found, we look in the beginning to support e.g. vbmeta_<org>
639    * partitions holding data for e.g. super partitions (b/80195851 for
640    * rationale).
641    */
642   vbmeta_offset = 0;
643   vbmeta_size = VBMETA_MAX_SIZE;
644   if (look_for_vbmeta_footer) {
645     uint8_t footer_buf[AVB_FOOTER_SIZE];
646     size_t footer_num_read;
647     AvbFooter footer;
648 
649     io_ret = ops->read_from_partition(ops,
650                                       full_partition_name,
651                                       -AVB_FOOTER_SIZE,
652                                       AVB_FOOTER_SIZE,
653                                       footer_buf,
654                                       &footer_num_read);
655     if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
656       ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
657       goto out;
658     } else if (io_ret != AVB_IO_RESULT_OK) {
659       avb_errorv(full_partition_name, ": Error loading footer.\n", NULL);
660       ret = AVB_SLOT_VERIFY_RESULT_ERROR_IO;
661       goto out;
662     }
663     avb_assert(footer_num_read == AVB_FOOTER_SIZE);
664 
665     if (!avb_footer_validate_and_byteswap((const AvbFooter*)footer_buf,
666                                           &footer)) {
667       avb_debugv(full_partition_name, ": No footer detected.\n", NULL);
668     } else {
669       /* Basic footer sanity check since the data is untrusted. */
670       if (footer.vbmeta_size > VBMETA_MAX_SIZE) {
671         avb_errorv(
672             full_partition_name, ": Invalid vbmeta size in footer.\n", NULL);
673       } else {
674         vbmeta_offset = footer.vbmeta_offset;
675         vbmeta_size = footer.vbmeta_size;
676       }
677     }
678   }
679 
680   vbmeta_buf = avb_malloc(vbmeta_size);
681   if (vbmeta_buf == NULL) {
682     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
683     goto out;
684   }
685 
686   if (vbmeta_offset != 0) {
687     avb_debugv("Loading vbmeta struct in footer from partition '",
688                full_partition_name,
689                "'.\n",
690                NULL);
691   } else {
692     avb_debugv("Loading vbmeta struct from partition '",
693                full_partition_name,
694                "'.\n",
695                NULL);
696   }
697 
698   io_ret = ops->read_from_partition(ops,
699                                     full_partition_name,
700                                     vbmeta_offset,
701                                     vbmeta_size,
702                                     vbmeta_buf,
703                                     &vbmeta_num_read);
704   if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
705     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
706     goto out;
707   } else if (io_ret != AVB_IO_RESULT_OK) {
708     /* If we're looking for 'vbmeta' but there is no such partition,
709      * go try to get it from the boot partition instead.
710      */
711     if (is_main_vbmeta && io_ret == AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION &&
712         !look_for_vbmeta_footer) {
713       avb_debugv(full_partition_name,
714                  ": No such partition. Trying 'boot' instead.\n",
715                  NULL);
716       ret = load_and_verify_vbmeta(ops,
717                                    requested_partitions,
718                                    ab_suffix,
719                                    flags,
720                                    allow_verification_error,
721                                    0 /* toplevel_vbmeta_flags */,
722                                    0 /* rollback_index_location */,
723                                    "boot",
724                                    avb_strlen("boot"),
725                                    NULL /* expected_public_key */,
726                                    0 /* expected_public_key_length */,
727                                    slot_data,
728                                    out_algorithm_type,
729                                    out_additional_cmdline_subst);
730       goto out;
731     } else {
732       avb_errorv(full_partition_name, ": Error loading vbmeta data.\n", NULL);
733       ret = AVB_SLOT_VERIFY_RESULT_ERROR_IO;
734       goto out;
735     }
736   }
737   avb_assert(vbmeta_num_read <= vbmeta_size);
738 
739   /* Check if the image is properly signed and get the public key used
740    * to sign the image.
741    */
742   vbmeta_ret =
743       avb_vbmeta_image_verify(vbmeta_buf, vbmeta_num_read, &pk_data, &pk_len);
744   switch (vbmeta_ret) {
745     case AVB_VBMETA_VERIFY_RESULT_OK:
746       avb_assert(pk_data != NULL && pk_len > 0);
747       break;
748 
749     case AVB_VBMETA_VERIFY_RESULT_OK_NOT_SIGNED:
750     case AVB_VBMETA_VERIFY_RESULT_HASH_MISMATCH:
751     case AVB_VBMETA_VERIFY_RESULT_SIGNATURE_MISMATCH:
752       ret = AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION;
753       avb_errorv(full_partition_name,
754                  ": Error verifying vbmeta image: ",
755                  avb_vbmeta_verify_result_to_string(vbmeta_ret),
756                  "\n",
757                  NULL);
758       if (!allow_verification_error) {
759         goto out;
760       }
761       break;
762 
763     case AVB_VBMETA_VERIFY_RESULT_INVALID_VBMETA_HEADER:
764       /* No way to continue this case. */
765       ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
766       avb_errorv(full_partition_name,
767                  ": Error verifying vbmeta image: invalid vbmeta header\n",
768                  NULL);
769       goto out;
770 
771     case AVB_VBMETA_VERIFY_RESULT_UNSUPPORTED_VERSION:
772       /* No way to continue this case. */
773       ret = AVB_SLOT_VERIFY_RESULT_ERROR_UNSUPPORTED_VERSION;
774       avb_errorv(full_partition_name,
775                  ": Error verifying vbmeta image: unsupported AVB version\n",
776                  NULL);
777       goto out;
778   }
779 
780   /* Byteswap the header. */
781   avb_vbmeta_image_header_to_host_byte_order((AvbVBMetaImageHeader*)vbmeta_buf,
782                                              &vbmeta_header);
783 
784   /* If we're the toplevel, assign flags so they'll be passed down. */
785   if (is_main_vbmeta) {
786     toplevel_vbmeta_flags = (AvbVBMetaImageFlags)vbmeta_header.flags;
787   } else {
788     if (vbmeta_header.flags != 0) {
789       ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
790       avb_errorv(full_partition_name,
791                  ": chained vbmeta image has non-zero flags\n",
792                  NULL);
793       goto out;
794     }
795   }
796 
797   uint32_t rollback_index_location_to_use = rollback_index_location;
798 
799   /* Check if key used to make signature matches what is expected. */
800   if (pk_data != NULL) {
801     if (expected_public_key != NULL) {
802       avb_assert(!is_main_vbmeta);
803       if (expected_public_key_length != pk_len ||
804           avb_safe_memcmp(expected_public_key, pk_data, pk_len) != 0) {
805         avb_errorv(full_partition_name,
806                    ": Public key used to sign data does not match key in chain "
807                    "partition descriptor.\n",
808                    NULL);
809         ret = AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED;
810         if (!allow_verification_error) {
811           goto out;
812         }
813       }
814     } else {
815       bool key_is_trusted = false;
816       const uint8_t* pk_metadata = NULL;
817       size_t pk_metadata_len = 0;
818 
819       if (vbmeta_header.public_key_metadata_size > 0) {
820         pk_metadata = vbmeta_buf + sizeof(AvbVBMetaImageHeader) +
821                       vbmeta_header.authentication_data_block_size +
822                       vbmeta_header.public_key_metadata_offset;
823         pk_metadata_len = vbmeta_header.public_key_metadata_size;
824       }
825 
826       // If we're not using a vbmeta partition, need to use another AvbOps...
827       if (flags & AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION) {
828         io_ret = ops->validate_public_key_for_partition(
829             ops,
830             full_partition_name,
831             pk_data,
832             pk_len,
833             pk_metadata,
834             pk_metadata_len,
835             &key_is_trusted,
836             &rollback_index_location_to_use);
837       } else {
838         avb_assert(is_main_vbmeta);
839         io_ret = ops->validate_vbmeta_public_key(ops,
840                                                  pk_data,
841                                                  pk_len,
842                                                  pk_metadata,
843                                                  pk_metadata_len,
844                                                  &key_is_trusted);
845       }
846 
847       if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
848         ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
849         goto out;
850       } else if (io_ret != AVB_IO_RESULT_OK) {
851         avb_errorv(full_partition_name,
852                    ": Error while checking public key used to sign data.\n",
853                    NULL);
854         ret = AVB_SLOT_VERIFY_RESULT_ERROR_IO;
855         goto out;
856       }
857       if (!key_is_trusted) {
858         avb_errorv(full_partition_name,
859                    ": Public key used to sign data rejected.\n",
860                    NULL);
861         ret = AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED;
862         if (!allow_verification_error) {
863           goto out;
864         }
865       }
866     }
867   }
868 
869   /* Check rollback index. */
870   io_ret = ops->read_rollback_index(
871       ops, rollback_index_location_to_use, &stored_rollback_index);
872   if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
873     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
874     goto out;
875   } else if (io_ret != AVB_IO_RESULT_OK) {
876     avb_errorv(full_partition_name,
877                ": Error getting rollback index for location.\n",
878                NULL);
879     ret = AVB_SLOT_VERIFY_RESULT_ERROR_IO;
880     goto out;
881   }
882   if (vbmeta_header.rollback_index < stored_rollback_index) {
883     avb_errorv(
884         full_partition_name,
885         ": Image rollback index is less than the stored rollback index.\n",
886         NULL);
887     ret = AVB_SLOT_VERIFY_RESULT_ERROR_ROLLBACK_INDEX;
888     if (!allow_verification_error) {
889       goto out;
890     }
891   }
892 
893   /* Copy vbmeta to vbmeta_images before recursing. */
894   if (is_main_vbmeta) {
895     avb_assert(slot_data->num_vbmeta_images == 0);
896   } else {
897     if (!(flags & AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION)) {
898       avb_assert(slot_data->num_vbmeta_images > 0);
899     }
900   }
901   if (slot_data->num_vbmeta_images == MAX_NUMBER_OF_VBMETA_IMAGES) {
902     avb_errorv(full_partition_name, ": Too many vbmeta images.\n", NULL);
903     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
904     goto out;
905   }
906   vbmeta_image_data = &slot_data->vbmeta_images[slot_data->num_vbmeta_images++];
907   vbmeta_image_data->partition_name = avb_strdup(partition_name);
908   vbmeta_image_data->vbmeta_data = vbmeta_buf;
909   /* Note that |vbmeta_buf| is actually |vbmeta_num_read| bytes long
910    * and this includes data past the end of the image. Pass the
911    * actual size of the vbmeta image. Also, no need to use
912    * avb_safe_add() since the header has already been verified.
913    */
914   vbmeta_image_data->vbmeta_size =
915       sizeof(AvbVBMetaImageHeader) +
916       vbmeta_header.authentication_data_block_size +
917       vbmeta_header.auxiliary_data_block_size;
918   vbmeta_image_data->verify_result = vbmeta_ret;
919 
920   /* If verification has been disabled by setting a bit in the image,
921    * we're done... except that we need to load the entirety of the
922    * requested partitions.
923    */
924   if (vbmeta_header.flags & AVB_VBMETA_IMAGE_FLAGS_VERIFICATION_DISABLED) {
925     AvbSlotVerifyResult sub_ret;
926     avb_debugv(
927         full_partition_name, ": VERIFICATION_DISABLED bit is set.\n", NULL);
928     /* If load_requested_partitions() fail it is always a fatal
929      * failure (e.g. ERROR_INVALID_ARGUMENT, ERROR_OOM, etc.) rather
930      * than recoverable (e.g. one where result_should_continue()
931      * returns true) and we want to convey that error.
932      */
933     sub_ret = load_requested_partitions(
934         ops, requested_partitions, ab_suffix, slot_data);
935     if (sub_ret != AVB_SLOT_VERIFY_RESULT_OK) {
936       ret = sub_ret;
937     }
938     goto out;
939   }
940 
941   /* Now go through all descriptors and take the appropriate action:
942    *
943    * - hash descriptor: Load data from partition, calculate hash, and
944    *   checks that it matches what's in the hash descriptor.
945    *
946    * - hashtree descriptor: Do nothing since verification happens
947    *   on-the-fly from within the OS. (Unless the descriptor uses a
948    *   persistent digest, in which case we need to find it).
949    *
950    * - chained partition descriptor: Load the footer, load the vbmeta
951    *   image, verify vbmeta image (includes rollback checks, hash
952    *   checks, bail on chained partitions).
953    */
954   descriptors =
955       avb_descriptor_get_all(vbmeta_buf, vbmeta_num_read, &num_descriptors);
956   for (n = 0; n < num_descriptors; n++) {
957     AvbDescriptor desc;
958 
959     if (!avb_descriptor_validate_and_byteswap(descriptors[n], &desc)) {
960       avb_errorv(full_partition_name, ": Descriptor is invalid.\n", NULL);
961       ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
962       goto out;
963     }
964 
965     switch (desc.tag) {
966       case AVB_DESCRIPTOR_TAG_HASH: {
967         AvbSlotVerifyResult sub_ret;
968         sub_ret = load_and_verify_hash_partition(ops,
969                                                  requested_partitions,
970                                                  ab_suffix,
971                                                  allow_verification_error,
972                                                  descriptors[n],
973                                                  slot_data);
974         if (sub_ret != AVB_SLOT_VERIFY_RESULT_OK) {
975           ret = sub_ret;
976           if (!allow_verification_error || !result_should_continue(ret)) {
977             goto out;
978           }
979         }
980       } break;
981 
982       case AVB_DESCRIPTOR_TAG_CHAIN_PARTITION: {
983         AvbSlotVerifyResult sub_ret;
984         AvbChainPartitionDescriptor chain_desc;
985         const uint8_t* chain_partition_name;
986         const uint8_t* chain_public_key;
987 
988         /* Only allow CHAIN_PARTITION descriptors in the main vbmeta image. */
989         if (!is_main_vbmeta) {
990           avb_errorv(full_partition_name,
991                      ": Encountered chain descriptor not in main image.\n",
992                      NULL);
993           ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
994           goto out;
995         }
996 
997         if (!avb_chain_partition_descriptor_validate_and_byteswap(
998                 (AvbChainPartitionDescriptor*)descriptors[n], &chain_desc)) {
999           avb_errorv(full_partition_name,
1000                      ": Chain partition descriptor is invalid.\n",
1001                      NULL);
1002           ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1003           goto out;
1004         }
1005 
1006         if (chain_desc.rollback_index_location == 0) {
1007           avb_errorv(full_partition_name,
1008                      ": Chain partition has invalid "
1009                      "rollback_index_location field.\n",
1010                      NULL);
1011           ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1012           goto out;
1013         }
1014 
1015         chain_partition_name = ((const uint8_t*)descriptors[n]) +
1016                                sizeof(AvbChainPartitionDescriptor);
1017         chain_public_key = chain_partition_name + chain_desc.partition_name_len;
1018 
1019         sub_ret =
1020             load_and_verify_vbmeta(ops,
1021                                    requested_partitions,
1022                                    ab_suffix,
1023                                    flags,
1024                                    allow_verification_error,
1025                                    toplevel_vbmeta_flags,
1026                                    chain_desc.rollback_index_location,
1027                                    (const char*)chain_partition_name,
1028                                    chain_desc.partition_name_len,
1029                                    chain_public_key,
1030                                    chain_desc.public_key_len,
1031                                    slot_data,
1032                                    NULL, /* out_algorithm_type */
1033                                    NULL /* out_additional_cmdline_subst */);
1034         if (sub_ret != AVB_SLOT_VERIFY_RESULT_OK) {
1035           ret = sub_ret;
1036           if (!result_should_continue(ret)) {
1037             goto out;
1038           }
1039         }
1040       } break;
1041 
1042       case AVB_DESCRIPTOR_TAG_KERNEL_CMDLINE: {
1043         const uint8_t* kernel_cmdline;
1044         AvbKernelCmdlineDescriptor kernel_cmdline_desc;
1045         bool apply_cmdline;
1046 
1047         if (!avb_kernel_cmdline_descriptor_validate_and_byteswap(
1048                 (AvbKernelCmdlineDescriptor*)descriptors[n],
1049                 &kernel_cmdline_desc)) {
1050           avb_errorv(full_partition_name,
1051                      ": Kernel cmdline descriptor is invalid.\n",
1052                      NULL);
1053           ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1054           goto out;
1055         }
1056 
1057         kernel_cmdline = ((const uint8_t*)descriptors[n]) +
1058                          sizeof(AvbKernelCmdlineDescriptor);
1059 
1060         if (!avb_validate_utf8(kernel_cmdline,
1061                                kernel_cmdline_desc.kernel_cmdline_length)) {
1062           avb_errorv(full_partition_name,
1063                      ": Kernel cmdline is not valid UTF-8.\n",
1064                      NULL);
1065           ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1066           goto out;
1067         }
1068 
1069         /* Compare the flags for top-level VBMeta struct with flags in
1070          * the command-line descriptor so command-line snippets only
1071          * intended for a certain mode (dm-verity enabled/disabled)
1072          * are skipped if applicable.
1073          */
1074         apply_cmdline = true;
1075         if (toplevel_vbmeta_flags & AVB_VBMETA_IMAGE_FLAGS_HASHTREE_DISABLED) {
1076           if (kernel_cmdline_desc.flags &
1077               AVB_KERNEL_CMDLINE_FLAGS_USE_ONLY_IF_HASHTREE_NOT_DISABLED) {
1078             apply_cmdline = false;
1079           }
1080         } else {
1081           if (kernel_cmdline_desc.flags &
1082               AVB_KERNEL_CMDLINE_FLAGS_USE_ONLY_IF_HASHTREE_DISABLED) {
1083             apply_cmdline = false;
1084           }
1085         }
1086 
1087         if (apply_cmdline) {
1088           if (slot_data->cmdline == NULL) {
1089             slot_data->cmdline =
1090                 avb_calloc(kernel_cmdline_desc.kernel_cmdline_length + 1);
1091             if (slot_data->cmdline == NULL) {
1092               ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1093               goto out;
1094             }
1095             avb_memcpy(slot_data->cmdline,
1096                        kernel_cmdline,
1097                        kernel_cmdline_desc.kernel_cmdline_length);
1098           } else {
1099             /* new cmdline is: <existing_cmdline> + ' ' + <newcmdline> + '\0' */
1100             size_t orig_size = avb_strlen(slot_data->cmdline);
1101             size_t new_size =
1102                 orig_size + 1 + kernel_cmdline_desc.kernel_cmdline_length + 1;
1103             char* new_cmdline = avb_calloc(new_size);
1104             if (new_cmdline == NULL) {
1105               ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1106               goto out;
1107             }
1108             avb_memcpy(new_cmdline, slot_data->cmdline, orig_size);
1109             new_cmdline[orig_size] = ' ';
1110             avb_memcpy(new_cmdline + orig_size + 1,
1111                        kernel_cmdline,
1112                        kernel_cmdline_desc.kernel_cmdline_length);
1113             avb_free(slot_data->cmdline);
1114             slot_data->cmdline = new_cmdline;
1115           }
1116         }
1117       } break;
1118 
1119       case AVB_DESCRIPTOR_TAG_HASHTREE: {
1120         AvbHashtreeDescriptor hashtree_desc;
1121 
1122         if (!avb_hashtree_descriptor_validate_and_byteswap(
1123                 (AvbHashtreeDescriptor*)descriptors[n], &hashtree_desc)) {
1124           avb_errorv(
1125               full_partition_name, ": Hashtree descriptor is invalid.\n", NULL);
1126           ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1127           goto out;
1128         }
1129 
1130         /* We only need to continue when there is no digest in the descriptor.
1131          * This is because the only processing here is to find the digest and
1132          * make it available on the kernel command line.
1133          */
1134         if (hashtree_desc.root_digest_len == 0) {
1135           char part_name[AVB_PART_NAME_MAX_SIZE];
1136           size_t digest_len = 0;
1137           uint8_t digest_buf[AVB_SHA512_DIGEST_SIZE];
1138           const uint8_t* desc_partition_name =
1139               ((const uint8_t*)descriptors[n]) + sizeof(AvbHashtreeDescriptor);
1140 
1141           if (!avb_validate_utf8(desc_partition_name,
1142                                  hashtree_desc.partition_name_len)) {
1143             avb_error("Partition name is not valid UTF-8.\n");
1144             ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1145             goto out;
1146           }
1147 
1148           /* No ab_suffix for partitions without a digest in the descriptor
1149            * because these partitions hold data unique to this device and are
1150            * not updated using an A/B scheme.
1151            */
1152           if ((hashtree_desc.flags &
1153                AVB_HASHTREE_DESCRIPTOR_FLAGS_DO_NOT_USE_AB) == 0 &&
1154               avb_strlen(ab_suffix) != 0) {
1155             avb_error("Cannot use A/B with a persistent root digest.\n");
1156             ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1157             goto out;
1158           }
1159           if (hashtree_desc.partition_name_len >= AVB_PART_NAME_MAX_SIZE) {
1160             avb_error("Partition name does not fit.\n");
1161             ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1162             goto out;
1163           }
1164           avb_memcpy(
1165               part_name, desc_partition_name, hashtree_desc.partition_name_len);
1166           part_name[hashtree_desc.partition_name_len] = '\0';
1167 
1168           /* Determine the expected digest size from the hash algorithm. */
1169           if (avb_strcmp((const char*)hashtree_desc.hash_algorithm, "sha1") ==
1170               0) {
1171             digest_len = AVB_SHA1_DIGEST_SIZE;
1172           } else if (avb_strcmp((const char*)hashtree_desc.hash_algorithm,
1173                                 "sha256") == 0) {
1174             digest_len = AVB_SHA256_DIGEST_SIZE;
1175           } else if (avb_strcmp((const char*)hashtree_desc.hash_algorithm,
1176                                 "sha512") == 0) {
1177             digest_len = AVB_SHA512_DIGEST_SIZE;
1178           } else {
1179             avb_errorv(part_name, ": Unsupported hash algorithm.\n", NULL);
1180             ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1181             goto out;
1182           }
1183 
1184           ret = read_persistent_digest(ops,
1185                                        part_name,
1186                                        digest_len,
1187                                        NULL /* initial_digest */,
1188                                        digest_buf);
1189           if (ret != AVB_SLOT_VERIFY_RESULT_OK) {
1190             goto out;
1191           }
1192 
1193           if (out_additional_cmdline_subst) {
1194             ret =
1195                 avb_add_root_digest_substitution(part_name,
1196                                                  digest_buf,
1197                                                  digest_len,
1198                                                  out_additional_cmdline_subst);
1199             if (ret != AVB_SLOT_VERIFY_RESULT_OK) {
1200               goto out;
1201             }
1202           }
1203         }
1204       } break;
1205 
1206       case AVB_DESCRIPTOR_TAG_PROPERTY:
1207         /* Do nothing. */
1208         break;
1209     }
1210   }
1211 
1212   if (rollback_index_location < 0 ||
1213       rollback_index_location >= AVB_MAX_NUMBER_OF_ROLLBACK_INDEX_LOCATIONS) {
1214     avb_errorv(
1215         full_partition_name, ": Invalid rollback_index_location.\n", NULL);
1216     ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1217     goto out;
1218   }
1219 
1220   slot_data->rollback_indexes[rollback_index_location] =
1221       vbmeta_header.rollback_index;
1222 
1223   if (out_algorithm_type != NULL) {
1224     *out_algorithm_type = (AvbAlgorithmType)vbmeta_header.algorithm_type;
1225   }
1226 
1227 out:
1228   /* If |vbmeta_image_data| isn't NULL it means that it adopted
1229    * |vbmeta_buf| so in that case don't free it here.
1230    */
1231   if (vbmeta_image_data == NULL) {
1232     if (vbmeta_buf != NULL) {
1233       avb_free(vbmeta_buf);
1234     }
1235   }
1236   if (descriptors != NULL) {
1237     avb_free(descriptors);
1238   }
1239   return ret;
1240 }
1241 
1242 static AvbIOResult avb_manage_hashtree_error_mode(
1243     AvbOps* ops,
1244     AvbSlotVerifyFlags flags,
1245     AvbSlotVerifyData* data,
1246     AvbHashtreeErrorMode* out_hashtree_error_mode) {
1247   AvbHashtreeErrorMode ret = AVB_HASHTREE_ERROR_MODE_RESTART;
1248   AvbIOResult io_ret = AVB_IO_RESULT_OK;
1249   uint8_t vbmeta_digest_sha256[AVB_SHA256_DIGEST_SIZE];
1250   uint8_t stored_vbmeta_digest_sha256[AVB_SHA256_DIGEST_SIZE];
1251   size_t num_bytes_read;
1252 
1253   avb_assert(out_hashtree_error_mode != NULL);
1254   avb_assert(ops->read_persistent_value != NULL);
1255   avb_assert(ops->write_persistent_value != NULL);
1256 
1257   // If we're rebooting because of dm-verity corruption, make a note of
1258   // the vbmeta hash so we can stay in 'eio' mode until things change.
1259   if (flags & AVB_SLOT_VERIFY_FLAGS_RESTART_CAUSED_BY_HASHTREE_CORRUPTION) {
1260     avb_debug(
1261         "Rebooting because of dm-verity corruption - "
1262         "recording OS instance and using 'eio' mode.\n");
1263     avb_slot_verify_data_calculate_vbmeta_digest(
1264         data, AVB_DIGEST_TYPE_SHA256, vbmeta_digest_sha256);
1265     io_ret = ops->write_persistent_value(ops,
1266                                          AVB_NPV_MANAGED_VERITY_MODE,
1267                                          AVB_SHA256_DIGEST_SIZE,
1268                                          vbmeta_digest_sha256);
1269     if (io_ret != AVB_IO_RESULT_OK) {
1270       avb_error("Error writing to " AVB_NPV_MANAGED_VERITY_MODE ".\n");
1271       goto out;
1272     }
1273     ret = AVB_HASHTREE_ERROR_MODE_EIO;
1274     io_ret = AVB_IO_RESULT_OK;
1275     goto out;
1276   }
1277 
1278   // See if we're in 'eio' mode.
1279   io_ret = ops->read_persistent_value(ops,
1280                                       AVB_NPV_MANAGED_VERITY_MODE,
1281                                       AVB_SHA256_DIGEST_SIZE,
1282                                       stored_vbmeta_digest_sha256,
1283                                       &num_bytes_read);
1284   if (io_ret == AVB_IO_RESULT_ERROR_NO_SUCH_VALUE ||
1285       (io_ret == AVB_IO_RESULT_OK && num_bytes_read == 0)) {
1286     // This is the usual case ('eio' mode not set).
1287     avb_debug("No dm-verity corruption - using in 'restart' mode.\n");
1288     ret = AVB_HASHTREE_ERROR_MODE_RESTART;
1289     io_ret = AVB_IO_RESULT_OK;
1290     goto out;
1291   } else if (io_ret != AVB_IO_RESULT_OK) {
1292     avb_error("Error reading from " AVB_NPV_MANAGED_VERITY_MODE ".\n");
1293     goto out;
1294   }
1295   if (num_bytes_read != AVB_SHA256_DIGEST_SIZE) {
1296     avb_error(
1297         "Unexpected number of bytes read from " AVB_NPV_MANAGED_VERITY_MODE
1298         ".\n");
1299     io_ret = AVB_IO_RESULT_ERROR_IO;
1300     goto out;
1301   }
1302 
1303   // OK, so we're currently in 'eio' mode and the vbmeta digest of the OS
1304   // that caused this is in |stored_vbmeta_digest_sha256| ... now see if
1305   // the OS we're dealing with now is the same.
1306   avb_slot_verify_data_calculate_vbmeta_digest(
1307       data, AVB_DIGEST_TYPE_SHA256, vbmeta_digest_sha256);
1308   if (avb_memcmp(vbmeta_digest_sha256,
1309                  stored_vbmeta_digest_sha256,
1310                  AVB_SHA256_DIGEST_SIZE) == 0) {
1311     // It's the same so we're still in 'eio' mode.
1312     avb_debug("Same OS instance detected - staying in 'eio' mode.\n");
1313     ret = AVB_HASHTREE_ERROR_MODE_EIO;
1314     io_ret = AVB_IO_RESULT_OK;
1315   } else {
1316     // It did change!
1317     avb_debug(
1318         "New OS instance detected - changing from 'eio' to 'restart' mode.\n");
1319     io_ret =
1320         ops->write_persistent_value(ops,
1321                                     AVB_NPV_MANAGED_VERITY_MODE,
1322                                     0,  // This clears the persistent property.
1323                                     vbmeta_digest_sha256);
1324     if (io_ret != AVB_IO_RESULT_OK) {
1325       avb_error("Error clearing " AVB_NPV_MANAGED_VERITY_MODE ".\n");
1326       goto out;
1327     }
1328     ret = AVB_HASHTREE_ERROR_MODE_RESTART;
1329     io_ret = AVB_IO_RESULT_OK;
1330   }
1331 
1332 out:
1333   *out_hashtree_error_mode = ret;
1334   return io_ret;
1335 }
1336 
1337 static bool has_system_partition(AvbOps* ops, const char* ab_suffix) {
1338   char part_name[AVB_PART_NAME_MAX_SIZE];
1339   char* system_part_name = "system";
1340   char guid_buf[37];
1341   AvbIOResult io_ret;
1342 
1343   if (!avb_str_concat(part_name,
1344                       sizeof part_name,
1345                       system_part_name,
1346                       avb_strlen(system_part_name),
1347                       ab_suffix,
1348                       avb_strlen(ab_suffix))) {
1349     avb_error("System partition name and suffix does not fit.\n");
1350     return false;
1351   }
1352 
1353   io_ret = ops->get_unique_guid_for_partition(
1354       ops, part_name, guid_buf, sizeof guid_buf);
1355   if (io_ret == AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION) {
1356     avb_debug("No system partition.\n");
1357     return false;
1358   } else if (io_ret != AVB_IO_RESULT_OK) {
1359     avb_error("Error getting unique GUID for system partition.\n");
1360     return false;
1361   }
1362 
1363   return true;
1364 }
1365 
1366 AvbSlotVerifyResult avb_slot_verify(AvbOps* ops,
1367                                     const char* const* requested_partitions,
1368                                     const char* ab_suffix,
1369                                     AvbSlotVerifyFlags flags,
1370                                     AvbHashtreeErrorMode hashtree_error_mode,
1371                                     AvbSlotVerifyData** out_data) {
1372   AvbSlotVerifyResult ret = 0;
1373   AvbSlotVerifyData* slot_data = NULL;
1374   AvbAlgorithmType algorithm_type = AVB_ALGORITHM_TYPE_NONE;
1375   bool using_boot_for_vbmeta = false;
1376   AvbVBMetaImageHeader toplevel_vbmeta;
1377   bool allow_verification_error =
1378       (flags & AVB_SLOT_VERIFY_FLAGS_ALLOW_VERIFICATION_ERROR);
1379   AvbCmdlineSubstList* additional_cmdline_subst = NULL;
1380 
1381   /* Fail early if we're missing the AvbOps needed for slot verification. */
1382   avb_assert(ops->read_is_device_unlocked != NULL);
1383   avb_assert(ops->read_from_partition != NULL);
1384   avb_assert(ops->get_size_of_partition != NULL);
1385   avb_assert(ops->read_rollback_index != NULL);
1386   avb_assert(ops->get_unique_guid_for_partition != NULL);
1387 
1388   if (out_data != NULL) {
1389     *out_data = NULL;
1390   }
1391 
1392   /* Allowing dm-verity errors defeats the purpose of verified boot so
1393    * only allow this if set up to allow verification errors
1394    * (e.g. typically only UNLOCKED mode).
1395    */
1396   if (hashtree_error_mode == AVB_HASHTREE_ERROR_MODE_LOGGING &&
1397       !allow_verification_error) {
1398     ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT;
1399     goto fail;
1400   }
1401 
1402   /* Make sure passed-in AvbOps support persistent values if
1403    * asking for libavb to manage verity state.
1404    */
1405   if (hashtree_error_mode == AVB_HASHTREE_ERROR_MODE_MANAGED_RESTART_AND_EIO) {
1406     if (ops->read_persistent_value == NULL ||
1407         ops->write_persistent_value == NULL) {
1408       avb_error(
1409           "Persistent values required for "
1410           "AVB_HASHTREE_ERROR_MODE_MANAGED_RESTART_AND_EIO "
1411           "but are not implemented in given AvbOps.\n");
1412       ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT;
1413       goto fail;
1414     }
1415   }
1416 
1417   /* Make sure passed-in AvbOps support verifying public keys and getting
1418    * rollback index location if not using a vbmeta partition.
1419    */
1420   if (flags & AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION) {
1421     if (ops->validate_public_key_for_partition == NULL) {
1422       avb_error(
1423           "AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION was passed but the "
1424           "validate_public_key_for_partition() operation isn't implemented.\n");
1425       ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT;
1426       goto fail;
1427     }
1428   } else {
1429     avb_assert(ops->validate_vbmeta_public_key != NULL);
1430   }
1431 
1432   slot_data = avb_calloc(sizeof(AvbSlotVerifyData));
1433   if (slot_data == NULL) {
1434     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1435     goto fail;
1436   }
1437   slot_data->vbmeta_images =
1438       avb_calloc(sizeof(AvbVBMetaData) * MAX_NUMBER_OF_VBMETA_IMAGES);
1439   if (slot_data->vbmeta_images == NULL) {
1440     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1441     goto fail;
1442   }
1443   slot_data->loaded_partitions =
1444       avb_calloc(sizeof(AvbPartitionData) * MAX_NUMBER_OF_LOADED_PARTITIONS);
1445   if (slot_data->loaded_partitions == NULL) {
1446     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1447     goto fail;
1448   }
1449 
1450   additional_cmdline_subst = avb_new_cmdline_subst_list();
1451   if (additional_cmdline_subst == NULL) {
1452     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1453     goto fail;
1454   }
1455 
1456   if (flags & AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION) {
1457     if (requested_partitions == NULL || requested_partitions[0] == NULL) {
1458       avb_fatal(
1459           "Requested partitions cannot be empty when using "
1460           "AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION");
1461       ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT;
1462       goto fail;
1463     }
1464 
1465     /* No vbmeta partition, go through each of the requested partitions... */
1466     for (size_t n = 0; requested_partitions[n] != NULL; n++) {
1467       ret = load_and_verify_vbmeta(ops,
1468                                    requested_partitions,
1469                                    ab_suffix,
1470                                    flags,
1471                                    allow_verification_error,
1472                                    0 /* toplevel_vbmeta_flags */,
1473                                    0 /* rollback_index_location */,
1474                                    requested_partitions[n],
1475                                    avb_strlen(requested_partitions[n]),
1476                                    NULL /* expected_public_key */,
1477                                    0 /* expected_public_key_length */,
1478                                    slot_data,
1479                                    &algorithm_type,
1480                                    additional_cmdline_subst);
1481       if (!allow_verification_error && ret != AVB_SLOT_VERIFY_RESULT_OK) {
1482         goto fail;
1483       }
1484     }
1485 
1486   } else {
1487     /* Usual path, load "vbmeta"... */
1488     ret = load_and_verify_vbmeta(ops,
1489                                  requested_partitions,
1490                                  ab_suffix,
1491                                  flags,
1492                                  allow_verification_error,
1493                                  0 /* toplevel_vbmeta_flags */,
1494                                  0 /* rollback_index_location */,
1495                                  "vbmeta",
1496                                  avb_strlen("vbmeta"),
1497                                  NULL /* expected_public_key */,
1498                                  0 /* expected_public_key_length */,
1499                                  slot_data,
1500                                  &algorithm_type,
1501                                  additional_cmdline_subst);
1502     if (!allow_verification_error && ret != AVB_SLOT_VERIFY_RESULT_OK) {
1503       goto fail;
1504     }
1505   }
1506 
1507   if (!result_should_continue(ret)) {
1508     goto fail;
1509   }
1510 
1511   /* If things check out, mangle the kernel command-line as needed. */
1512   if (!(flags & AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION)) {
1513     if (avb_strcmp(slot_data->vbmeta_images[0].partition_name, "vbmeta") != 0) {
1514       avb_assert(
1515           avb_strcmp(slot_data->vbmeta_images[0].partition_name, "boot") == 0);
1516       using_boot_for_vbmeta = true;
1517     }
1518   }
1519 
1520   /* Byteswap top-level vbmeta header since we'll need it below. */
1521   avb_vbmeta_image_header_to_host_byte_order(
1522       (const AvbVBMetaImageHeader*)slot_data->vbmeta_images[0].vbmeta_data,
1523       &toplevel_vbmeta);
1524 
1525   /* Fill in |ab_suffix| field. */
1526   slot_data->ab_suffix = avb_strdup(ab_suffix);
1527   if (slot_data->ab_suffix == NULL) {
1528     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1529     goto fail;
1530   }
1531 
1532   /* If verification is disabled, we are done ... we specifically
1533    * don't want to add any androidboot.* options since verification
1534    * is disabled.
1535    */
1536   if (toplevel_vbmeta.flags & AVB_VBMETA_IMAGE_FLAGS_VERIFICATION_DISABLED) {
1537     /* Since verification is disabled we didn't process any
1538      * descriptors and thus there's no cmdline... so set root= such
1539      * that the system partition is mounted.
1540      */
1541     avb_assert(slot_data->cmdline == NULL);
1542     // Devices with dynamic partitions won't have system partition.
1543     // Instead, it has a large super partition to accommodate *.img files.
1544     // See b/119551429 for details.
1545     if (has_system_partition(ops, ab_suffix)) {
1546       slot_data->cmdline =
1547           avb_strdup("root=PARTUUID=$(ANDROID_SYSTEM_PARTUUID)");
1548     } else {
1549       // The |cmdline| field should be a NUL-terminated string.
1550       slot_data->cmdline = avb_strdup("");
1551     }
1552     if (slot_data->cmdline == NULL) {
1553       ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1554       goto fail;
1555     }
1556   } else {
1557     /* If requested, manage dm-verity mode... */
1558     AvbHashtreeErrorMode resolved_hashtree_error_mode = hashtree_error_mode;
1559     if (hashtree_error_mode ==
1560         AVB_HASHTREE_ERROR_MODE_MANAGED_RESTART_AND_EIO) {
1561       AvbIOResult io_ret;
1562       io_ret = avb_manage_hashtree_error_mode(
1563           ops, flags, slot_data, &resolved_hashtree_error_mode);
1564       if (io_ret != AVB_IO_RESULT_OK) {
1565         ret = AVB_SLOT_VERIFY_RESULT_ERROR_IO;
1566         if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
1567           ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1568         }
1569         goto fail;
1570       }
1571     }
1572     slot_data->resolved_hashtree_error_mode = resolved_hashtree_error_mode;
1573 
1574     /* Add options... */
1575     AvbSlotVerifyResult sub_ret;
1576     sub_ret = avb_append_options(ops,
1577                                  flags,
1578                                  slot_data,
1579                                  &toplevel_vbmeta,
1580                                  algorithm_type,
1581                                  hashtree_error_mode,
1582                                  resolved_hashtree_error_mode);
1583     if (sub_ret != AVB_SLOT_VERIFY_RESULT_OK) {
1584       ret = sub_ret;
1585       goto fail;
1586     }
1587   }
1588 
1589   /* Substitute $(ANDROID_SYSTEM_PARTUUID) and friends. */
1590   if (slot_data->cmdline != NULL && avb_strlen(slot_data->cmdline) != 0) {
1591     char* new_cmdline;
1592     new_cmdline = avb_sub_cmdline(ops,
1593                                   slot_data->cmdline,
1594                                   ab_suffix,
1595                                   using_boot_for_vbmeta,
1596                                   additional_cmdline_subst);
1597     if (new_cmdline != slot_data->cmdline) {
1598       if (new_cmdline == NULL) {
1599         ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1600         goto fail;
1601       }
1602       avb_free(slot_data->cmdline);
1603       slot_data->cmdline = new_cmdline;
1604     }
1605   }
1606 
1607   if (out_data != NULL) {
1608     *out_data = slot_data;
1609   } else {
1610     avb_slot_verify_data_free(slot_data);
1611   }
1612 
1613   avb_free_cmdline_subst_list(additional_cmdline_subst);
1614   additional_cmdline_subst = NULL;
1615 
1616   if (!allow_verification_error) {
1617     avb_assert(ret == AVB_SLOT_VERIFY_RESULT_OK);
1618   }
1619 
1620   return ret;
1621 
1622 fail:
1623   if (slot_data != NULL) {
1624     avb_slot_verify_data_free(slot_data);
1625   }
1626   if (additional_cmdline_subst != NULL) {
1627     avb_free_cmdline_subst_list(additional_cmdline_subst);
1628   }
1629   return ret;
1630 }
1631 
1632 void avb_slot_verify_data_free(AvbSlotVerifyData* data) {
1633   if (data->ab_suffix != NULL) {
1634     avb_free(data->ab_suffix);
1635   }
1636   if (data->cmdline != NULL) {
1637     avb_free(data->cmdline);
1638   }
1639   if (data->vbmeta_images != NULL) {
1640     size_t n;
1641     for (n = 0; n < data->num_vbmeta_images; n++) {
1642       AvbVBMetaData* vbmeta_image = &data->vbmeta_images[n];
1643       if (vbmeta_image->partition_name != NULL) {
1644         avb_free(vbmeta_image->partition_name);
1645       }
1646       if (vbmeta_image->vbmeta_data != NULL) {
1647         avb_free(vbmeta_image->vbmeta_data);
1648       }
1649     }
1650     avb_free(data->vbmeta_images);
1651   }
1652   if (data->loaded_partitions != NULL) {
1653     size_t n;
1654     for (n = 0; n < data->num_loaded_partitions; n++) {
1655       AvbPartitionData* loaded_partition = &data->loaded_partitions[n];
1656       if (loaded_partition->partition_name != NULL) {
1657         avb_free(loaded_partition->partition_name);
1658       }
1659       if (loaded_partition->data != NULL && !loaded_partition->preloaded) {
1660         sysmem_free((phys_addr_t)loaded_partition->data);
1661       }
1662     }
1663     avb_free(data->loaded_partitions);
1664   }
1665   avb_free(data);
1666 }
1667 
1668 const char* avb_slot_verify_result_to_string(AvbSlotVerifyResult result) {
1669   const char* ret = NULL;
1670 
1671   switch (result) {
1672     case AVB_SLOT_VERIFY_RESULT_OK:
1673       ret = "OK";
1674       break;
1675     case AVB_SLOT_VERIFY_RESULT_ERROR_OOM:
1676       ret = "ERROR_OOM";
1677       break;
1678     case AVB_SLOT_VERIFY_RESULT_ERROR_IO:
1679       ret = "ERROR_IO";
1680       break;
1681     case AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION:
1682       ret = "ERROR_VERIFICATION";
1683       break;
1684     case AVB_SLOT_VERIFY_RESULT_ERROR_ROLLBACK_INDEX:
1685       ret = "ERROR_ROLLBACK_INDEX";
1686       break;
1687     case AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED:
1688       ret = "ERROR_PUBLIC_KEY_REJECTED";
1689       break;
1690     case AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA:
1691       ret = "ERROR_INVALID_METADATA";
1692       break;
1693     case AVB_SLOT_VERIFY_RESULT_ERROR_UNSUPPORTED_VERSION:
1694       ret = "ERROR_UNSUPPORTED_VERSION";
1695       break;
1696     case AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT:
1697       ret = "ERROR_INVALID_ARGUMENT";
1698       break;
1699       /* Do not add a 'default:' case here because of -Wswitch. */
1700   }
1701 
1702   if (ret == NULL) {
1703     avb_error("Unknown AvbSlotVerifyResult value.\n");
1704     ret = "(unknown)";
1705   }
1706 
1707   return ret;
1708 }
1709 
1710 void avb_slot_verify_data_calculate_vbmeta_digest(AvbSlotVerifyData* data,
1711                                                   AvbDigestType digest_type,
1712                                                   uint8_t* out_digest) {
1713   bool ret = false;
1714   size_t n;
1715 
1716   switch (digest_type) {
1717     case AVB_DIGEST_TYPE_SHA256: {
1718       AvbSHA256Ctx ctx;
1719       avb_sha256_init(&ctx);
1720       for (n = 0; n < data->num_vbmeta_images; n++) {
1721         avb_sha256_update(&ctx,
1722                           data->vbmeta_images[n].vbmeta_data,
1723                           data->vbmeta_images[n].vbmeta_size);
1724       }
1725       avb_memcpy(out_digest, avb_sha256_final(&ctx), AVB_SHA256_DIGEST_SIZE);
1726       ret = true;
1727     } break;
1728 
1729     case AVB_DIGEST_TYPE_SHA512: {
1730       AvbSHA512Ctx ctx;
1731       avb_sha512_init(&ctx);
1732       for (n = 0; n < data->num_vbmeta_images; n++) {
1733         avb_sha512_update(&ctx,
1734                           data->vbmeta_images[n].vbmeta_data,
1735                           data->vbmeta_images[n].vbmeta_size);
1736       }
1737       avb_memcpy(out_digest, avb_sha512_final(&ctx), AVB_SHA512_DIGEST_SIZE);
1738       ret = true;
1739     } break;
1740 
1741       /* Do not add a 'default:' case here because of -Wswitch. */
1742   }
1743 
1744   if (!ret) {
1745     avb_fatal("Unknown digest type");
1746   }
1747 }
1748