+static TCHAR unquoted_imagepath[PATH_LENGTH];\r
+static TCHAR imagepath[PATH_LENGTH];\r
+static TCHAR imageargv0[PATH_LENGTH];\r
+\r
+void nssm_exit(int status) {\r
+ free_imports();\r
+ unsetup_utf8();\r
+ exit(status);\r
+}\r
+\r
+/* Are two strings case-insensitively equivalent? */\r
+int str_equiv(const TCHAR *a, const TCHAR *b) {\r
+ size_t len = _tcslen(a);\r
+ if (_tcslen(b) != len) return 0;\r
+ if (_tcsnicmp(a, b, len)) return 0;\r
+ return 1;\r
+}\r
+\r
+/* Convert a string to a number. */\r
+int str_number(const TCHAR *string, unsigned long *number, TCHAR **bogus) {\r
+ if (! string) return 1;\r
+\r
+ *number = _tcstoul(string, bogus, 0);\r
+ if (**bogus) return 2;\r
+\r
+ return 0;\r
+}\r
+\r
+int str_number(const TCHAR *string, unsigned long *number) {\r
+ TCHAR *bogus;\r
+ return str_number(string, number, &bogus);\r
+}\r
+\r
+/* Does a char need to be escaped? */\r
+static bool needs_escape(const TCHAR c) {\r
+ if (c == _T('"')) return true;\r
+ if (c == _T('&')) return true;\r
+ if (c == _T('%')) return true;\r
+ if (c == _T('^')) return true;\r
+ if (c == _T('<')) return true;\r
+ if (c == _T('>')) return true;\r
+ if (c == _T('|')) return true;\r
+ return false;\r
+}\r
+\r
+/* Does a char need to be quoted? */\r
+static bool needs_quote(const TCHAR c) {\r
+ if (c == _T(' ')) return true;\r
+ if (c == _T('\t')) return true;\r
+ if (c == _T('\n')) return true;\r
+ if (c == _T('\v')) return true;\r
+ if (c == _T('"')) return true;\r
+ if (c == _T('*')) return true;\r
+ return needs_escape(c);\r
+}\r
+\r
+/* https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/ */\r
+/* http://www.robvanderwoude.com/escapechars.php */\r
+int quote(const TCHAR *unquoted, TCHAR *buffer, size_t buflen) {\r
+ size_t i, j, n;\r
+ size_t len = _tcslen(unquoted);\r
+ if (len > buflen - 1) return 1;\r
+\r
+ bool escape = false;\r
+ bool quotes = false;\r
+\r
+ for (i = 0; i < len; i++) {\r
+ if (needs_escape(unquoted[i])) {\r
+ escape = quotes = true;\r
+ break;\r
+ }\r
+ if (needs_quote(unquoted[i])) quotes = true;\r
+ }\r
+ if (! quotes) {\r
+ memmove(buffer, unquoted, (len + 1) * sizeof(TCHAR));\r
+ return 0;\r
+ }\r
+\r
+ /* "" */\r
+ size_t quoted_len = 2;\r
+ if (escape) quoted_len += 2;\r