Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Changes.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
libhxcpp 6.1.0 (unreleased)
------------------------------------------------------------

* Fixed Sys.args() on Windows losing letters outside ASCII in a console program: main is given its arguments in the ANSI code page, and they were read as UTF-8. A letter of the code page, as the e acute of a Western one, came out as U+FFFD, and a letter the code page lacks was a "?" before the program started. An argument could end in the wrong place too: for a character it lacks Windows writes the nearest it has, which for a full width quote (U+FF02) is a quote. The arguments are now the C runtime's written as UTF-8 where the ANSI command line holds every character, and are split from the wide command line by the same rules where it does not, where a program linked with setargv.obj gets no wildcards expanded; a command line of ASCII is left as it was. A cppia script run by Cppia.exe gets the same arguments

libhxcpp 6.0.4
------------------------------------------------------------

Expand Down
8 changes: 8 additions & 0 deletions include/hx/HxcppMain.h
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,16 @@

extern int _hxcpp_argc;
extern char **_hxcpp_argv;
#if defined(HX_WINDOWS) && !defined(HX_WINRT)
char **_hxcpp_windows_utf8_argv(int *ioArgc, char **inArgv);
#endif
int main(int argc,char **argv)
{
#if defined(HX_WINDOWS) && !defined(HX_WINRT)
// The C runtime's arguments are in the ANSI code page, and Sys.args()
// reads _hxcpp_argv as UTF-8
argv = _hxcpp_windows_utf8_argv(&argc, argv);
#endif
_hxcpp_argc = argc;
_hxcpp_argv = argv;
#endif
Expand Down
157 changes: 157 additions & 0 deletions src/hx/StdLibs.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ typedef int64_t __int64;
#endif
#include <string>
#include <map>
#include <vector>
#include <stdio.h>
#include <time.h>
#include <clocale>
Expand All @@ -56,6 +57,162 @@ void __hx_stack_push_last_exception();
int _hxcpp_argc = 0;
char **_hxcpp_argv = 0;

#if defined(HX_WINDOWS) && !defined(HX_WINRT)

// One argument as UTF-8, kept for the life of the program as main's own are
static char *hxUtf8Argument(const wchar_t *inText, int inLength)
{
int bytes = inLength ? WideCharToMultiByte(CP_UTF8, 0, inText, inLength, 0, 0, 0, 0) : 0;
char *result = (char *)malloc(bytes + 1);
if (bytes)
WideCharToMultiByte(CP_UTF8, 0, inText, inLength, result, bytes, 0, 0);
result[bytes] = '\0';
return result;
}

// Text of the ANSI code page as UTF-16. False when there is none to give:
// the text is empty, or Windows will not convert it.
static bool hxWideFromAnsi(const char *inText, std::vector<wchar_t> &outUnits)
{
int length = (int)strlen(inText);
int count = length ? MultiByteToWideChar(CP_ACP, 0, inText, length, 0, 0) : 0;
if (count <= 0)
return false;
outUnits.resize(count);
return MultiByteToWideChar(CP_ACP, 0, inText, length, &outUnits[0], count) == count;
}

// Splits a command line by the rules of Microsoft's C runtime, "Parsing C
// command-line arguments" in its documentation, as main's own arguments are
static void hxSplitCommandLine(const wchar_t *inLine, std::vector< std::vector<wchar_t> > &outArguments)
{
const wchar_t *p = inLine;
std::vector<wchar_t> argument;

// The program's name: a quote only turns quoting on or off, and a
// backslash is a letter of a path
bool inQuotes = false;
for( ; *p && (inQuotes || (*p != ' ' && *p != '\t')); p++)
{
if (*p == '"')
inQuotes = !inQuotes;
else
argument.push_back(*p);
}
outArguments.push_back(argument);

inQuotes = false;
for(;;)
{
while(*p == ' ' || *p == '\t')
p++;
if (!*p)
break;

argument.clear();
for(;;)
{
// 2n backslashes and a quote are n backslashes, and the quote turns
// quoting on or off. 2n+1 and a quote are n backslashes and the
// quote itself. Backslashes before anything else are themselves.
size_t backslashes = 0;
for( ; *p == '\\'; p++)
backslashes++;
bool keep = true;
if (*p == '"')
{
if (backslashes % 2 == 0)
{
// Two quotes inside quotes are one quote, still inside
if (inQuotes && p[1] == '"')
p++;
else
{
keep = false;
inQuotes = !inQuotes;
}
}
backslashes /= 2;
}
argument.insert(argument.end(), backslashes, L'\\');

if (!*p || (!inQuotes && (*p == ' ' || *p == '\t')))
break;
if (keep)
argument.push_back(*p);
p++;
}
outArguments.push_back(argument);
}
}

// What a program's main does with its arguments before anything reads them.
//
// The C runtime splits the ANSI copy of the command line, so main is given
// bytes of the ANSI code page, and __get_args reads UTF-8: a letter of the
// code page came out as U+FFFD, and a letter it lacks was "?" before the
// program started.
//
// - A command line of ASCII is left as it is.
// - Where the ANSI copy still holds every character, the arguments stay the
// runtime's and are only written as UTF-8, so its splitting is kept, and
// its wildcard expansion in a program built for that.
// - Where it does not, the command line itself is split here, by the same
// rules. The ANSI copy is not safe even to split: Windows puts the nearest
// character it has in place of one it lacks, and for U+FF02 that is a
// quote, which moved where an argument ends. Nothing expands wildcards
// here, so a program built for that gets none on such a command line.
char **_hxcpp_windows_utf8_argv(int *ioArgc, char **inArgv)
{
const wchar_t *wide = GetCommandLineW();
const char *ansi = GetCommandLineA();
if (!wide || !ansi)
return inArgv;

int wideLength = 0;
bool ascii = true;
for( ; wide[wideLength]; wideLength++)
if (wide[wideLength] >= 0x80)
ascii = false;
if (ascii)
return inArgv;

std::vector<wchar_t> units;
bool ansiHoldsAll = hxWideFromAnsi(ansi, units) && units.size() == (size_t)wideLength &&
!memcmp(&units[0], wide, sizeof(wchar_t) * wideLength);

std::vector<char *> arguments;
if (ansiHoldsAll)
{
for(int i = 0; i < *ioArgc; i++)
{
// An argument that will not convert stays as the runtime gave it
if (hxWideFromAnsi(inArgv[i], units))
arguments.push_back( hxUtf8Argument(&units[0], (int)units.size()) );
else
arguments.push_back( inArgv[i] );
}
}
else
{
std::vector< std::vector<wchar_t> > split;
hxSplitCommandLine(wide, split);
for(size_t i = 0; i < split.size(); i++)
arguments.push_back( hxUtf8Argument(split[i].empty() ? L"" : &split[i][0], (int)split[i].size()) );
}

// Never freed, and a program may move _hxcpp_argv along it, as the cppia
// host does to hide its own options from a script
char **result = (char **)malloc(sizeof(char *) * (arguments.size() + 1));
for(size_t i = 0; i < arguments.size(); i++)
result[i] = arguments[i];
result[arguments.size()] = 0;
*ioArgc = (int)arguments.size();
return result;
}

#endif

namespace hx
{

Expand Down
80 changes: 80 additions & 0 deletions test/regression/ArgsWide/Main.hx
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import sys.io.Process;

using StringTools;

// Starts itself with arguments and checks that Sys.args() gives them back.
// On Windows main's arguments are in the ANSI code page: a letter of that
// code page came back as U+FFFD, its byte read as UTF-8, and a letter outside
// it as "?", lost before the program started.
class Main {
// Each argument as the code units of its String, so nothing here depends
// on how a pipe encodes text
static function codes(args:Array<String>):String {
return [for (arg in args) "[" + [for (i in 0...arg.length) arg.charCodeAt(i).hex(4)].join(" ") + "]"].join(" ");
}

static function check(what:String, args:Array<String>) {
var p = new Process(Sys.programPath(), ["--child"].concat(args));
var seen = p.stdout.readAll().toString().trim();
var code = p.exitCode();
p.close();
var expected = codes(args);
if (code != 0)
Sys.stderr().writeString('$what: exit code $code\n');
if (seen != expected)
Sys.stderr().writeString('$what: sent $expected, got $seen\n');
Sys.println('$what: ${code == 0 && seen == expected}');
}

// A command line as written, which Process does not quote again. Only
// Windows hands a program its command line whole, to split by rules of
// its own, so only there is anything to check
static function checkLine(what:String, tail:String, expected:Array<String>) {
var ok = true;
if (Sys.systemName() == "Windows") {
var p = new Process('"${Sys.programPath()}" --child $tail');
var seen = p.stdout.readAll().toString().trim();
var code = p.exitCode();
p.close();
ok = code == 0 && seen == codes(expected);
if (!ok)
Sys.stderr().writeString('$what: wanted ${codes(expected)}, got $seen, exit code $code\n');
}
Sys.println('$what: $ok');
}

static function main() {
var args = Sys.args();
if (args[0] == "--child") {
Sys.println(codes(args.slice(1)));
return;
}

check("ASCII arguments", ["a", "-b", "c d"]);
// e acute, which the Western code pages hold
check("a letter of the ANSI code page", ["caf\u00E9"]);
// Japanese, Russian and Greek: no one code page holds all three
check("letters of other code pages", ["\u65E5\u672C", "\u043F\u0440\u0438\u0432\u0435\u0442", "\u03B1\u03B2"]);
check("a character above U+FFFF", ["\u{1F600}"]);
check("a space beside such a letter", ["\u00E9 \u65E5"]);
check("a quote beside such a letter", ["\u00E9\"\u65E5"]);
check("a backslash before a quote", ["\u00E9\\\"\u65E5"]);
check("a last backslash", ["\u65E5\\", "\u00E9"]);
check("a space and a last backslash", ["\u00E9 \u65E5\\", "a"]);
check("an empty argument among them", ["\u00E9", "", "\u65E5"]);
check("an argument that starts with #", ["#\u00E9", "\u65E5"]);
// A full width quote and an ideographic space: the code page's nearest
// characters are a quote, which ended the argument early, and a space
check("a letter whose nearest ANSI character is a quote", ["a\uFF02 b", "c"]);
check("a letter whose nearest ANSI character is a space", ["a\u3000b", "c"]);

// The C runtime's rules for a command line, which hold for one it
// cannot split itself because the ANSI code page lacks a letter of it
checkLine("two quotes inside quotes are one quote", '"\u65E5""\u672C" a', ["\u65E5\"\u672C", "a"]);
checkLine("two backslashes and a quote are a backslash", '\u65E5\\\\"\u672C a"', ["\u65E5\\\u672C a"]);
checkLine("three backslashes and a quote are a backslash and a quote", '\u65E5\\\\\\"\u672C a', ["\u65E5\\\"\u672C", "a"]);
checkLine("backslashes before a letter are themselves", '\u65E5\\\\\u672C', ["\u65E5\\\\\u672C"]);
checkLine("a tab ends an argument", '\u65E5\t\u672C', ["\u65E5", "\u672C"]);
checkLine("a quote left open takes the rest", '"\u65E5 \u672C', ["\u65E5 \u672C"]);
}
}
2 changes: 2 additions & 0 deletions test/regression/ArgsWide/build.hxml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-m Main
--cpp bin
19 changes: 19 additions & 0 deletions test/regression/ArgsWide/stdout.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
ASCII arguments: true
a letter of the ANSI code page: true
letters of other code pages: true
a character above U+FFFF: true
a space beside such a letter: true
a quote beside such a letter: true
a backslash before a quote: true
a last backslash: true
a space and a last backslash: true
an empty argument among them: true
an argument that starts with #: true
a letter whose nearest ANSI character is a quote: true
a letter whose nearest ANSI character is a space: true
two quotes inside quotes are one quote: true
two backslashes and a quote are a backslash: true
three backslashes and a quote are a backslash and a quote: true
backslashes before a letter are themselves: true
a tab ends an argument: true
a quote left open takes the rest: true
2 changes: 2 additions & 0 deletions test/regression/CppiaHostArgs/Main.hx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ class Main {
check("a script sees the arguments after it", [script, "a", "-b"], "[a,-b]");
check("a -jit before the script is the host's", ["-jit", script, "a", "-b"], "[a,-b]");
check("a -jit after the script is the script's too", [script, "x", "-jit"], "[x,-jit]");
// On Windows the host's main is given these in the ANSI code page
check("a script sees letters outside ASCII", [script, "caf\u00E9", "\u65E5\u672C"], "[caf\u00E9,\u65E5\u672C]");
var fingerprint = run(["-fingerprint"]);
Sys.println('-fingerprint prints 16 hex digits: ${~/^[0-9a-f]{16}$/.match(fingerprint)}');
}
Expand Down
1 change: 1 addition & 0 deletions test/regression/CppiaHostArgs/stdout.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ a script run alone sees no arguments: true
a script sees the arguments after it: true
a -jit before the script is the host's: true
a -jit after the script is the script's too: true
a script sees letters outside ASCII: true
-fingerprint prints 16 hex digits: true
1 change: 1 addition & 0 deletions test/regression/emscripten-skip.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
# Emscripten job fails.

AnonConcurrentString: threads
ArgsWide: processes
ArrayConcurrentString: threads
AtomicFieldSpinSafePoint: threads (std::thread, which needs a pthreads build)
AtomicSafePointUnregisteredThread: threads (std::thread, which needs a pthreads build)
Expand Down
Loading