Home | History | Annotate | Download | only in utils
      1 // Copyright 2014 The Android Open Source Project
      2 //
      3 // This software is licensed under the terms of the GNU General Public
      4 // License version 2, as published by the Free Software Foundation, and
      5 // may be copied, distributed, and modified under those terms.
      6 //
      7 // This program is distributed in the hope that it will be useful,
      8 // but WITHOUT ANY WARRANTY; without even the implied warranty of
      9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     10 // GNU General Public License for more details.
     11 
     12 #include "android/utils/win32_cmdline_quote.h"
     13 
     14 #include <string.h>
     15 
     16 #include "android/utils/stralloc.h"
     17 #include "android/utils/system.h"
     18 
     19 char* win32_cmdline_quote(const char* param) {
     20   // If |param| doesn't contain any problematic character, just return it as-is.
     21   size_t n = strcspn(param, " \t\v\n\"");
     22   if (param[n] == '\0')
     23       return ASTRDUP(param);
     24 
     25   // Otherwise, we need to quote some of the characters.
     26   stralloc_t out = STRALLOC_INIT;
     27 
     28   // Add initial quote.
     29   stralloc_add_c(&out, '"');
     30 
     31   n = 0;
     32   while (param[n]) {
     33       size_t num_backslashes = 0;
     34       while (param[n] == '\\') {
     35           n++;
     36           num_backslashes++;
     37       }
     38 
     39       if (!param[n]) {
     40           // End of string, if there are backslashes, double them.
     41           for (; num_backslashes > 0; num_backslashes--)
     42               stralloc_add_str(&out, "\\\\");
     43           break;
     44       }
     45 
     46       if (param[n] == '"') {
     47           // Escape all backslashes as well as the quote that follows them.
     48           for (; num_backslashes > 0; num_backslashes--)
     49               stralloc_add_str(&out, "\\\\");
     50           stralloc_add_str(&out, "\\\"");
     51       } else {
     52           for (; num_backslashes > 0; num_backslashes--)
     53               stralloc_add_c(&out, '\\');
     54           stralloc_add_c(&out, param[n]);
     55       }
     56       n++;
     57   }
     58 
     59   // Add final quote.
     60   stralloc_add_c(&out, '"');
     61 
     62   char* result = ASTRDUP(stralloc_cstr(&out));
     63   stralloc_reset(&out);
     64   return result;
     65 }
     66