fdtgrep: Improve error handling with invalid device tree

This tool requires that the aliases node be the first node in the tree. But
when it is not, it does not handle things gracefully. In fact it crashes.

Fix this, and add a more helpful error message.

Signed-off-by: Simon Glass <sjg@chromium.org>
Reported-by: Masahiro Yamada <yamada.masahiro@socionext.com>
diff --git a/tools/fdtgrep.c b/tools/fdtgrep.c
index 67aa41a..8d3fef4 100644
--- a/tools/fdtgrep.c
+++ b/tools/fdtgrep.c
@@ -660,6 +660,8 @@
 		if (!ret)
 			count++;
 	}
+	if (ret && ret != -FDT_ERR_NOTFOUND)
+		return ret;
 
 	/* Find all the aliases and add those regions back in */
 	if (disp->add_aliases && count < max_regions) {
@@ -667,7 +669,11 @@
 
 		new_count = fdt_add_alias_regions(fdt, region, count,
 						  max_regions, &state);
-		if (new_count <= max_regions) {
+		if (new_count == -FDT_ERR_NOTFOUND) {
+			/* No alias node found */
+		} else if (new_count < 0) {
+			return new_count;
+		} else if (new_count <= max_regions) {
 			/*
 			* The alias regions will now be at the end of the list.
 			* Sort the regions by offset to get things into the
@@ -679,9 +685,6 @@
 		}
 	}
 
-	if (ret != -FDT_ERR_NOTFOUND)
-		return ret;
-
 	return count;
 }
 
@@ -807,6 +810,9 @@
 				disp->flags);
 		if (count < 0) {
 			report_error("fdt_find_regions", count);
+			if (count == -FDT_ERR_BADLAYOUT)
+				fprintf(stderr,
+					"/aliases node must come before all other nodes\n");
 			return -1;
 		}
 		if (count <= max_regions)