153642Sguido// SPDX-License-Identifier: GPL-2.0-or-later
260854Sdarrenr/*
353642Sguido * (C) Copyright David Gibson <dwg@au1.ibm.com>, IBM Corporation.  2005.
453642Sguido */
553642Sguido
653642Sguido#include "dtc.h"
753642Sguido
853642Sguido#include <dirent.h>
953642Sguido#include <sys/stat.h>
1057126Sguido
1153642Sguidostatic struct node *read_fstree(const char *dirname)
1253642Sguido{
1353642Sguido	DIR *d;
1453642Sguido	struct dirent *de;
1553642Sguido	struct stat st;
1653642Sguido	struct node *tree;
1753642Sguido
1853642Sguido	d = opendir(dirname);
1953642Sguido	if (!d)
2053642Sguido		die("Couldn't opendir() \"%s\": %s\n", dirname, strerror(errno));
2160854Sdarrenr
2260854Sdarrenr	tree = build_node(NULL, NULL, NULL);
2360854Sdarrenr
2460854Sdarrenr	while ((de = readdir(d)) != NULL) {
2553642Sguido		char *tmpname;
2653642Sguido
2753642Sguido		if (streq(de->d_name, ".")
2853642Sguido		    || streq(de->d_name, ".."))
2953642Sguido			continue;
3053642Sguido
3153642Sguido		tmpname = join_path(dirname, de->d_name);
3253642Sguido
3353642Sguido		if (stat(tmpname, &st) < 0)
3453642Sguido			die("stat(%s): %s\n", tmpname, strerror(errno));
3560854Sdarrenr
3653642Sguido		if (S_ISREG(st.st_mode)) {
3753642Sguido			struct property *prop;
3853642Sguido			FILE *pfile;
3953642Sguido
4053642Sguido			pfile = fopen(tmpname, "rb");
4153642Sguido			if (! pfile) {
4253642Sguido				fprintf(stderr,
4353642Sguido					"WARNING: Cannot open %s: %s\n",
4453642Sguido					tmpname, strerror(errno));
4553642Sguido			} else {
4653642Sguido				prop = build_property(xstrdup(de->d_name),
4753642Sguido						      data_copy_file(pfile,
4853642Sguido								     st.st_size),
4953642Sguido						      NULL);
5057096Sguido				add_property(tree, prop);
5153642Sguido				fclose(pfile);
5253642Sguido			}
5353642Sguido		} else if (S_ISDIR(st.st_mode)) {
5453642Sguido			struct node *newchild;
5553642Sguido
5653642Sguido			newchild = read_fstree(tmpname);
5753642Sguido			newchild = name_node(newchild, xstrdup(de->d_name));
5853642Sguido			add_child(tree, newchild);
5953642Sguido		}
6053642Sguido
6153642Sguido		free(tmpname);
6253642Sguido	}
6353642Sguido
6453642Sguido	closedir(d);
6553642Sguido	return tree;
6653642Sguido}
6753642Sguido
6853642Sguidostruct dt_info *dt_from_fs(const char *dirname)
6953642Sguido{
7053642Sguido	struct node *tree;
7153642Sguido
7253642Sguido	tree = read_fstree(dirname);
7353642Sguido	tree = name_node(tree, "");
7453642Sguido
7553642Sguido	return build_dt_info(DTSF_V1, NULL, tree, guess_boot_cpuid(tree));
7653642Sguido}
7753642Sguido