File:  [ELWIX - Embedded LightWeight unIX -] / embedtools / src / imgupd.c
Revision 1.1.2.1: download - view: text, annotated - select for diffs - revision graph
Wed Feb 5 12:37:31 2014 UTC (10 years, 9 months ago) by misho
Branches: tools2_0
initial commit for imgupd

#include "global.h"


char imgName[PATH_MAX], imgFile[PATH_MAX];
off_t imgSize, fSize, iSize;
int Verbose;
extern char compiled[], compiledby[], compilehost[];

static void
Usage()
{

	printf(	"IMGUPD is tool for management of images\n"
		"=== %s === %s@%s ===\n\n"
		"  Syntax: imgupd [options] <image_file>\n\n"
		"\t-v\t\tVerbose ...\n"
		"\t-s <size>\tStorage size\n"
		"\t-f <devfile>\tStorage file name\n"
		"\n", compiled, compiledby, compilehost);
}

static int
EmptyStore(int img)
{
	register int i;
	u_char buf[IMGBLOCK_SIZE];
	ssize_t wlen;

	memset(buf, 0, sizeof buf);
	for (i = 0; i < howmany(imgSize, IMGBLOCK_SIZE); i++)
		if ((wlen = write(img, buf, sizeof buf)) == -1 || 
				wlen != sizeof buf) {
			printf("Error:: at chunk %d init %d bytes, should be %u", 
					i, wlen, sizeof buf);
			return -1;
		} else
			VERB(1) printf("+Written chunk #%d\n", i);

	iSize = lseek(img, 0, SEEK_END);
	return iSize;
}

int
main(int argc, char **argv)
{
	char ch;
	int fd, img;

	while ((ch = getopt(argc, argv, "hvs:f:")) != -1)
		switch (ch) {
			case 'f':
				strlcpy(imgName, optarg, sizeof imgName);
				break;
			case 's':
				imgSize = strtoll(optarg, NULL, 0);
				if (!imgSize) {
					Usage();
					return 1;
				}
				break;
			case 'v':
				Verbose++;
				break;
			case 'h':
			default:
				Usage();
				return 1;
		}
	argc -= optind;
	argv += optind;
	if (!argc || !*imgName || !imgSize) {
		Usage();
		return 1;
	} else
		strlcpy(imgFile, *argv, sizeof imgFile);

	VERB(1) printf("imgSize=%llu imgName=%s imgFile=%s\n", imgSize, imgName, imgFile);

	/* open image file */
	fd = open(imgFile, O_RDONLY);
	if (fd == -1) {
		ESYSERR(0);
		return 2;
	} else
		fSize = lseek(fd, 0, SEEK_END);
	if (fSize == -1 || fSize > imgSize) {
		close(fd);
		printf("Error:: file size %llu is greater from storage size %llu\n", 
				fSize, imgSize);
		return 2;
	} else
		lseek(fd, 0, SEEK_SET);

	/* open storage device */
	img = open(imgName, O_RDWR | O_CREAT, 0644);
	if (img == -1) {
		ESYSERR(0);
		close(fd);
		return 3;
	}
	if (EmptyStore(img) == -1 || iSize < imgSize) {
		close(fd);
		close(img);
		unlink(imgName);
		printf("Error:: current storage size %llu is smaller from storage size %llu\n", 
				iSize, imgSize);
		return 3;
	} else
		lseek(img, 0, SEEK_SET);

	close(img);
	close(fd);
	return 0;
}

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>