cli: Extract basic CLI init into cli_common
Move the first initialization steps (log callback setting,
version/banner printing, and libflashprog init) into a new
function cli_init(). This will be shared by other CLIs.
Change-Id: I9f19006aac18ffcdc05159957d58a2668c41e2b1
Signed-off-by: Nico Huber <nico.h@gmx.de>
Reviewed-on: https://review.sourcearcade.org/c/flashprog/+/72987
diff --git a/cli_common.c b/cli_common.c
index 787e47d..024881c 100644
--- a/cli_common.c
+++ b/cli_common.c
@@ -16,6 +16,7 @@
* GNU General Public License for more details.
*/
+#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
@@ -35,6 +36,34 @@
return 0;
}
+/* Ensure a file is open by means of fstat */
+static bool cli_check_file(FILE *file)
+{
+ struct stat statbuf;
+
+ if (fstat(fileno(file), &statbuf) < 0)
+ return false;
+ return true;
+}
+
+int cli_init(void)
+{
+ /*
+ * Safety-guard against a user who has (mistakenly) closed
+ * stdout or stderr before exec'ing flashprog. We disable
+ * logging in this case to prevent writing log data to a flash
+ * chip when a flash device gets opened with fd 1 or 2.
+ */
+ if (cli_check_file(stdout) && cli_check_file(stderr)) {
+ flashprog_set_log_callback((flashprog_log_callback *)&flashprog_print_cb);
+ }
+
+ print_version();
+ print_banner();
+
+ return flashprog_init(/* perform_selfcheck => */1);
+}
+
int cli_parse_log_args(struct log_args *const args, const int opt, const char *const optarg)
{
switch (opt) {