1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
7 #ifndef mozilla_AssembleCmdLine_h
8 #define mozilla_AssembleCmdLine_h
12 # include "mozilla/UniquePtr.h"
17 # ifdef MOZILLA_INTERNAL_API
18 # include "nsString.h"
19 # endif // MOZILLA_INTERNAL_API
23 // Out param `aWideCmdLine` must be free()d by the caller.
24 inline int assembleCmdLine(const char* const* aArgv
, wchar_t** aWideCmdLine
,
26 const char* const* arg
;
36 * Find out how large the command line buffer should be.
39 for (arg
= aArgv
; *arg
; ++arg
) {
41 * \ and " need to be escaped by a \. In the worst case,
42 * every character is a \ or ", so the string of length
43 * may double. If we quote an argument, that needs two ".
44 * Finally, we need a space between arguments, and
45 * a null byte at the end of command line.
47 cmdLineSize
+= 2 * strlen(*arg
) /* \ and " need to be escaped */
48 + 2 /* we quote every argument */
49 + 1; /* space in between, or final null */
51 p
= cmdLine
= (char*)malloc(cmdLineSize
* sizeof(char));
56 for (arg
= aArgv
; *arg
; ++arg
) {
57 /* Add a space to separates the arguments */
66 * If the argument is empty or contains white space, it needs to
69 if (**arg
== '\0' || strpbrk(*arg
, " \f\n\r\t\v")) {
80 } else if (*q
== '"') {
83 * Double the backslashes since they are followed
86 for (i
= 0; i
< 2 * numBackslashes
; i
++) {
91 /* To escape the quote */
97 * Backslashes are not followed by a quote, so
98 * don't need to double the backslashes.
100 for (i
= 0; i
< numBackslashes
; i
++) {
109 /* Now we are at the end of this argument */
110 if (numBackslashes
) {
112 * Double the backslashes if we have a quote string
113 * delimiter at the end.
118 for (i
= 0; i
< numBackslashes
; i
++) {
128 int numChars
= MultiByteToWideChar(aCodePage
, 0, cmdLine
, -1, nullptr, 0);
129 *aWideCmdLine
= (wchar_t*)malloc(numChars
* sizeof(wchar_t));
130 MultiByteToWideChar(aCodePage
, 0, cmdLine
, -1, *aWideCmdLine
, numChars
);
135 } // namespace mozilla
137 #endif // defined(XP_WIN)
139 #endif // mozilla_AssembleCmdLine_h