Correct quoting for pkg-config on Windows

Niklas Gürtler profclonk at gmx.de
Fri Jan 4 05:36:44 PST 2013


Dear readers,

quoting of arguments to command line programs works different on Windows
than on *nix, for example:

When executing MinGW's gcc.exe from cmd.exe:

Typed in cmd.exe        Gets transformed to
"foo.exe"               foo.exe
"fo\"o.exe"             fo"o.exe
"foo bar.exe"           foo bar.exe
"foo\bar.exe"           foo\bar.exe
"foo\\bar.exe"          foo\\bar.exe
"foo\\\"bar.exe"        foo\"bar.exe
"foo\\\bar.exe"         foo\\\bar.exe
"foo\\\\\\\"bar.exe"    foo\\\"bar.exe

Filenames containing " are of course invalid, but this is only to
demonstrate the quoting behaviour.Note that these example strings will
result in ONE SINGLE argument (i.e. ONE argv[] entry) to the program.

So i wrote the attached patch to let pkg-config output correctly quoted
strings on Windows.

Greetings,
Niklas Gürtler
-------------- next part --------------
--- parse_old.c	2012-08-20 20:17:58 +0000
+++ parse.c	2012-12-29 22:31:51 +0000
@@ -633,6 +633,39 @@
 
 static char *strdup_escape_shell(const char *s)
 {
+#ifdef G_OS_WIN32
+	size_t len = strlen (s);
+	size_t count = len;
+	size_t i, j;
+	char space = 0;
+	for (i = 0; i < len; i++) {
+		if (s[i] == '"' || s[i] == '\\') count++;
+		if (s[i] == ' ') space = 1;
+	}
+	char* r = g_malloc (len + count + 3);
+	
+	j = 0;
+	if (space) r[j++] = '"';
+	size_t bs = 0;
+	for (i = 0; i < len; i++) {
+		if (s[i] == '\\') {
+			bs++;
+		} else if (s[i] == '"') {
+			while (bs != 0) {
+				r [j++] = '\\';
+				bs--;
+			}
+			r [j++] = '\\';
+		} else {
+			bs = 0;
+		}
+		r[j++] = s[i];
+	}
+	if (space) r[j++] = '"';
+	r[j] = '\0';
+//	printf ("Escaped: %s\n%s\n", s, r);
+	return r;
+#else
 	size_t r_s = strlen(s)+10, c = 0;
 	char *r = g_malloc(r_s);
 	while (s[0]) {
@@ -657,6 +690,7 @@
 	}
 	r[c] = 0;
 	return r;
+#endif
 }
 
 static void _do_parse_libs (Package *pkg, int argc, char **argv)


More information about the pkg-config mailing list