1 /*
2  * Copyright (c) 2023, Arm Limited and Contributors. All rights reserved.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
7 #include "cmd_update_image.h"
8 
9 #include <cstdio>
10 #include <cstdlib>
11 #include <cstring>
12 
13 #include "common/uuid/uuid.h"
14 
cmd_update_image(fwu_app & app,const std::string & img_type_uuid,const std::string & img_filename)15 int cmd_update_image(fwu_app &app, const std::string &img_type_uuid,
16 		     const std::string &img_filename)
17 {
18 	FILE *fp = fopen(img_filename.c_str(), "rb");
19 
20 	if (!fp) {
21 		printf("Error: failed to open image file: %s\n", img_filename.c_str());
22 		return -1;
23 	}
24 
25 	/* Get file size */
26 	fseek(fp, 0, SEEK_END);
27 	size_t img_size = ftell(fp);
28 	rewind(fp);
29 
30 	/* Allocate buffer for image data */
31 	uint8_t *img_buf = (uint8_t *)malloc(img_size);
32 
33 	if (!img_buf) {
34 		fclose(fp);
35 		printf("Error: failed to allocate image buffer\n");
36 		return -1;
37 	}
38 
39 	/* Read file contents into buffer */
40 	if (fread(img_buf, 1, img_size, fp)) {
41 		fclose(fp);
42 		free(img_buf);
43 		printf("Error: failed to read image file\n");
44 		return -1;
45 	}
46 
47 	fclose(fp);
48 
49 	/* Apply update */
50 	struct uuid_octets uuid;
51 
52 	uuid_guid_octets_from_canonical(&uuid, img_type_uuid.c_str());
53 
54 	int status = app.update_image(uuid, img_buf, img_size);
55 
56 	if (status)
57 		printf("Error: update image failed\n");
58 
59 	free(img_buf);
60 
61 	return status;
62 }
63