SWDEV-572301 - HIPCC does not handle -DSTR=\"foo\" #1083
<!--LLVM NEW CONTRIBUTOR COMMENT-->
Thank you for submitting a Pull Request (PR) to the LLVM Project!
This PR will be automatically labeled and the relevant teams will be notified.
If you wish to, you can add reviewers by using the "Reviewers" section on this page.
If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.
If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.
If you have further questions, they may be answered by the LLVM GitHub User Guide.
You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.
token = _tcstok_s(NULL, " ", &context);
argvcc.push_back(argv[i]);
NIT: Do we need all of them ?
I strongly suspect this doesn't handle spaces in quoted strings correctly? Like:
-DSTR=\"foo bar\"
Or escaped spaces? E.g.:
hipcc c:/foo\ bar/qux.cpp
Does hipcc have some testsuite that covers these scenarios?
I'm curious how does Clang handle this. Maybe we could borrow their approach.
I tried this simple program, which I think is doing what your patch is doing:
$ cat parse.cc
#include <windows.h>
#include <iostream>
#include <tchar.h>
#include <stdio.h>
int main (int argc, char **argv)
{
LPTSTR cmd = GetCommandLine();
TCHAR* context = NULL;
LPTSTR token = _tcstok_s(cmd, " ", &context);
for (int i = 0; i < argc; i++)
{
printf("token: %s\n", token);
token = _tcstok_s(NULL, " ", &context);
}
}
and I get this:
$ ./parse.exe \"foo bar\"
token: C:\msys2\home\alves\parse.exe
token: "\"foo"
token: "bar\""
This above is actually correct (unlike my previous comment). This one looks correct too:
$ ./parse.exe foo bar
token: C:\msys2\home\alves\parse.exe
token: foo
token: bar
But these two look odd:
$ ./parse.exe foo\ bar
token: C:\msys2\home\alves\parse.exe
token: "foo
$ ./parse.exe \"foo\ bar\"
token: C:\msys2\home\alves\parse.exe
token: "\"foo
Where did "bar" go? I think it isn't printed because the loop goes to argc, and argc == 2, while the _tcstok_s splits it in 3. But considering "bar" a separate argument in these last two cases would be incorrect, and argc==2 was what was actually right.
Takinga step back, are you sure the missing quotes were due to using argc/argv? If I compile this (with either clang-cl or Visual Studio):
#include <stdio.h>
int main (int argc, char **argv)
{
for (int i = 0; i < argc; i++)
{
printf("argv[%d]: %s\n", i, argv[i]);
}
}
I see this:
$ ./argv \"foo\"
argv[0]: C:\msys2\home\alves\argv.exe
argv[1]: "foo"
So the quotes seem to be preserved at that level?
Thanks @palves . I tried the case you are testing with (-DSTRING=\"foo bar\") with a HIPCC build to see if my patch handles this case. It doesn't. :-( So I tried a few things, but the core issue is that there is a space character in the argument and it would seem that the existing API functions on windows will still tokenize based on space characters. Which is why it divides foo and bar. Clang has the same issue, on windows. The solution, at least in CMD.exe (I haven't tried Powershell, but I suspect it has the same issue), is to wrap the command argument in double-quotes. So the hipcc command would look like this:
hipcc a.cpp "-DSTRING=\"foo bar\"" -c
I think because the CMD.exe shell will always require the double quote around arguments with spaces is something we can't avoid. And with my current patch if you do the above command it will compile successfully. However .... if I remove the "-c" option (to not call the linker and just compile to an object file), hipcc.exe will call the linker, and that does fail to compile/link. So my patch still needs some work. I'll try to post a fix to this, as well as address all comments today.
Thanks again for your review.
I'm using msys2 bash. As I said in my latest reply, -DSTR=\"foo bar\" _is_ supposed to be split at the space. To make it a single argument, the right way in msys2 is to pass -DSTR=\"foo\ bar\" (escape the space too). I'm not sure how to do it in CMD.exe. But whatever the environment, it shouldn't really matter -- we could create a testcase where a C program runs hipcc using CreateProcess to control exactly what the arguments are, and hipcc should process them correctly.
But this replacing-argument-parsing seems like a big red herring to me:
- I've showed with that little program in my previous reply that the Windows runtime does preserve the quotes in argv.
C:\str>type foo.cc
const char *str = STR;
C:\str>"c:/Program Files/AMD/ROCm/7.1/bin/clang" foo.cc -DSTR=\"foo\" -c
# no output, compiled successfully.
C:\str>"c:/Program Files/AMD/ROCm/7.1/bin/hipcc" foo.cc -DSTR=\"foo\" -c
foo.cc:1:19: error: use of undeclared identifier 'foo'
1 | const char *str = STR;
| ^~~
<command line>:2:13: note: expanded from macro 'STR'
2 | #define STR foo
| ^~~
1 error generated when compiling for gfx906.
failed to execute:""C:\Program Files\AMD\ROCm\7.1\bin\clang.exe" -O3 -x hip "foo.cc" -DSTR="foo" -c"
C:\msys2\home\alves\gdb\parse>
So how come HIPCC loses the quotes, but Clang does not? What does Clang do differently wrt to argc/argv? I suspect nothing, but I didn't check.
My initial investigation (in the internal Jira) suggests to me that the problem is that HIPCC's main/argv DOES see the quotes, but then they are lost when HIPCC invokes Clang:
$ hipcc a.cpp -DSTRING=\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\" -c -v
clang version 21.0.0git (git@github.com:Compute-Mirrors/llvm-project 5dcc622b51ecd499912c1062ce2b0ecda60d8e93)
Target: x86_64-pc-windows-msvc
Thread model: posix
InstalledDir: C:\Program Files\AMD\ROCm\7.1\bin
Found HIP installation: C:\Program Files\AMD\ROCm\7.1\, version 7.1.51803
"C:\\Program Files\\AMD\\ROCm\\7.1\\bin\\clang.exe" -cc1 -triple amdgcn-amd-amdhsa -aux-triple x86_64-pc-windows-msvc (...) -D STRING=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -D STRING=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx (...)
I'm still super confused how you got to a different conclusion.
The issue is that both clang.exe and hipcc.exe are independent applications using the same C++ runtime functions to retrieve command arguments (argv, argc). The hipcc.exe application needs to parse the arguments and then construct a (command) call to clang.exe (and lld.exe). So hipcc.exe uses the windows CLI, which processes the command arguments (can strip double quotes). Then it needs to construct a new command (to call clang.exe) and get the argument strings correct. We're essentially processing the command arguments twice, once by hipcc.exe and then we need to get those arguments into a command string to be processed again by clang.exe. And so my solution avoids using the existing C++ (argv, argc) in hipcc.exe, to try to keep the arguments strings intact so that hipcc.exe can properly construct the call/command to clang.
The solution I have here works for the simple case -DSTRING=\"foo\". But adding the space makes hipcc.exe treat ' bar\"' as a separate argument, and it actually drops the '-c' because in hipcc.cpp we're still using a for loop to iterate based on argc, and since it thinks ' bar\"' is a separate argument it stops processing arguments. I have a patch that I will post shortly that removes the argc for loop and just uses a while loop iterating until no more tokens are found in the argument string.
Good question. I think we do, but I'll see if I can drop some.
ok.
ok
So hipcc.exe uses the windows CLI, which processes the command arguments (can strip double quotes).
But I've already shown that the runtime does NOT strip double quotes! From what I shown in a previous comment:
$ ./argv \"foo\"
argv[0]: C:\msys2\home\alves\argv.exe
argv[1]: "foo"
Note
"foo" is quoted, while the printf has no explicit quotes!printf("argv[%d]: %s\n", i, argv[i]);
Can you show me an example where the runtime strips the quotes?
I looked at the HIPCC sources, and wow, there is so much wrong here, no surprise argument processing is broken.
The _tcstok_s approach here is just wrong, sorry. It tries to "re-parse" the Windows command line manually, but that is incorrect on Windows. _tcstok_s does not implement Windows argument parsing rules. Using _tcstok_s like that is a semantic break.
The problem is entirely on the other end -- the clang invocation. HIPCC already has a correctly parsed argc/argv. By throwing away argv and re-tokenizing GetCommandLine(), you lose correct quote handling, lose correct escaping, lose parity with POSIX behavior and create Windows-only divergence.
Looking at:
void HipBinAmd::executeHipCCCmd(vector<string> argv) {
the problem stands out quite clearly -- that is building an argument string by hand to pass to clang, without implementing Windows quoting rules! This code is broken on Windows, and it explains exactly the behavior we're seeing.
Even if you reconstructed argvcc perfectly, which the PR does not, the real bug still exists -- hipcc must re-escape arguments when converting argv => command-line string.
The comments in the file already hint at what needs to be done:
// TODO(hipcc): convert CMD to an array rather than a string
Also, the final clang invocation is using popen, in:
SystemCmdOut HipBinUtil::exec(const char* cmd, bool printConsole = false) const {
On Windows, _popen() does not execute a program directly. It instead does this:
cmd.exe /c <your string>
So the execution chain is:
hipcc
=> builds a single string CMD
=> _popen(CMD)
=> cmd.exe /c CMD
=> cmd.exe parses CMD
=> CreateProcess
=> clang CRT parses again
The correct fix is to stop building CMD as a string, instead build something like a std::vector<std::string>, or SmallVector<StringRef>, and pass it to llvm::sys::ExecuteAndWait. LLVM already implements correct Windows quoting internally, we should leverage it.
hipcc is is currently acting more like a shell, using shell execution APIs, while it should instead behave like a compiler driver. clang.exe itself is also a driver program that invokes other programs, and they already handled this problem. hipcc should be more like clang here, no need to reinvent the wheel.
_tcstok_s is not the right approach. The problem is on the clang invocation side.
Thanks @palves . A couple of things ...
Yup, options/argument processing in HIPCC is ... not ideal (to say the least). Reworking hipcc options processing has been on our plate for a number of years. The reason we're not doing that work is that we instead focused on moving functionality from hipcc into the Clang driver. Most of that has been done already, but there is still more to do.
"_LLVM already implements correct Windows quoting internally, we should leverage it._" I couldn't agree more, and the best way, IMO, to do that is to keep moving hipcc functionality into the Clang Driver, and then just have users call amdclang++.
Also if you look at the original issue in the ticket the problem is the user is trying to pass -DSTRING=\"foo\" and have the backslash and double-quote remain in the call to clang. So in your test:
$ ./argv \"foo\"
argv[0]: C:\msys2\home\alves\argv.exe
argv[1]: "foo"
you can see argv[1] has lost the \". This is the CLI (argv/argc) stripping the \ - which is what it is expected to do. And that is why I need call GetCommandLine(), to get the raw argument string.
If you have ROCm installed you can set HIPCC_VERBOSE=7, and then just call hipcc.exe and you will see the clang command hipcc generates.
Yup, options/argument processing in HIPCC is ... not ideal (to say the least). Reworking hipcc options processing has been on our plate for a number of years. The reason we're not doing that work is that we instead focused on moving functionality from hipcc into the Clang driver. Most of that has been done already, but there is still more to do.
OK, but current hipcc is completely fixable without being blocked by that.
Also if you look at the original issue in the ticket the problem is the user is trying to pass -DSTRING="foo" and
The user in the original issue is me! I reported this.
have the backslash and double-quote remain in the call to clang. So in your test:
> $ ./argv "foo"
argv[0]: C:\msys2\home\alves\argv.exe
argv[1]: "foo"
> you can see argv[1] has lost the ".
Huh, no, that's NOT what my test did. Here it is again:
$ ./argv \"foo\"
argv[0]: C:\msys2\home\alves\argv.exe
argv[1]: "foo"
The first line has \"foo\", not "foo". Just like in the subject of the Jira and in the subject of this PR.
And the last line shows that the program did NOT lose the quotes, if it had lost the quotes then that line would have been:
argv[1]: foo
instead. The quotes in that line are really part of the argv[1] string, not added by the printf.
This is the CLI (argv/argc) stripping the \ - which is what it is expected to do.
No, the CLI strips the quotes if you pass it "foo", not if you pass it \"foo\" ! That is completed expected.
And that is why I need call GetCommandLine(), to get the raw argument string.
This is completely the wrong thing to do. Really, e.g., _tcstok_s will incorrectly lose multi-spaces, like e.g., with
-DSTR=\"foo\ \ bar\"
Or even make hipcc misinterpret things that look like options when they are embedded in strings, like:
-DSTR=\"foo\ -M\"
Your patch would make hipcc think that that command line contains an "-M" argument. (-M is a random option that hipcc processes.)
The right thing to do is to pass the arguments to clang in a way that does not lose the quotes that are already in argv when you get to hipcc's main. Hipcc is currently losing the quotes because of the use of _popen, which runs the program via cmd.exe, and and by not implementing proper Windows escaping. Look at this comment in the code:
// Produce a version of $arg where characters significant to the shell are
// quoted. One could quote everything of course but don't bother for
// common characters such as alphanumerics.
// Do the quoting here because sometimes the $arg is changed in the loop
// Important to have all of '-Xlinker' in the set of unquoted characters.
// Windows needs different quoting, ignore for now
Specifically, look at the last line, which is already hinting you at what the problem is.
We should fix hipcc to not run clang using _popen, by either using llvm::sys::ExecuteAndWait instead, which escapes arguments correctly for Windows and then calls CreateProcessW (see flattenWindowsCommandLine and Execute in llvm/lib/Support/Windows/Program.inc), or if linking with llvm utils is too much at this point (now that I notice that hipcc does not link with llvm currently), just copy that bit of code into hipcc.
> If you have ROCm installed you can set HIPCC_VERBOSE=7, and then just call hipcc.exe and you will see the clang command hipcc generates.
Just like in the subject of the Jira
I see that the subject of the original Jira did not actually have the escapes (as I talk talking there about the literal characters, not what you type on the shell), though the description of the problem did, which may have contributed to the confusion. I've fix that now.
@palves I'm working on getting you a built HIP SDK package with these changes so that you can verify if the patch unblocks your work. I'd like to focus on getting you unblocked. And I suspect this patch should unblock you, at least temporarily, and shouldn't break anything else.
The reason I mentioned using the HIP_VERBOSE=7 env var is that it outputs the explicit clang command it uses, and you can try the clang command yourself in your CMD.exe session. This also allows you to see if hipcc.exe is generating the clang command incorrectly, because you can just copy and paste the clang command in your shell command.
For string commands that contain spaces, on Windows, you always need to encapsulate/wrap the string in double-quotes. So for your example -DSTR="\foo bar\", if you pass this to clang like this ( clang.exe a.cpp -c -DSTR="\foo bar\" ) you will get the same error you see in the ticket when you call hipcc.exe. You would need to give hipcc.exe the argument encapsulated with double-quotes like this hipcc.exe a.cpp -c "-DSTRING=\"foo bar\""
I do like the idea of building LLVM functionality into hipcc. In fact we have discussed doing this work before; specifically the CommandLine API. But our focus was to move hipcc functionality into the clang driver instead, and we pushed that work. We could consider it again. But for now I'd like to make sure you're not blocked.
!PSDB
PSDB Build Link: http://mlse-bdc-20dd129:8065/#/builders/11/builds/17
ping
_tcstok_s is not the right approach. The problem is on the clang invocation side.
If this is is problematic, and if @palves has a workaround already (I'm guess this is the case, given the age of this PR now), I'd vote to just close this one, and keep working on the hipcc removal effort.
chinmaydd
david-salinas
Windows only. HIPCC strips the escape chars on the command argument
Change-Id: Ie93f16e490ab91c5c3e85e7f59c4f54cdfeda357