From 2788b572a7419b1677e40c6a00e13c7b4e8970e7 Mon Sep 17 00:00:00 2001
From: David McCullough <davidm@snapgear.com>
Date: Mon, 9 Nov 2009 23:59:26 +0000
Subject: [PATCH] fix option order when invoking children

Poor getopt() implementations as found in many BSD/Darwin systems will
stop processing options after a non-option is encountered.  That means
ld-elf2flt has to be careful to not stick options after non-options when
executing sub children.  In a default setup, it will invoke `elf2flt` with
the output followed by the -a option which subsequently fails:
elf2flt: Can't open '-a': No such file or directory
---
 ld-elf2flt.c | 13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)

diff --git a/ld-elf2flt.c b/ld-elf2flt.c
index f9b0f1a..227c90b 100644
--- a/ld-elf2flt.c
+++ b/ld-elf2flt.c
@@ -76,7 +76,14 @@ static void append_sed(sed_commands_t *dst, const char *pattern,
 
 /* Execute an external program COMMAND.  Write its stdout to OUTPUT,
    unless that is NULL.  Pass the trailing NULL terminated list of
-   options, followed by all those in OPTIONS, if that is non-NULL.  */
+   options, followed by all those in OPTIONS, if that is non-NULL.
+   Order of options is important here as we may run on systems that
+   do not allow options after non-options (i.e. many BSDs).  So the
+   final command line will look like:
+   <command> [options] [... va args ...]
+   This is because [options] will (should?) never contain non-options,
+   while non-options will always be passed via the [va args].
+ */
 static int
 execute(const char *command, const char *output, const options_t *options, ...)
 {
@@ -92,12 +99,12 @@ execute(const char *command, const char *output, const options_t *options, ...)
 
 	init_options(&opts);
 	append_option(&opts, command);
+	if (options)
+		append_options(&opts, options);
 	va_start(args, options);
 	while ((opt = va_arg(args, const char *)))
 		append_option(&opts, opt);
 	va_end(args);
-	if (options)
-		append_options(&opts, options);
 	append_option(&opts, NULL);
 
 	fflush(stdout);
-- 
2.39.5