1 /* 2 * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 #include <stdlib.h> 27 #include <stdio.h> 28 #include <assert.h> 29 #include <sys/stat.h> 30 #include <ctype.h> 31 32 #ifdef DEBUG_ARGFILE 33 #ifndef NO_JNI 34 #define NO_JNI 35 #endif 36 #define JLI_ReportMessage(...) printf(__VA_ARGS__) 37 #define JDK_JAVA_OPTIONS "JDK_JAVA_OPTIONS" 38 int IsWhiteSpaceOption(const char* name) { return 1; } 39 #else 40 #include "java.h" 41 #include "jni.h" 42 #endif 43 44 #include "jli_util.h" 45 #include "emessages.h" 46 47 #define MAX_ARGF_SIZE 0x7fffffffL 48 49 static char* clone_substring(const char *begin, size_t len) { 50 char *rv = (char *) JLI_MemAlloc(len + 1); 51 memcpy(rv, begin, len); 52 rv[len] = '\0'; 53 return rv; 54 } 55 56 enum STATE { 57 FIND_NEXT, 58 IN_COMMENT, 59 IN_QUOTE, 60 IN_ESCAPE, 61 SKIP_LEAD_WS, 62 IN_TOKEN 63 }; 64 65 typedef struct { 66 enum STATE state; 67 const char* cptr; 68 const char* eob; 69 char quote_char; 70 JLI_List parts; 71 } __ctx_args; 72 73 #define NOT_FOUND -1 74 static int firstAppArgIndex = NOT_FOUND; 75 76 static jboolean expectingNoDashArg = JNI_FALSE; 77 // Initialize to 1, as the first argument is the app name and not preprocessed 78 static size_t argsCount = 1; 79 static jboolean stopExpansion = JNI_FALSE; 80 static jboolean relaunch = JNI_FALSE; 81 82 /* 83 * Prototypes for internal functions. 84 */ 85 static jboolean expand(JLI_List args, const char *str, const char *var_name); 86 87 JNIEXPORT void JNICALL 88 JLI_InitArgProcessing(jboolean hasJavaArgs, jboolean disableArgFile) { 89 // No expansion for relaunch 90 if (argsCount != 1) { 91 relaunch = JNI_TRUE; 92 stopExpansion = JNI_TRUE; 93 argsCount = 1; 94 } else { 95 stopExpansion = disableArgFile; 96 } 97 98 expectingNoDashArg = JNI_FALSE; 99 100 // for tools, this value remains 0 all the time. 101 firstAppArgIndex = hasJavaArgs ? 0: NOT_FOUND; 102 } 103 104 JNIEXPORT int JNICALL 105 JLI_GetAppArgIndex() { 106 // Will be 0 for tools 107 return firstAppArgIndex; 108 } 109 110 static void checkArg(const char *arg) { 111 size_t idx = 0; 112 argsCount++; 113 114 // All arguments arrive here must be a launcher argument, 115 // ie. by now, all argfile expansions must have been performed. 116 if (*arg == '-') { 117 expectingNoDashArg = JNI_FALSE; 118 if (IsWhiteSpaceOption(arg)) { 119 // expect an argument 120 expectingNoDashArg = JNI_TRUE; 121 122 if (JLI_StrCmp(arg, "-jar") == 0 || 123 JLI_StrCmp(arg, "--module") == 0 || 124 JLI_StrCmp(arg, "-m") == 0) { 125 // This is tricky, we do expect NoDashArg 126 // But that is considered main class to stop expansion 127 expectingNoDashArg = JNI_FALSE; 128 // We can not just update the idx here because if -jar @file 129 // still need expansion of @file to get the argument for -jar 130 } 131 } else if (JLI_StrCmp(arg, "--disable-@files") == 0) { 132 stopExpansion = JNI_TRUE; 133 } 134 } else { 135 if (!expectingNoDashArg) { 136 // this is main class, argsCount is index to next arg 137 idx = argsCount; 138 } 139 expectingNoDashArg = JNI_FALSE; 140 } 141 // only update on java mode and not yet found main class 142 if (firstAppArgIndex == NOT_FOUND && idx != 0) { 143 firstAppArgIndex = (int) idx; 144 } 145 } 146 147 /* 148 [\n\r] +------------+ +------------+ [\n\r] 149 +---------+ IN_COMMENT +<------+ | IN_ESCAPE +---------+ 150 | +------------+ | +------------+ | 151 | [#] ^ |[#] ^ | | 152 | +----------+ | [\\]| |[^\n\r] | 153 v | | | v | 154 +------------+ [^ \t\n\r\f] +------------+['"]> +------------+ | 155 | FIND_NEXT +-------------->+ IN_TOKEN +-----------+ IN_QUOTE + | 156 +------------+ +------------+ <[quote]+------------+ | 157 | ^ | | ^ ^ | 158 | | [ \t\n\r\f]| [\n\r]| | |[^ \t\n\r\f]v 159 | +--------------------------+-----------------------+ | +--------------+ 160 | ['"] | | SKIP_LEAD_WS | 161 +---------------------------------------------------------+ +--------------+ 162 */ 163 static char* nextToken(__ctx_args *pctx) { 164 const char* nextc = pctx->cptr; 165 const char* const eob = pctx->eob; 166 const char* anchor = nextc; 167 char *token; 168 169 for (; nextc < eob; nextc++) { 170 register char ch = *nextc; 171 172 // Skip white space characters 173 if (pctx->state == FIND_NEXT || pctx->state == SKIP_LEAD_WS) { 174 while (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t' || ch == '\f') { 175 nextc++; 176 if (nextc >= eob) { 177 return NULL; 178 } 179 ch = *nextc; 180 } 181 pctx->state = (pctx->state == FIND_NEXT) ? IN_TOKEN : IN_QUOTE; 182 anchor = nextc; 183 // Deal with escape sequences 184 } else if (pctx->state == IN_ESCAPE) { 185 // concatenation directive 186 if (ch == '\n' || ch == '\r') { 187 pctx->state = SKIP_LEAD_WS; 188 } else { 189 // escaped character 190 char* escaped = (char*) JLI_MemAlloc(2 * sizeof(char)); 191 escaped[1] = '\0'; 192 switch (ch) { 193 case 'n': 194 escaped[0] = '\n'; 195 break; 196 case 'r': 197 escaped[0] = '\r'; 198 break; 199 case 't': 200 escaped[0] = '\t'; 201 break; 202 case 'f': 203 escaped[0] = '\f'; 204 break; 205 default: 206 escaped[0] = ch; 207 break; 208 } 209 JLI_List_add(pctx->parts, escaped); 210 pctx->state = IN_QUOTE; 211 } 212 // anchor to next character 213 anchor = nextc + 1; 214 continue; 215 // ignore comment to EOL 216 } else if (pctx->state == IN_COMMENT) { 217 while (ch != '\n' && ch != '\r') { 218 nextc++; 219 if (nextc > eob) { 220 return NULL; 221 } 222 ch = *nextc; 223 } 224 pctx->state = FIND_NEXT; 225 continue; 226 } 227 228 assert(pctx->state != IN_ESCAPE); 229 assert(pctx->state != FIND_NEXT); 230 assert(pctx->state != SKIP_LEAD_WS); 231 assert(pctx->state != IN_COMMENT); 232 233 switch(ch) { 234 case ' ': 235 case '\t': 236 case '\f': 237 if (pctx->state == IN_QUOTE) { 238 continue; 239 } 240 // fall through 241 case '\n': 242 case '\r': 243 if (pctx->parts->size == 0) { 244 token = clone_substring(anchor, nextc - anchor); 245 } else { 246 JLI_List_addSubstring(pctx->parts, anchor, nextc - anchor); 247 token = JLI_List_combine(pctx->parts); 248 JLI_List_free(pctx->parts); 249 pctx->parts = JLI_List_new(4); 250 } 251 pctx->cptr = nextc + 1; 252 pctx->state = FIND_NEXT; 253 return token; 254 case '#': 255 if (pctx->state == IN_QUOTE) { 256 continue; 257 } 258 pctx->state = IN_COMMENT; 259 break; 260 case '\\': 261 if (pctx->state != IN_QUOTE) { 262 continue; 263 } 264 JLI_List_addSubstring(pctx->parts, anchor, nextc - anchor); 265 pctx->state = IN_ESCAPE; 266 break; 267 case '\'': 268 case '"': 269 if (pctx->state == IN_QUOTE && pctx->quote_char != ch) { 270 // not matching quote 271 continue; 272 } 273 // partial before quote 274 if (anchor != nextc) { 275 JLI_List_addSubstring(pctx->parts, anchor, nextc - anchor); 276 } 277 // anchor after quote character 278 anchor = nextc + 1; 279 if (pctx->state == IN_TOKEN) { 280 pctx->quote_char = ch; 281 pctx->state = IN_QUOTE; 282 } else { 283 pctx->state = IN_TOKEN; 284 } 285 break; 286 default: 287 break; 288 } 289 } 290 291 assert(nextc == eob); 292 if (anchor != nextc) { 293 // not yet return until end of stream, we have part of a token. 294 JLI_List_addSubstring(pctx->parts, anchor, nextc - anchor); 295 } 296 return NULL; 297 } 298 299 static JLI_List readArgFile(FILE *file) { 300 char buf[4096]; 301 JLI_List rv; 302 __ctx_args ctx; 303 size_t size; 304 char *token; 305 306 ctx.state = FIND_NEXT; 307 ctx.parts = JLI_List_new(4); 308 // initialize to avoid -Werror=maybe-uninitialized issues from gcc 7.3 onwards. 309 ctx.quote_char = '"'; 310 311 /* arbitrarily pick 8, seems to be a reasonable number of arguments */ 312 rv = JLI_List_new(8); 313 314 while (!feof(file)) { 315 size = fread(buf, sizeof(char), sizeof(buf), file); 316 if (ferror(file)) { 317 JLI_List_free(rv); 318 return NULL; 319 } 320 321 /* nextc is next character to read from the buffer 322 * eob is the end of input 323 * token is the copied token value, NULL if no a complete token 324 */ 325 ctx.cptr = buf; 326 ctx.eob = buf + size; 327 token = nextToken(&ctx); 328 while (token != NULL) { 329 checkArg(token); 330 JLI_List_add(rv, token); 331 token = nextToken(&ctx); 332 } 333 } 334 335 // remaining partial token 336 if (ctx.state == IN_TOKEN || ctx.state == IN_QUOTE) { 337 if (ctx.parts->size != 0) { 338 JLI_List_add(rv, JLI_List_combine(ctx.parts)); 339 } 340 } 341 JLI_List_free(ctx.parts); 342 343 return rv; 344 } 345 346 /* 347 * if the arg represent a file, that is, prefix with a single '@', 348 * return a list of arguments from the file. 349 * otherwise, return NULL. 350 */ 351 static JLI_List expandArgFile(const char *arg) { 352 FILE *fptr; 353 struct stat st; 354 JLI_List rv; 355 356 /* failed to access the file */ 357 if (stat(arg, &st) != 0) { 358 JLI_ReportMessage(CFG_ERROR6, arg); 359 exit(1); 360 } 361 362 if (st.st_size > MAX_ARGF_SIZE) { 363 JLI_ReportMessage(CFG_ERROR10, MAX_ARGF_SIZE); 364 exit(1); 365 } 366 367 fptr = fopen(arg, "r"); 368 /* arg file cannot be openned */ 369 if (fptr == NULL) { 370 JLI_ReportMessage(CFG_ERROR6, arg); 371 exit(1); 372 } 373 374 rv = readArgFile(fptr); 375 fclose(fptr); 376 377 /* error occurred reading the file */ 378 if (rv == NULL) { 379 JLI_ReportMessage(DLL_ERROR4, arg); 380 exit(1); 381 } 382 383 return rv; 384 } 385 386 /* 387 * expand a string into a list of words separated by whitespace. 388 */ 389 static JLI_List expandArg(const char *arg) { 390 JLI_List rv; 391 392 /* arbitrarily pick 8, seems to be a reasonable number of arguments */ 393 rv = JLI_List_new(8); 394 395 expand(rv, arg, NULL); 396 397 return rv; 398 } 399 400 JNIEXPORT JLI_List JNICALL 401 JLI_PreprocessArg(const char *arg, jboolean expandSourceOpt) { 402 JLI_List rv; 403 404 if (firstAppArgIndex > 0) { 405 // In user application arg, no more work. 406 return NULL; 407 } 408 409 if (stopExpansion) { 410 // still looking for user application arg 411 checkArg(arg); 412 return NULL; 413 } 414 415 if (expandSourceOpt 416 && JLI_StrCCmp(arg, "--source") == 0 417 && JLI_StrChr(arg, ' ') != NULL) { 418 return expandArg(arg); 419 } 420 421 if (arg[0] != '@') { 422 checkArg(arg); 423 return NULL; 424 } 425 426 if (arg[1] == '\0') { 427 // @ by itself is an argument 428 checkArg(arg); 429 return NULL; 430 } 431 432 arg++; 433 if (arg[0] == '@') { 434 // escaped @argument 435 rv = JLI_List_new(1); 436 checkArg(arg); 437 JLI_List_add(rv, JLI_StringDup(arg)); 438 } else { 439 rv = expandArgFile(arg); 440 } 441 return rv; 442 } 443 444 int isTerminalOpt(char *arg) { 445 return JLI_StrCmp(arg, "-jar") == 0 || 446 JLI_StrCmp(arg, "-m") == 0 || 447 JLI_StrCmp(arg, "--module") == 0 || 448 JLI_StrCmp(arg, "--dry-run") == 0 || 449 JLI_StrCmp(arg, "-h") == 0 || 450 JLI_StrCmp(arg, "-?") == 0 || 451 JLI_StrCmp(arg, "-help") == 0 || 452 JLI_StrCmp(arg, "--help") == 0 || 453 JLI_StrCmp(arg, "-X") == 0 || 454 JLI_StrCmp(arg, "--help-extra") == 0 || 455 JLI_StrCmp(arg, "-version") == 0 || 456 JLI_StrCmp(arg, "--version") == 0 || 457 JLI_StrCmp(arg, "-fullversion") == 0 || 458 JLI_StrCmp(arg, "--full-version") == 0; 459 } 460 461 JNIEXPORT jboolean JNICALL 462 JLI_AddArgsFromEnvVar(JLI_List args, const char *var_name) { 463 char *env = getenv(var_name); 464 465 if (firstAppArgIndex == 0) { 466 // Not 'java', return 467 return JNI_FALSE; 468 } 469 470 if (relaunch) { 471 return JNI_FALSE; 472 } 473 474 if (NULL == env) { 475 return JNI_FALSE; 476 } 477 478 JLI_ReportMessage(ARG_INFO_ENVVAR, var_name, env); 479 return expand(args, env, var_name); 480 } 481 482 /* 483 * Expand a string into a list of args. 484 * If the string is the result of looking up an environment variable, 485 * var_name should be set to the name of that environment variable, 486 * for use if needed in error messages. 487 */ 488 489 static jboolean expand(JLI_List args, const char *str, const char *var_name) { 490 jboolean inEnvVar = (var_name != NULL); 491 492 char *p, *arg; 493 char quote; 494 JLI_List argsInFile; 495 496 // This is retained until the process terminates as it is saved as the args 497 p = JLI_MemAlloc(JLI_StrLen(str) + 1); 498 while (*str != '\0') { 499 while (*str != '\0' && isspace(*str)) { 500 str++; 501 } 502 503 // Trailing space 504 if (*str == '\0') { 505 break; 506 } 507 508 arg = p; 509 while (*str != '\0' && !isspace(*str)) { 510 if (inEnvVar && (*str == '"' || *str == '\'')) { 511 quote = *str++; 512 while (*str != quote && *str != '\0') { 513 *p++ = *str++; 514 } 515 516 if (*str == '\0') { 517 JLI_ReportMessage(ARG_ERROR8, var_name); 518 exit(1); 519 } 520 str++; 521 } else { 522 *p++ = *str++; 523 } 524 } 525 526 *p++ = '\0'; 527 528 argsInFile = JLI_PreprocessArg(arg, JNI_FALSE); 529 530 if (NULL == argsInFile) { 531 if (isTerminalOpt(arg)) { 532 if (inEnvVar) { 533 JLI_ReportMessage(ARG_ERROR9, arg, var_name); 534 } else { 535 JLI_ReportMessage(ARG_ERROR15, arg); 536 } 537 exit(1); 538 } 539 JLI_List_add(args, arg); 540 } else { 541 size_t cnt, idx; 542 char *argFile = arg; 543 cnt = argsInFile->size; 544 for (idx = 0; idx < cnt; idx++) { 545 arg = argsInFile->elements[idx]; 546 if (isTerminalOpt(arg)) { 547 if (inEnvVar) { 548 JLI_ReportMessage(ARG_ERROR10, arg, argFile, var_name); 549 } else { 550 JLI_ReportMessage(ARG_ERROR16, arg, argFile); 551 } 552 exit(1); 553 } 554 JLI_List_add(args, arg); 555 } 556 // Shallow free, we reuse the string to avoid copy 557 JLI_MemFree(argsInFile->elements); 558 JLI_MemFree(argsInFile); 559 } 560 /* 561 * Check if main-class is specified after argument being checked. It 562 * must always appear after expansion, as a main-class could be specified 563 * indirectly into environment variable via an @argfile, and it must be 564 * caught now. 565 */ 566 if (firstAppArgIndex != NOT_FOUND) { 567 if (inEnvVar) { 568 JLI_ReportMessage(ARG_ERROR11, var_name); 569 } else { 570 JLI_ReportMessage(ARG_ERROR17); 571 } 572 exit(1); 573 } 574 575 assert (*str == '\0' || isspace(*str)); 576 } 577 578 return JNI_TRUE; 579 } 580 581 #ifdef DEBUG_ARGFILE 582 /* 583 * Stand-alone sanity test, build with following command line 584 * $ CC -DDEBUG_ARGFILE -DNO_JNI -g args.c jli_util.c 585 */ 586 587 void fail(char *expected, char *actual, size_t idx) { 588 printf("FAILED: Token[%lu] expected to be <%s>, got <%s>\n", idx, expected, actual); 589 exit(1); 590 } 591 592 void test_case(char *case_data, char **tokens, size_t cnt_tokens) { 593 size_t actual_cnt; 594 char *token; 595 __ctx_args ctx; 596 597 actual_cnt = 0; 598 599 ctx.state = FIND_NEXT; 600 ctx.parts = JLI_List_new(4); 601 ctx.cptr = case_data; 602 ctx.eob = case_data + strlen(case_data); 603 604 printf("Test case: <%s>, expected %lu tokens.\n", case_data, cnt_tokens); 605 606 for (token = nextToken(&ctx); token != NULL; token = nextToken(&ctx)) { 607 // should not have more tokens than expected 608 if (actual_cnt >= cnt_tokens) { 609 printf("FAILED: Extra token detected: <%s>\n", token); 610 exit(2); 611 } 612 if (JLI_StrCmp(token, tokens[actual_cnt]) != 0) { 613 fail(tokens[actual_cnt], token, actual_cnt); 614 } 615 actual_cnt++; 616 } 617 618 char* last = NULL; 619 if (ctx.parts->size != 0) { 620 last = JLI_List_combine(ctx.parts); 621 } 622 JLI_List_free(ctx.parts); 623 624 if (actual_cnt >= cnt_tokens) { 625 // same number of tokens, should have nothing left to parse 626 if (last != NULL) { 627 if (*last != '#') { 628 printf("Leftover detected: %s", last); 629 exit(2); 630 } 631 } 632 } else { 633 if (JLI_StrCmp(last, tokens[actual_cnt]) != 0) { 634 fail(tokens[actual_cnt], last, actual_cnt); 635 } 636 actual_cnt++; 637 } 638 if (actual_cnt != cnt_tokens) { 639 printf("FAILED: Number of tokens not match, expected %lu, got %lu\n", 640 cnt_tokens, actual_cnt); 641 exit(3); 642 } 643 644 printf("PASS\n"); 645 } 646 647 #define DO_CASE(name) \ 648 test_case(name[0], name + 1, sizeof(name)/sizeof(char*) - 1) 649 650 int main(int argc, char** argv) { 651 size_t i, j; 652 653 char* case1[] = { "-version -cp \"c:\\\\java libs\\\\one.jar\" \n", 654 "-version", "-cp", "c:\\java libs\\one.jar" }; 655 DO_CASE(case1); 656 657 // note the open quote at the end 658 char* case2[] = { "com.foo.Panda \"Furious 5\"\fand\t'Shi Fu' \"escape\tprison", 659 "com.foo.Panda", "Furious 5", "and", "Shi Fu", "escape\tprison"}; 660 DO_CASE(case2); 661 662 char* escaped_chars[] = { "escaped chars testing \"\\a\\b\\c\\f\\n\\r\\t\\v\\9\\6\\23\\82\\28\\377\\477\\278\\287\"", 663 "escaped", "chars", "testing", "abc\f\n\r\tv96238228377477278287"}; 664 DO_CASE(escaped_chars); 665 666 char* mixed_quote[] = { "\"mix 'single quote' in double\" 'mix \"double quote\" in single' partial\"quote me\"this", 667 "mix 'single quote' in double", "mix \"double quote\" in single", "partialquote methis"}; 668 DO_CASE(mixed_quote); 669 670 char* comments[] = { "line one #comment\n'line #2' #rest are comment\r\n#comment on line 3\nline 4 #comment to eof", 671 "line", "one", "line #2", "line", "4"}; 672 DO_CASE(comments); 673 674 char* open_quote[] = { "This is an \"open quote \n across line\n\t, note for WS.", 675 "This", "is", "an", "open quote ", "across", "line", ",", "note", "for", "WS." }; 676 DO_CASE(open_quote); 677 678 char* escape_in_open_quote[] = { "Try \"this \\\\\\\\ escape\\n double quote \\\" in open quote", 679 "Try", "this \\\\ escape\n double quote \" in open quote" }; 680 DO_CASE(escape_in_open_quote); 681 682 char* quote[] = { "'-Dmy.quote.single'='Property in single quote. Here a double quote\" Add some slashes \\\\/'", 683 "-Dmy.quote.single=Property in single quote. Here a double quote\" Add some slashes \\/" }; 684 DO_CASE(quote); 685 686 char* multi[] = { "\"Open quote to \n new \"line \\\n\r third\\\n\r\\\tand\ffourth\"", 687 "Open quote to ", "new", "line third\tand\ffourth" }; 688 DO_CASE(multi); 689 690 char* escape_quote[] = { "c:\\\"partial quote\"\\lib", 691 "c:\\partial quote\\lib" }; 692 DO_CASE(escape_quote); 693 694 if (argc > 1) { 695 for (i = 0; i < argc; i++) { 696 JLI_List tokens = JLI_PreprocessArg(argv[i], JNI_FALSE); 697 if (NULL != tokens) { 698 for (j = 0; j < tokens->size; j++) { 699 printf("Token[%lu]: <%s>\n", (unsigned long) j, tokens->elements[j]); 700 } 701 } 702 } 703 } 704 } 705 706 #endif // DEBUG_ARGFILE