xref: /rk3399_rockchip-uboot/lib/avb/libavb/avb_slot_verify.c (revision effae6d71544d6cab5ae01aa7160bb709b3a3e6e)
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     sha256_ctx.tot_len = hash_desc.salt_len + image_size_to_hash;
405     avb_sha256_init(&sha256_ctx);
406     avb_sha256_update(&sha256_ctx, desc_salt, hash_desc.salt_len);
407     avb_sha256_update(&sha256_ctx, image_buf, image_size_to_hash);
408     digest = avb_sha256_final(&sha256_ctx);
409     digest_len = AVB_SHA256_DIGEST_SIZE;
410   } else if (avb_strcmp((const char*)hash_desc.hash_algorithm, "sha512") == 0) {
411     sha512_ctx.tot_len = hash_desc.salt_len + image_size_to_hash;
412     avb_sha512_init(&sha512_ctx);
413     avb_sha512_update(&sha512_ctx, desc_salt, hash_desc.salt_len);
414     avb_sha512_update(&sha512_ctx, image_buf, image_size_to_hash);
415     digest = avb_sha512_final(&sha512_ctx);
416     digest_len = AVB_SHA512_DIGEST_SIZE;
417   } else {
418     avb_errorv(part_name, ": Unsupported hash algorithm.\n", NULL);
419     ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
420     goto out;
421   }
422 
423   if (hash_desc.digest_len == 0) {
424     /* Expect a match to a persistent digest. */
425     avb_debugv(part_name, ": No digest, using persistent digest.\n", NULL);
426     expected_digest_len = digest_len;
427     expected_digest = expected_digest_buf;
428     avb_assert(expected_digest_len <= sizeof(expected_digest_buf));
429     /* Pass |digest| as the |initial_digest| so devices not yet initialized get
430      * initialized to the current partition digest.
431      */
432     ret = read_persistent_digest(
433         ops, part_name, digest_len, digest, expected_digest_buf);
434     if (ret != AVB_SLOT_VERIFY_RESULT_OK) {
435       goto out;
436     }
437   } else {
438     /* Expect a match to the digest in the descriptor. */
439     expected_digest_len = hash_desc.digest_len;
440     expected_digest = desc_digest;
441   }
442 
443   if (digest_len != expected_digest_len) {
444     avb_errorv(
445         part_name, ": Digest in descriptor not of expected size.\n", NULL);
446     ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
447     goto out;
448   }
449 
450   if (avb_safe_memcmp(digest, expected_digest, digest_len) != 0) {
451     avb_errorv(part_name,
452                ": Hash of data does not match digest in descriptor.\n",
453                NULL);
454     ret = AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION;
455     goto out;
456   }
457 
458   ret = AVB_SLOT_VERIFY_RESULT_OK;
459 
460 out:
461 
462   /* If it worked and something was loaded, copy to slot_data. */
463   if ((ret == AVB_SLOT_VERIFY_RESULT_OK || result_should_continue(ret)) &&
464       image_buf != NULL) {
465     AvbPartitionData* loaded_partition;
466     if (slot_data->num_loaded_partitions == MAX_NUMBER_OF_LOADED_PARTITIONS) {
467       avb_errorv(part_name, ": Too many loaded partitions.\n", NULL);
468       ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
469       goto fail;
470     }
471     loaded_partition =
472         &slot_data->loaded_partitions[slot_data->num_loaded_partitions++];
473     loaded_partition->partition_name = avb_strdup(found);
474     loaded_partition->data_size = image_size;
475     loaded_partition->data = image_buf;
476     loaded_partition->preloaded = image_preloaded;
477     image_buf = NULL;
478   }
479 
480 fail:
481   if (image_buf != NULL && !image_preloaded) {
482     sysmem_free((phys_addr_t)image_buf);
483   }
484   return ret;
485 }
486 
487 static AvbSlotVerifyResult load_requested_partitions(
488     AvbOps* ops,
489     const char* const* requested_partitions,
490     const char* ab_suffix,
491     AvbSlotVerifyData* slot_data) {
492   AvbSlotVerifyResult ret;
493   uint8_t* image_buf = NULL;
494   bool image_preloaded = false;
495   size_t n;
496 
497   for (n = 0; requested_partitions[n] != NULL; n++) {
498     char part_name[AVB_PART_NAME_MAX_SIZE];
499     AvbIOResult io_ret;
500     uint64_t image_size;
501     AvbPartitionData* loaded_partition;
502 
503     if (!avb_str_concat(part_name,
504                         sizeof part_name,
505                         requested_partitions[n],
506                         avb_strlen(requested_partitions[n]),
507                         ab_suffix,
508                         avb_strlen(ab_suffix))) {
509       avb_error("Partition name and suffix does not fit.\n");
510       ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
511       goto out;
512     }
513 
514     io_ret = ops->get_size_of_partition(ops, part_name, &image_size);
515     if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
516       ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
517       goto out;
518     } else if (io_ret != AVB_IO_RESULT_OK) {
519       avb_errorv(part_name, ": Error determining partition size.\n", NULL);
520       ret = AVB_SLOT_VERIFY_RESULT_ERROR_IO;
521       goto out;
522     }
523     avb_debugv(part_name, ": Loading entire partition.\n", NULL);
524 
525     ret = load_full_partition(
526         ops, part_name, image_size, &image_buf, &image_preloaded, 1);
527     if (ret != AVB_SLOT_VERIFY_RESULT_OK) {
528       goto out;
529     }
530 
531     /* Move to slot_data. */
532     if (slot_data->num_loaded_partitions == MAX_NUMBER_OF_LOADED_PARTITIONS) {
533       avb_errorv(part_name, ": Too many loaded partitions.\n", NULL);
534       ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
535       goto out;
536     }
537     loaded_partition =
538         &slot_data->loaded_partitions[slot_data->num_loaded_partitions++];
539     loaded_partition->partition_name = avb_strdup(requested_partitions[n]);
540     if (loaded_partition->partition_name == NULL) {
541       ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
542       goto out;
543     }
544     loaded_partition->data_size = image_size;
545     loaded_partition->data = image_buf; /* Transferring the owner. */
546     loaded_partition->preloaded = image_preloaded;
547     image_buf = NULL;
548     image_preloaded = false;
549   }
550 
551   ret = AVB_SLOT_VERIFY_RESULT_OK;
552 
553 out:
554   /* Free the current buffer if any. */
555   if (image_buf != NULL && !image_preloaded) {
556     sysmem_free((phys_addr_t)image_buf);
557   }
558   /* Buffers that are already saved in slot_data will be handled by the caller
559    * even on failure. */
560   return ret;
561 }
562 
563 static AvbSlotVerifyResult load_and_verify_vbmeta(
564     AvbOps* ops,
565     const char* const* requested_partitions,
566     const char* ab_suffix,
567     AvbSlotVerifyFlags flags,
568     bool allow_verification_error,
569     AvbVBMetaImageFlags toplevel_vbmeta_flags,
570     int rollback_index_location,
571     const char* partition_name,
572     size_t partition_name_len,
573     const uint8_t* expected_public_key,
574     size_t expected_public_key_length,
575     AvbSlotVerifyData* slot_data,
576     AvbAlgorithmType* out_algorithm_type,
577     AvbCmdlineSubstList* out_additional_cmdline_subst) {
578   char full_partition_name[AVB_PART_NAME_MAX_SIZE];
579   AvbSlotVerifyResult ret;
580   AvbIOResult io_ret;
581   uint64_t vbmeta_offset;
582   size_t vbmeta_size;
583   uint8_t* vbmeta_buf = NULL;
584   size_t vbmeta_num_read;
585   AvbVBMetaVerifyResult vbmeta_ret;
586   const uint8_t* pk_data;
587   size_t pk_len;
588   AvbVBMetaImageHeader vbmeta_header;
589   uint64_t stored_rollback_index;
590   const AvbDescriptor** descriptors = NULL;
591   size_t num_descriptors;
592   size_t n;
593   bool is_main_vbmeta;
594   bool look_for_vbmeta_footer;
595   AvbVBMetaData* vbmeta_image_data = NULL;
596 
597   ret = AVB_SLOT_VERIFY_RESULT_OK;
598 
599   avb_assert(slot_data != NULL);
600 
601   /* Since we allow top-level vbmeta in 'boot', use
602    * rollback_index_location to determine whether we're the main
603    * vbmeta struct.
604    */
605   is_main_vbmeta = false;
606   if (rollback_index_location == 0) {
607     if ((flags & AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION) == 0) {
608       is_main_vbmeta = true;
609     }
610   }
611 
612   /* Don't use footers for vbmeta partitions ('vbmeta' or
613    * 'vbmeta_<partition_name>').
614    */
615   look_for_vbmeta_footer = true;
616   if (avb_strncmp(partition_name, "vbmeta", avb_strlen("vbmeta")) == 0) {
617     look_for_vbmeta_footer = false;
618   }
619 
620   if (!avb_validate_utf8((const uint8_t*)partition_name, partition_name_len)) {
621     avb_error("Partition name is not valid UTF-8.\n");
622     ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
623     goto out;
624   }
625 
626   /* Construct full partition name e.g. system_a. */
627   if (!avb_str_concat(full_partition_name,
628                       sizeof full_partition_name,
629                       partition_name,
630                       partition_name_len,
631                       ab_suffix,
632                       avb_strlen(ab_suffix))) {
633     avb_error("Partition name and suffix does not fit.\n");
634     ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
635     goto out;
636   }
637 
638   /* If we're loading from the main vbmeta partition, the vbmeta struct is in
639    * the beginning. Otherwise we may have to locate it via a footer... if no
640    * footer is found, we look in the beginning to support e.g. vbmeta_<org>
641    * partitions holding data for e.g. super partitions (b/80195851 for
642    * rationale).
643    */
644   vbmeta_offset = 0;
645   vbmeta_size = VBMETA_MAX_SIZE;
646   if (look_for_vbmeta_footer) {
647     uint8_t footer_buf[AVB_FOOTER_SIZE];
648     size_t footer_num_read;
649     AvbFooter footer;
650 
651     io_ret = ops->read_from_partition(ops,
652                                       full_partition_name,
653                                       -AVB_FOOTER_SIZE,
654                                       AVB_FOOTER_SIZE,
655                                       footer_buf,
656                                       &footer_num_read);
657     if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
658       ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
659       goto out;
660     } else if (io_ret != AVB_IO_RESULT_OK) {
661       avb_errorv(full_partition_name, ": Error loading footer.\n", NULL);
662       ret = AVB_SLOT_VERIFY_RESULT_ERROR_IO;
663       goto out;
664     }
665     avb_assert(footer_num_read == AVB_FOOTER_SIZE);
666 
667     if (!avb_footer_validate_and_byteswap((const AvbFooter*)footer_buf,
668                                           &footer)) {
669       avb_debugv(full_partition_name, ": No footer detected.\n", NULL);
670     } else {
671       /* Basic footer sanity check since the data is untrusted. */
672       if (footer.vbmeta_size > VBMETA_MAX_SIZE) {
673         avb_errorv(
674             full_partition_name, ": Invalid vbmeta size in footer.\n", NULL);
675       } else {
676         vbmeta_offset = footer.vbmeta_offset;
677         vbmeta_size = footer.vbmeta_size;
678       }
679     }
680   }
681 
682   vbmeta_buf = avb_malloc(vbmeta_size);
683   if (vbmeta_buf == NULL) {
684     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
685     goto out;
686   }
687 
688   if (vbmeta_offset != 0) {
689     avb_debugv("Loading vbmeta struct in footer from partition '",
690                full_partition_name,
691                "'.\n",
692                NULL);
693   } else {
694     avb_debugv("Loading vbmeta struct from partition '",
695                full_partition_name,
696                "'.\n",
697                NULL);
698   }
699 
700   io_ret = ops->read_from_partition(ops,
701                                     full_partition_name,
702                                     vbmeta_offset,
703                                     vbmeta_size,
704                                     vbmeta_buf,
705                                     &vbmeta_num_read);
706   if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
707     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
708     goto out;
709   } else if (io_ret != AVB_IO_RESULT_OK) {
710     /* If we're looking for 'vbmeta' but there is no such partition,
711      * go try to get it from the boot partition instead.
712      */
713     if (is_main_vbmeta && io_ret == AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION &&
714         !look_for_vbmeta_footer) {
715       avb_debugv(full_partition_name,
716                  ": No such partition. Trying 'boot' instead.\n",
717                  NULL);
718       ret = load_and_verify_vbmeta(ops,
719                                    requested_partitions,
720                                    ab_suffix,
721                                    flags,
722                                    allow_verification_error,
723                                    0 /* toplevel_vbmeta_flags */,
724                                    0 /* rollback_index_location */,
725                                    "boot",
726                                    avb_strlen("boot"),
727                                    NULL /* expected_public_key */,
728                                    0 /* expected_public_key_length */,
729                                    slot_data,
730                                    out_algorithm_type,
731                                    out_additional_cmdline_subst);
732       goto out;
733     } else {
734       avb_errorv(full_partition_name, ": Error loading vbmeta data.\n", NULL);
735       ret = AVB_SLOT_VERIFY_RESULT_ERROR_IO;
736       goto out;
737     }
738   }
739   avb_assert(vbmeta_num_read <= vbmeta_size);
740 
741   /* Check if the image is properly signed and get the public key used
742    * to sign the image.
743    */
744   vbmeta_ret =
745       avb_vbmeta_image_verify(vbmeta_buf, vbmeta_num_read, &pk_data, &pk_len);
746   switch (vbmeta_ret) {
747     case AVB_VBMETA_VERIFY_RESULT_OK:
748       avb_assert(pk_data != NULL && pk_len > 0);
749       break;
750 
751     case AVB_VBMETA_VERIFY_RESULT_OK_NOT_SIGNED:
752     case AVB_VBMETA_VERIFY_RESULT_HASH_MISMATCH:
753     case AVB_VBMETA_VERIFY_RESULT_SIGNATURE_MISMATCH:
754       ret = AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION;
755       avb_errorv(full_partition_name,
756                  ": Error verifying vbmeta image: ",
757                  avb_vbmeta_verify_result_to_string(vbmeta_ret),
758                  "\n",
759                  NULL);
760       if (!allow_verification_error) {
761         goto out;
762       }
763       break;
764 
765     case AVB_VBMETA_VERIFY_RESULT_INVALID_VBMETA_HEADER:
766       /* No way to continue this case. */
767       ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
768       avb_errorv(full_partition_name,
769                  ": Error verifying vbmeta image: invalid vbmeta header\n",
770                  NULL);
771       goto out;
772 
773     case AVB_VBMETA_VERIFY_RESULT_UNSUPPORTED_VERSION:
774       /* No way to continue this case. */
775       ret = AVB_SLOT_VERIFY_RESULT_ERROR_UNSUPPORTED_VERSION;
776       avb_errorv(full_partition_name,
777                  ": Error verifying vbmeta image: unsupported AVB version\n",
778                  NULL);
779       goto out;
780   }
781 
782   /* Byteswap the header. */
783   avb_vbmeta_image_header_to_host_byte_order((AvbVBMetaImageHeader*)vbmeta_buf,
784                                              &vbmeta_header);
785 
786   /* If we're the toplevel, assign flags so they'll be passed down. */
787   if (is_main_vbmeta) {
788     toplevel_vbmeta_flags = (AvbVBMetaImageFlags)vbmeta_header.flags;
789   } else {
790     if (vbmeta_header.flags != 0) {
791       ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
792       avb_errorv(full_partition_name,
793                  ": chained vbmeta image has non-zero flags\n",
794                  NULL);
795       goto out;
796     }
797   }
798 
799   uint32_t rollback_index_location_to_use = rollback_index_location;
800 
801   /* Check if key used to make signature matches what is expected. */
802   if (pk_data != NULL) {
803     if (expected_public_key != NULL) {
804       avb_assert(!is_main_vbmeta);
805       if (expected_public_key_length != pk_len ||
806           avb_safe_memcmp(expected_public_key, pk_data, pk_len) != 0) {
807         avb_errorv(full_partition_name,
808                    ": Public key used to sign data does not match key in chain "
809                    "partition descriptor.\n",
810                    NULL);
811         ret = AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED;
812         if (!allow_verification_error) {
813           goto out;
814         }
815       }
816     } else {
817       bool key_is_trusted = false;
818       const uint8_t* pk_metadata = NULL;
819       size_t pk_metadata_len = 0;
820 
821       if (vbmeta_header.public_key_metadata_size > 0) {
822         pk_metadata = vbmeta_buf + sizeof(AvbVBMetaImageHeader) +
823                       vbmeta_header.authentication_data_block_size +
824                       vbmeta_header.public_key_metadata_offset;
825         pk_metadata_len = vbmeta_header.public_key_metadata_size;
826       }
827 
828       // If we're not using a vbmeta partition, need to use another AvbOps...
829       if (flags & AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION) {
830         io_ret = ops->validate_public_key_for_partition(
831             ops,
832             full_partition_name,
833             pk_data,
834             pk_len,
835             pk_metadata,
836             pk_metadata_len,
837             &key_is_trusted,
838             &rollback_index_location_to_use);
839       } else {
840         avb_assert(is_main_vbmeta);
841         io_ret = ops->validate_vbmeta_public_key(ops,
842                                                  pk_data,
843                                                  pk_len,
844                                                  pk_metadata,
845                                                  pk_metadata_len,
846                                                  &key_is_trusted);
847       }
848 
849       if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
850         ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
851         goto out;
852       } else if (io_ret != AVB_IO_RESULT_OK) {
853         avb_errorv(full_partition_name,
854                    ": Error while checking public key used to sign data.\n",
855                    NULL);
856         ret = AVB_SLOT_VERIFY_RESULT_ERROR_IO;
857         goto out;
858       }
859       if (!key_is_trusted) {
860         avb_errorv(full_partition_name,
861                    ": Public key used to sign data rejected.\n",
862                    NULL);
863         ret = AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED;
864         if (!allow_verification_error) {
865           goto out;
866         }
867       }
868     }
869   }
870 
871   /* Check rollback index. */
872   io_ret = ops->read_rollback_index(
873       ops, rollback_index_location_to_use, &stored_rollback_index);
874   if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
875     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
876     goto out;
877   } else if (io_ret != AVB_IO_RESULT_OK) {
878     avb_errorv(full_partition_name,
879                ": Error getting rollback index for location.\n",
880                NULL);
881     ret = AVB_SLOT_VERIFY_RESULT_ERROR_IO;
882     goto out;
883   }
884   if (vbmeta_header.rollback_index < stored_rollback_index) {
885     avb_errorv(
886         full_partition_name,
887         ": Image rollback index is less than the stored rollback index.\n",
888         NULL);
889     ret = AVB_SLOT_VERIFY_RESULT_ERROR_ROLLBACK_INDEX;
890     if (!allow_verification_error) {
891       goto out;
892     }
893   }
894 
895   /* Copy vbmeta to vbmeta_images before recursing. */
896   if (is_main_vbmeta) {
897     avb_assert(slot_data->num_vbmeta_images == 0);
898   } else {
899     if (!(flags & AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION)) {
900       avb_assert(slot_data->num_vbmeta_images > 0);
901     }
902   }
903   if (slot_data->num_vbmeta_images == MAX_NUMBER_OF_VBMETA_IMAGES) {
904     avb_errorv(full_partition_name, ": Too many vbmeta images.\n", NULL);
905     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
906     goto out;
907   }
908   vbmeta_image_data = &slot_data->vbmeta_images[slot_data->num_vbmeta_images++];
909   vbmeta_image_data->partition_name = avb_strdup(partition_name);
910   vbmeta_image_data->vbmeta_data = vbmeta_buf;
911   /* Note that |vbmeta_buf| is actually |vbmeta_num_read| bytes long
912    * and this includes data past the end of the image. Pass the
913    * actual size of the vbmeta image. Also, no need to use
914    * avb_safe_add() since the header has already been verified.
915    */
916   vbmeta_image_data->vbmeta_size =
917       sizeof(AvbVBMetaImageHeader) +
918       vbmeta_header.authentication_data_block_size +
919       vbmeta_header.auxiliary_data_block_size;
920   vbmeta_image_data->verify_result = vbmeta_ret;
921 
922   /* If verification has been disabled by setting a bit in the image,
923    * we're done... except that we need to load the entirety of the
924    * requested partitions.
925    */
926   if (vbmeta_header.flags & AVB_VBMETA_IMAGE_FLAGS_VERIFICATION_DISABLED) {
927     AvbSlotVerifyResult sub_ret;
928     avb_debugv(
929         full_partition_name, ": VERIFICATION_DISABLED bit is set.\n", NULL);
930     /* If load_requested_partitions() fail it is always a fatal
931      * failure (e.g. ERROR_INVALID_ARGUMENT, ERROR_OOM, etc.) rather
932      * than recoverable (e.g. one where result_should_continue()
933      * returns true) and we want to convey that error.
934      */
935     sub_ret = load_requested_partitions(
936         ops, requested_partitions, ab_suffix, slot_data);
937     if (sub_ret != AVB_SLOT_VERIFY_RESULT_OK) {
938       ret = sub_ret;
939     }
940     goto out;
941   }
942 
943   /* Now go through all descriptors and take the appropriate action:
944    *
945    * - hash descriptor: Load data from partition, calculate hash, and
946    *   checks that it matches what's in the hash descriptor.
947    *
948    * - hashtree descriptor: Do nothing since verification happens
949    *   on-the-fly from within the OS. (Unless the descriptor uses a
950    *   persistent digest, in which case we need to find it).
951    *
952    * - chained partition descriptor: Load the footer, load the vbmeta
953    *   image, verify vbmeta image (includes rollback checks, hash
954    *   checks, bail on chained partitions).
955    */
956   descriptors =
957       avb_descriptor_get_all(vbmeta_buf, vbmeta_num_read, &num_descriptors);
958   for (n = 0; n < num_descriptors; n++) {
959     AvbDescriptor desc;
960 
961     if (!avb_descriptor_validate_and_byteswap(descriptors[n], &desc)) {
962       avb_errorv(full_partition_name, ": Descriptor is invalid.\n", NULL);
963       ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
964       goto out;
965     }
966 
967     switch (desc.tag) {
968       case AVB_DESCRIPTOR_TAG_HASH: {
969         AvbSlotVerifyResult sub_ret;
970         sub_ret = load_and_verify_hash_partition(ops,
971                                                  requested_partitions,
972                                                  ab_suffix,
973                                                  allow_verification_error,
974                                                  descriptors[n],
975                                                  slot_data);
976         if (sub_ret != AVB_SLOT_VERIFY_RESULT_OK) {
977           ret = sub_ret;
978           if (!allow_verification_error || !result_should_continue(ret)) {
979             goto out;
980           }
981         }
982       } break;
983 
984       case AVB_DESCRIPTOR_TAG_CHAIN_PARTITION: {
985         AvbSlotVerifyResult sub_ret;
986         AvbChainPartitionDescriptor chain_desc;
987         const uint8_t* chain_partition_name;
988         const uint8_t* chain_public_key;
989 
990         /* Only allow CHAIN_PARTITION descriptors in the main vbmeta image. */
991         if (!is_main_vbmeta) {
992           avb_errorv(full_partition_name,
993                      ": Encountered chain descriptor not in main image.\n",
994                      NULL);
995           ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
996           goto out;
997         }
998 
999         if (!avb_chain_partition_descriptor_validate_and_byteswap(
1000                 (AvbChainPartitionDescriptor*)descriptors[n], &chain_desc)) {
1001           avb_errorv(full_partition_name,
1002                      ": Chain partition descriptor is invalid.\n",
1003                      NULL);
1004           ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1005           goto out;
1006         }
1007 
1008         if (chain_desc.rollback_index_location == 0) {
1009           avb_errorv(full_partition_name,
1010                      ": Chain partition has invalid "
1011                      "rollback_index_location field.\n",
1012                      NULL);
1013           ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1014           goto out;
1015         }
1016 
1017         chain_partition_name = ((const uint8_t*)descriptors[n]) +
1018                                sizeof(AvbChainPartitionDescriptor);
1019         chain_public_key = chain_partition_name + chain_desc.partition_name_len;
1020 
1021         sub_ret =
1022             load_and_verify_vbmeta(ops,
1023                                    requested_partitions,
1024                                    ab_suffix,
1025                                    flags,
1026                                    allow_verification_error,
1027                                    toplevel_vbmeta_flags,
1028                                    chain_desc.rollback_index_location,
1029                                    (const char*)chain_partition_name,
1030                                    chain_desc.partition_name_len,
1031                                    chain_public_key,
1032                                    chain_desc.public_key_len,
1033                                    slot_data,
1034                                    NULL, /* out_algorithm_type */
1035                                    NULL /* out_additional_cmdline_subst */);
1036         if (sub_ret != AVB_SLOT_VERIFY_RESULT_OK) {
1037           ret = sub_ret;
1038           if (!result_should_continue(ret)) {
1039             goto out;
1040           }
1041         }
1042       } break;
1043 
1044       case AVB_DESCRIPTOR_TAG_KERNEL_CMDLINE: {
1045         const uint8_t* kernel_cmdline;
1046         AvbKernelCmdlineDescriptor kernel_cmdline_desc;
1047         bool apply_cmdline;
1048 
1049         if (!avb_kernel_cmdline_descriptor_validate_and_byteswap(
1050                 (AvbKernelCmdlineDescriptor*)descriptors[n],
1051                 &kernel_cmdline_desc)) {
1052           avb_errorv(full_partition_name,
1053                      ": Kernel cmdline descriptor is invalid.\n",
1054                      NULL);
1055           ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1056           goto out;
1057         }
1058 
1059         kernel_cmdline = ((const uint8_t*)descriptors[n]) +
1060                          sizeof(AvbKernelCmdlineDescriptor);
1061 
1062         if (!avb_validate_utf8(kernel_cmdline,
1063                                kernel_cmdline_desc.kernel_cmdline_length)) {
1064           avb_errorv(full_partition_name,
1065                      ": Kernel cmdline is not valid UTF-8.\n",
1066                      NULL);
1067           ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1068           goto out;
1069         }
1070 
1071         /* Compare the flags for top-level VBMeta struct with flags in
1072          * the command-line descriptor so command-line snippets only
1073          * intended for a certain mode (dm-verity enabled/disabled)
1074          * are skipped if applicable.
1075          */
1076         apply_cmdline = true;
1077         if (toplevel_vbmeta_flags & AVB_VBMETA_IMAGE_FLAGS_HASHTREE_DISABLED) {
1078           if (kernel_cmdline_desc.flags &
1079               AVB_KERNEL_CMDLINE_FLAGS_USE_ONLY_IF_HASHTREE_NOT_DISABLED) {
1080             apply_cmdline = false;
1081           }
1082         } else {
1083           if (kernel_cmdline_desc.flags &
1084               AVB_KERNEL_CMDLINE_FLAGS_USE_ONLY_IF_HASHTREE_DISABLED) {
1085             apply_cmdline = false;
1086           }
1087         }
1088 
1089         if (apply_cmdline) {
1090           if (slot_data->cmdline == NULL) {
1091             slot_data->cmdline =
1092                 avb_calloc(kernel_cmdline_desc.kernel_cmdline_length + 1);
1093             if (slot_data->cmdline == NULL) {
1094               ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1095               goto out;
1096             }
1097             avb_memcpy(slot_data->cmdline,
1098                        kernel_cmdline,
1099                        kernel_cmdline_desc.kernel_cmdline_length);
1100           } else {
1101             /* new cmdline is: <existing_cmdline> + ' ' + <newcmdline> + '\0' */
1102             size_t orig_size = avb_strlen(slot_data->cmdline);
1103             size_t new_size =
1104                 orig_size + 1 + kernel_cmdline_desc.kernel_cmdline_length + 1;
1105             char* new_cmdline = avb_calloc(new_size);
1106             if (new_cmdline == NULL) {
1107               ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1108               goto out;
1109             }
1110             avb_memcpy(new_cmdline, slot_data->cmdline, orig_size);
1111             new_cmdline[orig_size] = ' ';
1112             avb_memcpy(new_cmdline + orig_size + 1,
1113                        kernel_cmdline,
1114                        kernel_cmdline_desc.kernel_cmdline_length);
1115             avb_free(slot_data->cmdline);
1116             slot_data->cmdline = new_cmdline;
1117           }
1118         }
1119       } break;
1120 
1121       case AVB_DESCRIPTOR_TAG_HASHTREE: {
1122         AvbHashtreeDescriptor hashtree_desc;
1123 
1124         if (!avb_hashtree_descriptor_validate_and_byteswap(
1125                 (AvbHashtreeDescriptor*)descriptors[n], &hashtree_desc)) {
1126           avb_errorv(
1127               full_partition_name, ": Hashtree descriptor is invalid.\n", NULL);
1128           ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1129           goto out;
1130         }
1131 
1132         /* We only need to continue when there is no digest in the descriptor.
1133          * This is because the only processing here is to find the digest and
1134          * make it available on the kernel command line.
1135          */
1136         if (hashtree_desc.root_digest_len == 0) {
1137           char part_name[AVB_PART_NAME_MAX_SIZE];
1138           size_t digest_len = 0;
1139           uint8_t digest_buf[AVB_SHA512_DIGEST_SIZE];
1140           const uint8_t* desc_partition_name =
1141               ((const uint8_t*)descriptors[n]) + sizeof(AvbHashtreeDescriptor);
1142 
1143           if (!avb_validate_utf8(desc_partition_name,
1144                                  hashtree_desc.partition_name_len)) {
1145             avb_error("Partition name is not valid UTF-8.\n");
1146             ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1147             goto out;
1148           }
1149 
1150           /* No ab_suffix for partitions without a digest in the descriptor
1151            * because these partitions hold data unique to this device and are
1152            * not updated using an A/B scheme.
1153            */
1154           if ((hashtree_desc.flags &
1155                AVB_HASHTREE_DESCRIPTOR_FLAGS_DO_NOT_USE_AB) == 0 &&
1156               avb_strlen(ab_suffix) != 0) {
1157             avb_error("Cannot use A/B with a persistent root digest.\n");
1158             ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1159             goto out;
1160           }
1161           if (hashtree_desc.partition_name_len >= AVB_PART_NAME_MAX_SIZE) {
1162             avb_error("Partition name does not fit.\n");
1163             ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1164             goto out;
1165           }
1166           avb_memcpy(
1167               part_name, desc_partition_name, hashtree_desc.partition_name_len);
1168           part_name[hashtree_desc.partition_name_len] = '\0';
1169 
1170           /* Determine the expected digest size from the hash algorithm. */
1171           if (avb_strcmp((const char*)hashtree_desc.hash_algorithm, "sha1") ==
1172               0) {
1173             digest_len = AVB_SHA1_DIGEST_SIZE;
1174           } else if (avb_strcmp((const char*)hashtree_desc.hash_algorithm,
1175                                 "sha256") == 0) {
1176             digest_len = AVB_SHA256_DIGEST_SIZE;
1177           } else if (avb_strcmp((const char*)hashtree_desc.hash_algorithm,
1178                                 "sha512") == 0) {
1179             digest_len = AVB_SHA512_DIGEST_SIZE;
1180           } else {
1181             avb_errorv(part_name, ": Unsupported hash algorithm.\n", NULL);
1182             ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1183             goto out;
1184           }
1185 
1186           ret = read_persistent_digest(ops,
1187                                        part_name,
1188                                        digest_len,
1189                                        NULL /* initial_digest */,
1190                                        digest_buf);
1191           if (ret != AVB_SLOT_VERIFY_RESULT_OK) {
1192             goto out;
1193           }
1194 
1195           if (out_additional_cmdline_subst) {
1196             ret =
1197                 avb_add_root_digest_substitution(part_name,
1198                                                  digest_buf,
1199                                                  digest_len,
1200                                                  out_additional_cmdline_subst);
1201             if (ret != AVB_SLOT_VERIFY_RESULT_OK) {
1202               goto out;
1203             }
1204           }
1205         }
1206       } break;
1207 
1208       case AVB_DESCRIPTOR_TAG_PROPERTY:
1209         /* Do nothing. */
1210         break;
1211     }
1212   }
1213 
1214   if (rollback_index_location < 0 ||
1215       rollback_index_location >= AVB_MAX_NUMBER_OF_ROLLBACK_INDEX_LOCATIONS) {
1216     avb_errorv(
1217         full_partition_name, ": Invalid rollback_index_location.\n", NULL);
1218     ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA;
1219     goto out;
1220   }
1221 
1222   slot_data->rollback_indexes[rollback_index_location] =
1223       vbmeta_header.rollback_index;
1224 
1225   if (out_algorithm_type != NULL) {
1226     *out_algorithm_type = (AvbAlgorithmType)vbmeta_header.algorithm_type;
1227   }
1228 
1229 out:
1230   /* If |vbmeta_image_data| isn't NULL it means that it adopted
1231    * |vbmeta_buf| so in that case don't free it here.
1232    */
1233   if (vbmeta_image_data == NULL) {
1234     if (vbmeta_buf != NULL) {
1235       avb_free(vbmeta_buf);
1236     }
1237   }
1238   if (descriptors != NULL) {
1239     avb_free(descriptors);
1240   }
1241   return ret;
1242 }
1243 
1244 static AvbIOResult avb_manage_hashtree_error_mode(
1245     AvbOps* ops,
1246     AvbSlotVerifyFlags flags,
1247     AvbSlotVerifyData* data,
1248     AvbHashtreeErrorMode* out_hashtree_error_mode) {
1249   AvbHashtreeErrorMode ret = AVB_HASHTREE_ERROR_MODE_RESTART;
1250   AvbIOResult io_ret = AVB_IO_RESULT_OK;
1251   uint8_t vbmeta_digest_sha256[AVB_SHA256_DIGEST_SIZE];
1252   uint8_t stored_vbmeta_digest_sha256[AVB_SHA256_DIGEST_SIZE];
1253   size_t num_bytes_read;
1254 
1255   avb_assert(out_hashtree_error_mode != NULL);
1256   avb_assert(ops->read_persistent_value != NULL);
1257   avb_assert(ops->write_persistent_value != NULL);
1258 
1259   // If we're rebooting because of dm-verity corruption, make a note of
1260   // the vbmeta hash so we can stay in 'eio' mode until things change.
1261   if (flags & AVB_SLOT_VERIFY_FLAGS_RESTART_CAUSED_BY_HASHTREE_CORRUPTION) {
1262     avb_debug(
1263         "Rebooting because of dm-verity corruption - "
1264         "recording OS instance and using 'eio' mode.\n");
1265     avb_slot_verify_data_calculate_vbmeta_digest(
1266         data, AVB_DIGEST_TYPE_SHA256, vbmeta_digest_sha256);
1267     io_ret = ops->write_persistent_value(ops,
1268                                          AVB_NPV_MANAGED_VERITY_MODE,
1269                                          AVB_SHA256_DIGEST_SIZE,
1270                                          vbmeta_digest_sha256);
1271     if (io_ret != AVB_IO_RESULT_OK) {
1272       avb_error("Error writing to " AVB_NPV_MANAGED_VERITY_MODE ".\n");
1273       goto out;
1274     }
1275     ret = AVB_HASHTREE_ERROR_MODE_EIO;
1276     io_ret = AVB_IO_RESULT_OK;
1277     goto out;
1278   }
1279 
1280   // See if we're in 'eio' mode.
1281   io_ret = ops->read_persistent_value(ops,
1282                                       AVB_NPV_MANAGED_VERITY_MODE,
1283                                       AVB_SHA256_DIGEST_SIZE,
1284                                       stored_vbmeta_digest_sha256,
1285                                       &num_bytes_read);
1286   if (io_ret == AVB_IO_RESULT_ERROR_NO_SUCH_VALUE ||
1287       (io_ret == AVB_IO_RESULT_OK && num_bytes_read == 0)) {
1288     // This is the usual case ('eio' mode not set).
1289     avb_debug("No dm-verity corruption - using in 'restart' mode.\n");
1290     ret = AVB_HASHTREE_ERROR_MODE_RESTART;
1291     io_ret = AVB_IO_RESULT_OK;
1292     goto out;
1293   } else if (io_ret != AVB_IO_RESULT_OK) {
1294     avb_error("Error reading from " AVB_NPV_MANAGED_VERITY_MODE ".\n");
1295     goto out;
1296   }
1297   if (num_bytes_read != AVB_SHA256_DIGEST_SIZE) {
1298     avb_error(
1299         "Unexpected number of bytes read from " AVB_NPV_MANAGED_VERITY_MODE
1300         ".\n");
1301     io_ret = AVB_IO_RESULT_ERROR_IO;
1302     goto out;
1303   }
1304 
1305   // OK, so we're currently in 'eio' mode and the vbmeta digest of the OS
1306   // that caused this is in |stored_vbmeta_digest_sha256| ... now see if
1307   // the OS we're dealing with now is the same.
1308   avb_slot_verify_data_calculate_vbmeta_digest(
1309       data, AVB_DIGEST_TYPE_SHA256, vbmeta_digest_sha256);
1310   if (avb_memcmp(vbmeta_digest_sha256,
1311                  stored_vbmeta_digest_sha256,
1312                  AVB_SHA256_DIGEST_SIZE) == 0) {
1313     // It's the same so we're still in 'eio' mode.
1314     avb_debug("Same OS instance detected - staying in 'eio' mode.\n");
1315     ret = AVB_HASHTREE_ERROR_MODE_EIO;
1316     io_ret = AVB_IO_RESULT_OK;
1317   } else {
1318     // It did change!
1319     avb_debug(
1320         "New OS instance detected - changing from 'eio' to 'restart' mode.\n");
1321     io_ret =
1322         ops->write_persistent_value(ops,
1323                                     AVB_NPV_MANAGED_VERITY_MODE,
1324                                     0,  // This clears the persistent property.
1325                                     vbmeta_digest_sha256);
1326     if (io_ret != AVB_IO_RESULT_OK) {
1327       avb_error("Error clearing " AVB_NPV_MANAGED_VERITY_MODE ".\n");
1328       goto out;
1329     }
1330     ret = AVB_HASHTREE_ERROR_MODE_RESTART;
1331     io_ret = AVB_IO_RESULT_OK;
1332   }
1333 
1334 out:
1335   *out_hashtree_error_mode = ret;
1336   return io_ret;
1337 }
1338 
1339 static bool has_system_partition(AvbOps* ops, const char* ab_suffix) {
1340   char part_name[AVB_PART_NAME_MAX_SIZE];
1341   char* system_part_name = "system";
1342   char guid_buf[37];
1343   AvbIOResult io_ret;
1344 
1345   if (!avb_str_concat(part_name,
1346                       sizeof part_name,
1347                       system_part_name,
1348                       avb_strlen(system_part_name),
1349                       ab_suffix,
1350                       avb_strlen(ab_suffix))) {
1351     avb_error("System partition name and suffix does not fit.\n");
1352     return false;
1353   }
1354 
1355   io_ret = ops->get_unique_guid_for_partition(
1356       ops, part_name, guid_buf, sizeof guid_buf);
1357   if (io_ret == AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION) {
1358     avb_debug("No system partition.\n");
1359     return false;
1360   } else if (io_ret != AVB_IO_RESULT_OK) {
1361     avb_error("Error getting unique GUID for system partition.\n");
1362     return false;
1363   }
1364 
1365   return true;
1366 }
1367 
1368 AvbSlotVerifyResult avb_slot_verify(AvbOps* ops,
1369                                     const char* const* requested_partitions,
1370                                     const char* ab_suffix,
1371                                     AvbSlotVerifyFlags flags,
1372                                     AvbHashtreeErrorMode hashtree_error_mode,
1373                                     AvbSlotVerifyData** out_data) {
1374   AvbSlotVerifyResult ret = 0;
1375   AvbSlotVerifyData* slot_data = NULL;
1376   AvbAlgorithmType algorithm_type = AVB_ALGORITHM_TYPE_NONE;
1377   bool using_boot_for_vbmeta = false;
1378   AvbVBMetaImageHeader toplevel_vbmeta;
1379   bool allow_verification_error =
1380       (flags & AVB_SLOT_VERIFY_FLAGS_ALLOW_VERIFICATION_ERROR);
1381   AvbCmdlineSubstList* additional_cmdline_subst = NULL;
1382 
1383   /* Fail early if we're missing the AvbOps needed for slot verification. */
1384   avb_assert(ops->read_is_device_unlocked != NULL);
1385   avb_assert(ops->read_from_partition != NULL);
1386   avb_assert(ops->get_size_of_partition != NULL);
1387   avb_assert(ops->read_rollback_index != NULL);
1388   avb_assert(ops->get_unique_guid_for_partition != NULL);
1389 
1390   if (out_data != NULL) {
1391     *out_data = NULL;
1392   }
1393 
1394   /* Allowing dm-verity errors defeats the purpose of verified boot so
1395    * only allow this if set up to allow verification errors
1396    * (e.g. typically only UNLOCKED mode).
1397    */
1398   if (hashtree_error_mode == AVB_HASHTREE_ERROR_MODE_LOGGING &&
1399       !allow_verification_error) {
1400     ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT;
1401     goto fail;
1402   }
1403 
1404   /* Make sure passed-in AvbOps support persistent values if
1405    * asking for libavb to manage verity state.
1406    */
1407   if (hashtree_error_mode == AVB_HASHTREE_ERROR_MODE_MANAGED_RESTART_AND_EIO) {
1408     if (ops->read_persistent_value == NULL ||
1409         ops->write_persistent_value == NULL) {
1410       avb_error(
1411           "Persistent values required for "
1412           "AVB_HASHTREE_ERROR_MODE_MANAGED_RESTART_AND_EIO "
1413           "but are not implemented in given AvbOps.\n");
1414       ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT;
1415       goto fail;
1416     }
1417   }
1418 
1419   /* Make sure passed-in AvbOps support verifying public keys and getting
1420    * rollback index location if not using a vbmeta partition.
1421    */
1422   if (flags & AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION) {
1423     if (ops->validate_public_key_for_partition == NULL) {
1424       avb_error(
1425           "AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION was passed but the "
1426           "validate_public_key_for_partition() operation isn't implemented.\n");
1427       ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT;
1428       goto fail;
1429     }
1430   } else {
1431     avb_assert(ops->validate_vbmeta_public_key != NULL);
1432   }
1433 
1434   slot_data = avb_calloc(sizeof(AvbSlotVerifyData));
1435   if (slot_data == NULL) {
1436     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1437     goto fail;
1438   }
1439   slot_data->vbmeta_images =
1440       avb_calloc(sizeof(AvbVBMetaData) * MAX_NUMBER_OF_VBMETA_IMAGES);
1441   if (slot_data->vbmeta_images == NULL) {
1442     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1443     goto fail;
1444   }
1445   slot_data->loaded_partitions =
1446       avb_calloc(sizeof(AvbPartitionData) * MAX_NUMBER_OF_LOADED_PARTITIONS);
1447   if (slot_data->loaded_partitions == NULL) {
1448     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1449     goto fail;
1450   }
1451 
1452   additional_cmdline_subst = avb_new_cmdline_subst_list();
1453   if (additional_cmdline_subst == NULL) {
1454     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1455     goto fail;
1456   }
1457 
1458   if (flags & AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION) {
1459     if (requested_partitions == NULL || requested_partitions[0] == NULL) {
1460       avb_fatal(
1461           "Requested partitions cannot be empty when using "
1462           "AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION");
1463       ret = AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT;
1464       goto fail;
1465     }
1466 
1467     /* No vbmeta partition, go through each of the requested partitions... */
1468     for (size_t n = 0; requested_partitions[n] != NULL; n++) {
1469       ret = load_and_verify_vbmeta(ops,
1470                                    requested_partitions,
1471                                    ab_suffix,
1472                                    flags,
1473                                    allow_verification_error,
1474                                    0 /* toplevel_vbmeta_flags */,
1475                                    0 /* rollback_index_location */,
1476                                    requested_partitions[n],
1477                                    avb_strlen(requested_partitions[n]),
1478                                    NULL /* expected_public_key */,
1479                                    0 /* expected_public_key_length */,
1480                                    slot_data,
1481                                    &algorithm_type,
1482                                    additional_cmdline_subst);
1483       if (!allow_verification_error && ret != AVB_SLOT_VERIFY_RESULT_OK) {
1484         goto fail;
1485       }
1486     }
1487 
1488   } else {
1489     /* Usual path, load "vbmeta"... */
1490     ret = load_and_verify_vbmeta(ops,
1491                                  requested_partitions,
1492                                  ab_suffix,
1493                                  flags,
1494                                  allow_verification_error,
1495                                  0 /* toplevel_vbmeta_flags */,
1496                                  0 /* rollback_index_location */,
1497                                  "vbmeta",
1498                                  avb_strlen("vbmeta"),
1499                                  NULL /* expected_public_key */,
1500                                  0 /* expected_public_key_length */,
1501                                  slot_data,
1502                                  &algorithm_type,
1503                                  additional_cmdline_subst);
1504     if (!allow_verification_error && ret != AVB_SLOT_VERIFY_RESULT_OK) {
1505       goto fail;
1506     }
1507   }
1508 
1509   if (!result_should_continue(ret)) {
1510     goto fail;
1511   }
1512 
1513   /* If things check out, mangle the kernel command-line as needed. */
1514   if (!(flags & AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION)) {
1515     if (avb_strcmp(slot_data->vbmeta_images[0].partition_name, "vbmeta") != 0) {
1516       avb_assert(
1517           avb_strcmp(slot_data->vbmeta_images[0].partition_name, "boot") == 0);
1518       using_boot_for_vbmeta = true;
1519     }
1520   }
1521 
1522   /* Byteswap top-level vbmeta header since we'll need it below. */
1523   avb_vbmeta_image_header_to_host_byte_order(
1524       (const AvbVBMetaImageHeader*)slot_data->vbmeta_images[0].vbmeta_data,
1525       &toplevel_vbmeta);
1526 
1527   /* Fill in |ab_suffix| field. */
1528   slot_data->ab_suffix = avb_strdup(ab_suffix);
1529   if (slot_data->ab_suffix == NULL) {
1530     ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1531     goto fail;
1532   }
1533 
1534   /* If verification is disabled, we are done ... we specifically
1535    * don't want to add any androidboot.* options since verification
1536    * is disabled.
1537    */
1538   if (toplevel_vbmeta.flags & AVB_VBMETA_IMAGE_FLAGS_VERIFICATION_DISABLED) {
1539     /* Since verification is disabled we didn't process any
1540      * descriptors and thus there's no cmdline... so set root= such
1541      * that the system partition is mounted.
1542      */
1543     avb_assert(slot_data->cmdline == NULL);
1544     // Devices with dynamic partitions won't have system partition.
1545     // Instead, it has a large super partition to accommodate *.img files.
1546     // See b/119551429 for details.
1547     if (has_system_partition(ops, ab_suffix)) {
1548       slot_data->cmdline =
1549           avb_strdup("root=PARTUUID=$(ANDROID_SYSTEM_PARTUUID)");
1550     } else {
1551       // The |cmdline| field should be a NUL-terminated string.
1552       slot_data->cmdline = avb_strdup("");
1553     }
1554     if (slot_data->cmdline == NULL) {
1555       ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1556       goto fail;
1557     }
1558   } else {
1559     /* If requested, manage dm-verity mode... */
1560     AvbHashtreeErrorMode resolved_hashtree_error_mode = hashtree_error_mode;
1561     if (hashtree_error_mode ==
1562         AVB_HASHTREE_ERROR_MODE_MANAGED_RESTART_AND_EIO) {
1563       AvbIOResult io_ret;
1564       io_ret = avb_manage_hashtree_error_mode(
1565           ops, flags, slot_data, &resolved_hashtree_error_mode);
1566       if (io_ret != AVB_IO_RESULT_OK) {
1567         ret = AVB_SLOT_VERIFY_RESULT_ERROR_IO;
1568         if (io_ret == AVB_IO_RESULT_ERROR_OOM) {
1569           ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1570         }
1571         goto fail;
1572       }
1573     }
1574     slot_data->resolved_hashtree_error_mode = resolved_hashtree_error_mode;
1575 
1576     /* Add options... */
1577     AvbSlotVerifyResult sub_ret;
1578     sub_ret = avb_append_options(ops,
1579                                  flags,
1580                                  slot_data,
1581                                  &toplevel_vbmeta,
1582                                  algorithm_type,
1583                                  hashtree_error_mode,
1584                                  resolved_hashtree_error_mode);
1585     if (sub_ret != AVB_SLOT_VERIFY_RESULT_OK) {
1586       ret = sub_ret;
1587       goto fail;
1588     }
1589   }
1590 
1591   /* Substitute $(ANDROID_SYSTEM_PARTUUID) and friends. */
1592   if (slot_data->cmdline != NULL && avb_strlen(slot_data->cmdline) != 0) {
1593     char* new_cmdline;
1594     new_cmdline = avb_sub_cmdline(ops,
1595                                   slot_data->cmdline,
1596                                   ab_suffix,
1597                                   using_boot_for_vbmeta,
1598                                   additional_cmdline_subst);
1599     if (new_cmdline != slot_data->cmdline) {
1600       if (new_cmdline == NULL) {
1601         ret = AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
1602         goto fail;
1603       }
1604       avb_free(slot_data->cmdline);
1605       slot_data->cmdline = new_cmdline;
1606     }
1607   }
1608 
1609   if (out_data != NULL) {
1610     *out_data = slot_data;
1611   } else {
1612     avb_slot_verify_data_free(slot_data);
1613   }
1614 
1615   avb_free_cmdline_subst_list(additional_cmdline_subst);
1616   additional_cmdline_subst = NULL;
1617 
1618   if (!allow_verification_error) {
1619     avb_assert(ret == AVB_SLOT_VERIFY_RESULT_OK);
1620   }
1621 
1622   return ret;
1623 
1624 fail:
1625   if (slot_data != NULL) {
1626     avb_slot_verify_data_free(slot_data);
1627   }
1628   if (additional_cmdline_subst != NULL) {
1629     avb_free_cmdline_subst_list(additional_cmdline_subst);
1630   }
1631   return ret;
1632 }
1633 
1634 void avb_slot_verify_data_free(AvbSlotVerifyData* data) {
1635   if (data->ab_suffix != NULL) {
1636     avb_free(data->ab_suffix);
1637   }
1638   if (data->cmdline != NULL) {
1639     avb_free(data->cmdline);
1640   }
1641   if (data->vbmeta_images != NULL) {
1642     size_t n;
1643     for (n = 0; n < data->num_vbmeta_images; n++) {
1644       AvbVBMetaData* vbmeta_image = &data->vbmeta_images[n];
1645       if (vbmeta_image->partition_name != NULL) {
1646         avb_free(vbmeta_image->partition_name);
1647       }
1648       if (vbmeta_image->vbmeta_data != NULL) {
1649         avb_free(vbmeta_image->vbmeta_data);
1650       }
1651     }
1652     avb_free(data->vbmeta_images);
1653   }
1654   if (data->loaded_partitions != NULL) {
1655     size_t n;
1656     for (n = 0; n < data->num_loaded_partitions; n++) {
1657       AvbPartitionData* loaded_partition = &data->loaded_partitions[n];
1658       if (loaded_partition->partition_name != NULL) {
1659         avb_free(loaded_partition->partition_name);
1660       }
1661       if (loaded_partition->data != NULL && !loaded_partition->preloaded) {
1662         sysmem_free((phys_addr_t)loaded_partition->data);
1663       }
1664     }
1665     avb_free(data->loaded_partitions);
1666   }
1667   avb_free(data);
1668 }
1669 
1670 const char* avb_slot_verify_result_to_string(AvbSlotVerifyResult result) {
1671   const char* ret = NULL;
1672 
1673   switch (result) {
1674     case AVB_SLOT_VERIFY_RESULT_OK:
1675       ret = "OK";
1676       break;
1677     case AVB_SLOT_VERIFY_RESULT_ERROR_OOM:
1678       ret = "ERROR_OOM";
1679       break;
1680     case AVB_SLOT_VERIFY_RESULT_ERROR_IO:
1681       ret = "ERROR_IO";
1682       break;
1683     case AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION:
1684       ret = "ERROR_VERIFICATION";
1685       break;
1686     case AVB_SLOT_VERIFY_RESULT_ERROR_ROLLBACK_INDEX:
1687       ret = "ERROR_ROLLBACK_INDEX";
1688       break;
1689     case AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED:
1690       ret = "ERROR_PUBLIC_KEY_REJECTED";
1691       break;
1692     case AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA:
1693       ret = "ERROR_INVALID_METADATA";
1694       break;
1695     case AVB_SLOT_VERIFY_RESULT_ERROR_UNSUPPORTED_VERSION:
1696       ret = "ERROR_UNSUPPORTED_VERSION";
1697       break;
1698     case AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_ARGUMENT:
1699       ret = "ERROR_INVALID_ARGUMENT";
1700       break;
1701       /* Do not add a 'default:' case here because of -Wswitch. */
1702   }
1703 
1704   if (ret == NULL) {
1705     avb_error("Unknown AvbSlotVerifyResult value.\n");
1706     ret = "(unknown)";
1707   }
1708 
1709   return ret;
1710 }
1711 
1712 void avb_slot_verify_data_calculate_vbmeta_digest(AvbSlotVerifyData* data,
1713                                                   AvbDigestType digest_type,
1714                                                   uint8_t* out_digest) {
1715   bool ret = false;
1716   size_t n;
1717 
1718   switch (digest_type) {
1719     case AVB_DIGEST_TYPE_SHA256: {
1720       AvbSHA256Ctx ctx;
1721 
1722       ctx.tot_len = 0;
1723       for (n = 0; n < data->num_vbmeta_images; n++)
1724         ctx.tot_len += data->vbmeta_images[n].vbmeta_size;
1725 
1726       avb_sha256_init(&ctx);
1727       for (n = 0; n < data->num_vbmeta_images; n++) {
1728         avb_sha256_update(&ctx,
1729                           data->vbmeta_images[n].vbmeta_data,
1730                           data->vbmeta_images[n].vbmeta_size);
1731       }
1732       avb_memcpy(out_digest, avb_sha256_final(&ctx), AVB_SHA256_DIGEST_SIZE);
1733       ret = true;
1734     } break;
1735 
1736     case AVB_DIGEST_TYPE_SHA512: {
1737       AvbSHA512Ctx ctx;
1738 
1739       ctx.tot_len = 0;
1740       for (n = 0; n < data->num_vbmeta_images; n++)
1741         ctx.tot_len += data->vbmeta_images[n].vbmeta_size;
1742 
1743       avb_sha512_init(&ctx);
1744       for (n = 0; n < data->num_vbmeta_images; n++) {
1745         avb_sha512_update(&ctx,
1746                           data->vbmeta_images[n].vbmeta_data,
1747                           data->vbmeta_images[n].vbmeta_size);
1748       }
1749       avb_memcpy(out_digest, avb_sha512_final(&ctx), AVB_SHA512_DIGEST_SIZE);
1750       ret = true;
1751     } break;
1752 
1753       /* Do not add a 'default:' case here because of -Wswitch. */
1754   }
1755 
1756   if (!ret) {
1757     avb_fatal("Unknown digest type");
1758   }
1759 }
1760