Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2044 lines
62 KiB

  1. // UTIL.C -- Data structure manipulation functions
  2. //
  3. // Copyright (c) 1988-1990, Microsoft Corporation. All rights reserved.
  4. //
  5. // Purpose:
  6. // This module contains routines manipulating the Data Structures of NMAKE. The
  7. // routines are independent of the Mode of execution (Real/Bound).
  8. //
  9. // Revision History:
  10. // 04-Feb-2000 BTF Ported to Win64
  11. // 01-Feb-1994 HV Turn off extra info display.
  12. // 17-Jan-1994 HV Fixed bug #3548: possible bug in findMacroValues because we
  13. // are scanning 'string' byte-by-byte instead of char-by-char
  14. // 15-Nov-1993 JdR Major speed improvements
  15. // 15-Oct-1993 HV Use tchar.h instead of mbstring.h directly, change STR*() to _ftcs*()
  16. // 03-Jun-1993 HV Add helper local function TruncateString for findFirst.
  17. // 10-May-1993 HV Add include file mbstring.h
  18. // Change the str* functions to STR*
  19. // 08-Apr-1993 HV Rewrite prependPath() to use _splitpath() and _makepath()
  20. // 31-Mar-1993 HV Rewrite drive(), path(), filename(), and extension() to use
  21. // _splitpath() instead of parsing the pathname by itself.
  22. // 08-Jun-1992 SS Port to DOSX32
  23. // 27-May-1992 RG Changed open_file to use _fsopen with _SH_DENYWR
  24. // 29-May-1990 SB ^$ was not becoming same as $$ for command lines ...
  25. // 01-May-1990 SB Nasty Preprocessor quirk bug in modifySpecialvalue() fixed
  26. // 27-Feb-1990 SB GP fault for '!if "$(debug"=="y"' fixed (bug t119)
  27. // 08-Feb-1990 SB GP fault for 'echo $(FOO:" =" ^) fixed
  28. // 06-Feb-1990 SB Handle $* etc in presence of Quoted names.
  29. // 02-Feb-1990 SB Add file_open() function
  30. // 31-Jan-1990 SB Debug changes; testAddr used to track problems at that addr
  31. // 08-Dec-1989 SB Changed SPRINTF() to avoid C6 warnings with -Oes
  32. // 04-Dec-1989 SB ZFormat() proto was misspelled as Zformat()
  33. // 01-Dec-1989 SB realloc_memory() added; allocate() uses _msize() now
  34. // 22-Nov-1989 SB Add strcmpiquote() and unQuote()
  35. // 22-Nov-1989 SB add #ifdef DEBUG_MEMORY funcs free_memory() and mem_status()
  36. // 13-Nov-1989 SB restoreEnv() function unreferenced
  37. // 08-Oct-1989 SB Added searchBucket(); find() now checks equivalence of quoted
  38. // and unquoted versions of a target.
  39. // 06-Sep-1989 SB $* in in-line files was clobbering Global variable 'buf'
  40. // 18-Aug-1989 SB heapdump() gets two parameters
  41. // 03-Jul-1989 SB moved curTime() to utilb.c and utilr.c to handle DOSONLY ver
  42. // 30-Jun-1989 SB added curTime() to get current Time.
  43. // 28-Jun-1989 SB changed copyEnviron()
  44. // 05-Jun-1989 SB makeString("") instead of using "" in DGROUP for null macro
  45. // 21-May-1989 SB modified find() to understand that targets 'foo.c', '.\foo.c'
  46. // and './foo.c' are the same.
  47. // 13-May-1989 SB Added functions path(), drive(), filename(), extension(),
  48. // strbskip(), strbscan() instead of ZTOOLS library
  49. // 12-May-1989 SB Fixed bug in substitute strings
  50. // 10-May-1989 SB Added stuff for ESCH handling changes in Quotes;
  51. // 01-May-1989 SB changed return value of allocate().
  52. // 14-Apr-1989 SB restoreEnv() created for macroBackInheritance
  53. // 05-Apr-1989 SB made all funcs NEAR; Reqd to make all function calls NEAR
  54. // 17-Mar-1989 SB substituteStrings() now has 3 new error checks & avoids GPs
  55. // 13-Mar-1989 SB ZFormat() was missing the legal case of '%%'
  56. // 22-Feb-1989 SB ZFormat() has buffer overflow check with extra parameter
  57. // and SPRINTF() gives a new error
  58. // 15-Feb-1989 SB Changed modifySpecialValue(), was not performing correctly
  59. // for $(@D) and $(@B) for some cases.
  60. // 13-Feb-1989 SB Made Prototypes for ZTools Library functions as extern
  61. // 5-Dec-1988 SB Made SPRINTF() cdecl as NMAKE now uses Pascal calling
  62. // 25-Nov-1988 SB Added SPRINTF() and ZFormat() and also added prototypes for
  63. // functions used from ZTools Library (6 of them)
  64. // 10-Nov-1988 SB Removed mixed mode functions (bound & real) to utilr.c
  65. // & utilb.c; corr globals/debug data also moved
  66. // 10-Oct-1988 SB Add Comments for hash().
  67. // 18-Sep-1988 RB Fix bad flag checking for targets in find().
  68. // 15-Sep-1988 RB Move some def's out to GLOBALS.
  69. // 22-Aug-1988 RB Don't find undefined macros.
  70. // 17-Aug-1988 RB Clean up. Clear memory in allocate().
  71. // 8-Jul-1988 rj Minor speedup (?) to find().
  72. // 7-Jul-1988 rj Modified find and hash; less efficient, but case-indep.
  73. // 1-Jul-1988 rj Fixed line truncation after null special macro.
  74. // 30-Jun-1988 rj Fixed bug with checkDynamicDependency not handling $$.
  75. // 29-Jun-1988 rj Fixed bug with extra * after expanding $**.
  76. // Fixed abysmal with $$(@?).
  77. // Fixed handling of F, B, R modifiers.
  78. // 22-Jun-1988 rj Added friendly filename truncation (findFirst).
  79. // 22-Jun-1988 rj Fixed bug #3 (.abc.def.ghi not detected).
  80. // 16-Jun-1988 rj Modified several routines to look for escape
  81. // character when walking through strings.
  82. // 27-May-1988 rb Fixed space-appending on list-expansion macros.
  83. // Don't include trailing path separator in $(@D).
  84. #include "precomp.h"
  85. #pragma hdrstop
  86. // Prototypes of functions local to this module
  87. void putValue(char**, char**, char**, char**, char*, unsigned*, char *);
  88. void substituteStrings(char**, char**, char**, char**, char*,
  89. unsigned*, char *);
  90. char * isolateMacroName(char*, char*);
  91. char * checkDynamicDependency(char*);
  92. void increaseBuffer(char**, char**, char**, unsigned*, char *);
  93. void putSpecial(char**, char**, char**, char**, unsigned*,
  94. unsigned, char *);
  95. char * modifySpecialValue(char, char*, char*);
  96. STRINGLIST * searchBucket(char *, STRINGLIST **, unsigned);
  97. int envVars(char **environ);
  98. // Prototypes of functions used by ZFormat from ZTools Library
  99. char * strbscan(char *, char *);
  100. char * strbskip(char *, char *);
  101. int drive(const char *, char *);
  102. int path(const char *, char *);
  103. int filenamepart(const char *, char *);
  104. int extension(const char *, char *);
  105. const char special1[] = "*@<?";
  106. const char special2[] = "DFBR";
  107. // These two variables are needed in order to provide
  108. // more informative error messages in case findMacroValue
  109. // detects an illegal macro in the command block of
  110. // a batch mode rule.
  111. static BOOL fFindingMacroInBatchRule = FALSE;
  112. static char * szBatchRuleName; // current rule name
  113. #if !defined(NDEBUG)
  114. size_t TotalAlloc;
  115. unsigned long CntAlloc;
  116. void
  117. printStats(
  118. void
  119. )
  120. {
  121. #if defined(STATISTICS)
  122. fprintf(stderr,"\n Memory Allocation:\n"
  123. " total allocation:\t%12.lu\n"
  124. " individual allocations:\t%12.lu\n"
  125. " Macros:\n"
  126. " searches:\t\t%12.lu\n"
  127. " chain walks:\t\t%12.lu\n"
  128. " insertions:\t\t%12.lu\n"
  129. "\n Targets:\n"
  130. " searches:\t\t%12.lu\n"
  131. " chain walks:\t\t%12.lu\n"
  132. "\n Others:\n"
  133. " stricmp compares:\t%12.lu\n"
  134. " String List frees:\t%12.lu\n"
  135. " String List allocs:\t%12.lu\n",
  136. TotalAlloc,
  137. CntAlloc,
  138. CntfindMacro,
  139. CntmacroChains,
  140. CntinsertMacro,
  141. CntfindTarget,
  142. CnttargetChains,
  143. CntStriCmp,
  144. CntFreeStrList,
  145. CntAllocStrList);
  146. #endif
  147. }
  148. #endif
  149. #define ALLOCBLKSIZE 32768
  150. unsigned long AllocFreeCnt;
  151. char * PtrAlloc;
  152. STRINGLIST *PtrFreeStrList;
  153. // rallocate - allocate raw memory (not cleared)
  154. //
  155. // Tries to allocate a chunk of memory, prints error message and exits if
  156. // the requested amount is not available.
  157. void *
  158. rallocate(
  159. size_t size
  160. )
  161. {
  162. void *chunk = malloc(size);
  163. if (chunk == NULL) {
  164. makeError(currentLine, OUT_OF_MEMORY);
  165. }
  166. #if !defined(NDEBUG)
  167. TotalAlloc += size;
  168. CntAlloc++;
  169. #endif
  170. return(chunk);
  171. }
  172. // allocate - allocate memory and clear it
  173. //
  174. // Tries to allocate a chunk of memory, prints error message and exits if
  175. // the requested amount is not available.
  176. // IMPORTANT: we must clear the memory here. Code elsewhere relies on this.
  177. void *
  178. allocate(
  179. size_t size // Number of bytes requested
  180. )
  181. {
  182. void *chunk = rallocate(size);
  183. memset(chunk, 0, size);
  184. return(chunk);
  185. }
  186. void *
  187. alloc_stringlist(
  188. void
  189. )
  190. {
  191. STRINGLIST *chunk;
  192. #if defined(STATISTICS)
  193. CntAllocStrList++;
  194. #endif
  195. if (PtrFreeStrList != NULL) {
  196. chunk = PtrFreeStrList;
  197. PtrFreeStrList = chunk->next;
  198. } else {
  199. if (AllocFreeCnt < sizeof(STRINGLIST)) {
  200. PtrAlloc = (char *) rallocate(ALLOCBLKSIZE);
  201. AllocFreeCnt = ALLOCBLKSIZE;
  202. }
  203. chunk = (STRINGLIST *) PtrAlloc;
  204. PtrAlloc += sizeof(STRINGLIST);
  205. AllocFreeCnt -= sizeof(STRINGLIST);
  206. }
  207. chunk->next = NULL;
  208. chunk->text = NULL;
  209. return (void *)chunk;
  210. }
  211. void
  212. free_stringlist(
  213. STRINGLIST *pMem
  214. )
  215. {
  216. #if !defined(NDEBUG)
  217. STRINGLIST *tmp;
  218. for (tmp = PtrFreeStrList; tmp != NULL; tmp = tmp->next) {
  219. if (tmp == pMem) {
  220. fprintf(stderr, "free same pointer twice: %p\n", pMem);
  221. return;
  222. }
  223. }
  224. pMem->text = NULL;
  225. #endif
  226. pMem->next = PtrFreeStrList;
  227. PtrFreeStrList = pMem;
  228. #if defined(STATISTICS)
  229. CntFreeStrList++;
  230. #endif
  231. }
  232. // allocate space, copies the given string into the newly allocated space, and
  233. // returns ptr.
  234. char *
  235. makeString(
  236. const char *s
  237. )
  238. {
  239. char *t;
  240. size_t l = _tcslen(s) + 1;
  241. t = (char *) rallocate(l);
  242. memcpy(t, s, l);
  243. return(t);
  244. }
  245. // like makeString, but creates quoted string
  246. char *
  247. makeQuotedString(
  248. const char *s
  249. )
  250. {
  251. char *t;
  252. size_t l = _tcslen(s);
  253. t = (char *) rallocate(l + 3);
  254. t[0] = '"';
  255. memcpy(t+1, s, l);
  256. t[l+1] = '"';
  257. t[l+2] = '\0';
  258. return(t);
  259. }
  260. // reallocate String sz1 and append sz2
  261. char *
  262. reallocString(
  263. char * szTarget,
  264. const char * szAppend
  265. )
  266. {
  267. char *szNew;
  268. size_t cbNew = _tcslen(szTarget) + _tcslen(szAppend) + 1;
  269. szNew = (char *) REALLOC(szTarget, cbNew);
  270. if (!szNew)
  271. makeError(0, OUT_OF_MEMORY);
  272. return _tcscat(szNew, szAppend);
  273. }
  274. // makes element the head of list
  275. void
  276. prependItem(
  277. STRINGLIST **list,
  278. STRINGLIST *element
  279. )
  280. {
  281. element->next = *list;
  282. *list = element;
  283. }
  284. // makes element the tail of list
  285. void
  286. appendItem(
  287. STRINGLIST **list,
  288. STRINGLIST *element
  289. )
  290. {
  291. for (; *list; list = &(*list)->next)
  292. ;
  293. *list = element;
  294. }
  295. // hash - returns hash value corresponding to a string
  296. //
  297. // Purpose:
  298. // This is a hash function. The hash function uses the following Algorithm --
  299. // Add the characters making up the string (s) to get N (ASCII values)
  300. // N mod total ,gives the hash value,
  301. // where, total is MAXMACRO for macros
  302. // MAXTARGET targets
  303. // Additionally, for targets it takes Uppercase Values alone, since, targets
  304. // are generally filenames and DOS/OS2 filenames are case independent.
  305. //
  306. // Input:
  307. // s = name for which a hash is required
  308. // total = Constant used in the hash function
  309. // targetFlag = boolean flag; true for targets, false for macros
  310. //
  311. // Output:
  312. // Returns hash value between 0 and (total-1)
  313. unsigned
  314. hash(
  315. char *s,
  316. unsigned total,
  317. BOOL targetFlag
  318. )
  319. {
  320. unsigned n;
  321. unsigned c;
  322. if (targetFlag) {
  323. for (n = 0; c = *s; (n += c), s++)
  324. if (c == '/') {
  325. c = '\\'; // slash == backslash in targets
  326. } else {
  327. c = _totupper(c); // lower-case == upper-case in targets
  328. }
  329. } else {
  330. for (n = 0; *s; n += *s++)
  331. ;
  332. }
  333. return(n % total);
  334. }
  335. // find - look up a string in a hash table
  336. //
  337. // Look up a macro or target name in a hash table and return the entry
  338. // or NULL.
  339. // If a macro and undefined, return NULL.
  340. // Targets get matched in a special way because of filename equivalence.
  341. STRINGLIST *
  342. find(
  343. char *str,
  344. unsigned limit,
  345. STRINGLIST *table[],
  346. BOOL targetFlag
  347. )
  348. {
  349. unsigned n;
  350. char *string = str;
  351. char *quote;
  352. STRINGLIST *found;
  353. BOOL fAllocStr = FALSE;
  354. if (*string) {
  355. n = hash(string, limit, targetFlag);
  356. if (targetFlag) {
  357. #if defined(STATISTICS)
  358. CntfindTarget++;
  359. #endif
  360. found = searchBucket(string, table, n);
  361. if (found) {
  362. return(found);
  363. }
  364. //Look for .\string
  365. if (!_tcsncmp(string, ".\\", 2) || !_tcsncmp(string, "./", 2)) {
  366. string += 2;
  367. } else {
  368. string = (char *)rallocate(2 + _tcslen(str) + 1);
  369. _tcscat(_tcscpy(string, ".\\"), str);
  370. fAllocStr = (BOOL)TRUE;
  371. }
  372. n = hash(string, limit, targetFlag);
  373. found = searchBucket(string, table, n);
  374. if (found) {
  375. if (fAllocStr) {
  376. FREE(string);
  377. }
  378. return(found);
  379. }
  380. // Look for ./string
  381. if (string != (str + 2)) {
  382. string[1] = '/';
  383. }
  384. n = hash(string, limit, targetFlag);
  385. found = searchBucket(string, table, n);
  386. if (fAllocStr) {
  387. FREE(string);
  388. }
  389. if (found) {
  390. return(found);
  391. }
  392. //Look for "foo" or foo
  393. if (*str == '"') {
  394. quote = unQuote(str);
  395. } else {
  396. size_t len = _tcslen(str) + 2;
  397. quote = (char *) allocate(len + 1);
  398. _tcscat(_tcscat(_tcscpy(quote, "\""), str), "\"");
  399. }
  400. n = hash(quote, limit, targetFlag);
  401. found = searchBucket(quote, table, n);
  402. FREE(quote);
  403. return found;
  404. }
  405. for (found = table[n]; found; found = found->next) {
  406. if (!_tcscmp(found->text, string)) {
  407. return((((MACRODEF *)found)->flags & M_UNDEFINED) ? NULL : found);
  408. }
  409. }
  410. }
  411. return(NULL);
  412. }
  413. // FINDMACROVALUES --
  414. // looks up a macro's value in hash table, prepends to list a STRINGLIST
  415. // element holding pointer to macro's text, then recurses on any macro
  416. // invocations in the value
  417. //
  418. // The lexer checks for overrun in names (they must be < 128 chars).
  419. // If a longer, undefined macro is only referred to in the value of
  420. // another macro which is never invoked, the error will not be flagged.
  421. // I think this is reasonable behavior.
  422. //
  423. // MACRO NAMES CAN ONLY CONSIST OF ALPHANUMERIC CHARS AND UNDERSCORE
  424. //
  425. // we pass a null list pointer-pointer if we just want to check for cyclical
  426. // definitions w/o building the list.
  427. //
  428. // the name parameter is what's on the left side of an = when we're just
  429. // checking cyclical definitions. When we "find" the macros in a target
  430. // block, we have to pass the name of the macro whose text we're recursing
  431. // on in our recursive call to findMacroValues().
  432. //
  433. // Might want to check into how to do this w/o recursion (is it possible?)
  434. //
  435. // This function is RECURSIVE.
  436. // Added a fix to make this function handle expand macros which refer
  437. // to other recursive macros.
  438. //
  439. // levelSeen is the recLevel at which a macroname was first seen so that
  440. // the appropriate expansion can be calculated (even when recursing ...)
  441. BOOL
  442. findMacroValues(
  443. char *string, // string to check
  444. STRINGLIST **list, // list to build
  445. STRINGLIST **newtail, // tail of list to update
  446. char *name, // name = string
  447. unsigned recLevel, // recursion level
  448. unsigned levelSeen,
  449. UCHAR flags
  450. )
  451. {
  452. char macroName[MAXNAME];
  453. char *s;
  454. MACRODEF *p;
  455. STRINGLIST *q, *r, dummy, *tail;
  456. unsigned i;
  457. BOOL inQuotes = (BOOL) FALSE; // flag when inside quote marks
  458. if (list) {
  459. if (newtail) {
  460. tail = *newtail;
  461. } else {
  462. tail = *list;
  463. if (tail) {
  464. while (tail->next) {
  465. tail = tail->next;
  466. }
  467. }
  468. }
  469. } else {
  470. tail = NULL;
  471. }
  472. for (s = string; *s; ++s) { // walk the string
  473. for (; *s && *s != '$'; s = _tcsinc(s)) { // find next macro
  474. if (*s == '\"')
  475. inQuotes = (BOOL) !inQuotes;
  476. if (!inQuotes && *s == ESCH) {
  477. ++s; // skip past ESCH
  478. if (*s == '\"')
  479. inQuotes = (BOOL) !inQuotes;
  480. }
  481. }
  482. if (!*s)
  483. break; // move past '$'
  484. if (!s[1])
  485. if (ON(flags, M_ENVIRONMENT_DEF)) {
  486. if (newtail)
  487. *newtail = tail;
  488. return(FALSE);
  489. } else
  490. makeError(currentLine, SYNTAX_ONE_DOLLAR);
  491. s = _tcsinc(s);
  492. if (!inQuotes && *s == ESCH) {
  493. s = _tcsinc(s);
  494. if (!MACRO_CHAR(*s))
  495. if (ON(flags, M_ENVIRONMENT_DEF)) {
  496. if (newtail)
  497. *newtail = tail;
  498. return(FALSE);
  499. } else
  500. makeError(currentLine, SYNTAX_BAD_CHAR, *s);
  501. }
  502. if (*s == '$') { // $$ = dynamic
  503. s = checkDynamicDependency(s); // dependency
  504. continue; // or just $$->$
  505. } else if (*s == '(') { // name is longer
  506. s = isolateMacroName(s+1, macroName); // than 1 char
  507. if (_tcschr(special1, *macroName)) {
  508. if (fFindingMacroInBatchRule && OFF(gFlags, F1_NO_BATCH)) {
  509. // we only allow $< in batch rules
  510. // so this is an error
  511. char * szBadMacro = (char *) _alloca(_tcslen(macroName) + 4);
  512. sprintf(szBadMacro, "$(%s)", macroName);
  513. makeError(0, BAD_BATCH_MACRO, szBadMacro, szBatchRuleName);
  514. }
  515. else
  516. continue;
  517. }
  518. } else {
  519. if (_tcschr(special1, *s)){
  520. if (fFindingMacroInBatchRule && OFF(gFlags, F1_NO_BATCH) && *s != '<') {
  521. char szBadMacro[3];
  522. szBadMacro[0] = '$';
  523. szBadMacro[1] = *s;
  524. szBadMacro[2] = '\0';
  525. // we only allow $< in batch rules
  526. // so this is an error
  527. makeError(0, BAD_BATCH_MACRO, szBadMacro, szBatchRuleName);
  528. }
  529. else
  530. continue; // 1-letter macro
  531. }
  532. if (!MACRO_CHAR(*s))
  533. if (ON(flags, M_ENVIRONMENT_DEF)) {
  534. if (newtail) *newtail = tail;
  535. return(FALSE);
  536. } else
  537. makeError(currentLine, SYNTAX_ONE_DOLLAR);
  538. macroName[0] = *s;
  539. macroName[1] = '\0';
  540. }
  541. // If list isn't NULL, allocate storage for a new node. Otherwise
  542. // this function was called purely to verify the macro name was
  543. // valid and we can just use the dummy node as a place holder.
  544. //
  545. // 2/28/92 BryanT dummy.text wasn't being initialized each
  546. // time. As a result, if we were to recurse
  547. // this function, whatever value was in text
  548. // on the last iteration is still there.
  549. // In the case where the macroName doesn't exist
  550. // in the the call to findMacro(), and the old
  551. // dummy->text field contained a '$', the
  552. // function would recurse infinitely.
  553. // Set to an empty string now
  554. //
  555. // q = (list) ? makeNewStrListElement() : &dummy;
  556. if (list != NULL) {
  557. q = makeNewStrListElement();
  558. } else {
  559. dummy.next = NULL;
  560. dummy.text = makeString(" ");
  561. q = &dummy;
  562. }
  563. if (p = findMacro(macroName)) {
  564. // macro names are case sensitive
  565. if (name && !_tcscmp(name, macroName)) { // self-refer-
  566. r = p->values; // ential macro
  567. for (i = recLevel; i != levelSeen && r; --i)
  568. r = r->next; // (a = $a;b)
  569. q->text = (r) ? r->text : makeString("");
  570. }
  571. else if (ON(p->flags, M_EXPANDING_THIS_ONE)) { // recursive def
  572. if (ON(flags, M_ENVIRONMENT_DEF)) {
  573. if (newtail) *newtail = tail;
  574. return(FALSE);
  575. } else
  576. makeError(currentLine, CYCLE_IN_MACRODEF, macroName);
  577. }
  578. else if (ON(p->flags, M_UNDEFINED)) {
  579. q->text = makeString(""); // if macro undefd [DS 18040]
  580. }
  581. else
  582. q->text = p->values->text;
  583. }
  584. if (list) { // if blding list
  585. if (!p || ON(p->flags, M_UNDEFINED))
  586. q->text = makeString(""); // if macro undefd
  587. q->next = NULL; // use NULL as its value
  588. if (tail) {
  589. tail->next = q;
  590. }else {
  591. *list = q;
  592. }
  593. tail = q;
  594. } // if found text,
  595. if (!p || !_tcschr(q->text, '$'))
  596. continue; // and found $ in
  597. SET(p->flags, M_EXPANDING_THIS_ONE); // text, recurse
  598. findMacroValues(q->text,
  599. list,
  600. &tail,
  601. macroName,
  602. recLevel+1,
  603. (name && _tcscmp(name, macroName)? recLevel : levelSeen),
  604. flags);
  605. CLEAR(p->flags, M_EXPANDING_THIS_ONE);
  606. }
  607. if (newtail) *newtail = tail;
  608. return(TRUE);
  609. }
  610. //
  611. // findMacroValuesInRule --
  612. // This is a wrapper around findMacroValues that generates an
  613. // error if an illegal special macro is referenced (directly
  614. // or indirectly) by the command block of a batch-mode rule
  615. //
  616. BOOL
  617. findMacroValuesInRule(
  618. RULELIST *pRule, // pointer to current rule
  619. char *string, // string to check
  620. STRINGLIST **list // list to build
  621. )
  622. {
  623. BOOL retval;
  624. if (fFindingMacroInBatchRule = pRule->fBatch)
  625. szBatchRuleName = pRule->name;
  626. retval = findMacroValues(string, list, NULL, NULL, 0, 0, 0);
  627. fFindingMacroInBatchRule = FALSE;
  628. return retval;
  629. }
  630. // isolateMacroName -- returns pointer to name of macro in extended invocation
  631. //
  632. // arguments: s pointer to macro invocation
  633. // macro pointer to location to store macro's name
  634. //
  635. // returns: pointer to end of macro's name
  636. //
  637. // isolates name and moves s
  638. char *
  639. isolateMacroName(
  640. char *s, // past closing paren
  641. char *macro // lexer already ckd for bad syntax
  642. )
  643. {
  644. char *t;
  645. for (t = macro; *s && *s != ')' && *s != ':'; t=_tcsinc(t), s=_tcsinc(s)) {
  646. if (*s == ESCH) {
  647. s++;
  648. if (!MACRO_CHAR(*s))
  649. makeError(currentLine, SYNTAX_BAD_CHAR, *s);
  650. }
  651. _tccpy(t, s);
  652. }
  653. while (*s != ')') {
  654. if (*s == ESCH)
  655. s++;
  656. if (!*s)
  657. break;
  658. s++;
  659. }
  660. if (*s != ')')
  661. makeError(currentLine, SYNTAX_NO_PAREN);
  662. *t = '\0';
  663. if (t - macro > MAXNAME)
  664. makeError(currentLine, NAME_TOO_LONG);
  665. return(s);
  666. }
  667. // figures out length of the special macro in question, and returns a ptr to
  668. // the char after the last char in the invocation
  669. char *
  670. checkDynamicDependency(
  671. char *s
  672. )
  673. {
  674. char *t;
  675. t = s + 1;
  676. if (*t == ESCH)
  677. return(t); // If $^, leave us at the ^
  678. if (*t == '(') {
  679. if (*++t == ESCH) {
  680. return(t);
  681. } else {
  682. if (*t == '@') {
  683. if (*++t == ESCH)
  684. makeError(currentLine, SYNTAX_BAD_CHAR, *++t);
  685. else if (*t == ')')
  686. return(t);
  687. else if (_tcschr(special2, *t)) {
  688. if (*++t == ESCH)
  689. makeError(currentLine, SYNTAX_BAD_CHAR, *++t);
  690. else if (*t == ')')
  691. return(t);
  692. }
  693. } else {
  694. t = s + 1; // invalid spec. mac.
  695. if (*t == ESCH)
  696. return(t); // evals. to $(
  697. return(++t);
  698. }
  699. }
  700. }
  701. return(s); // char matched
  702. }
  703. // removes and expands any macros that exist in the string macroStr.
  704. // could return a different string (in case expandMacros needs more
  705. // buffer size for macro expansion. it is the caller's responsibility
  706. // to free the string soon as it is not required....
  707. char *
  708. removeMacros(
  709. char *macroStr
  710. )
  711. {
  712. STRINGLIST *eMacros = NULL;
  713. STRINGLIST *m;
  714. if (_tcschr(macroStr, '$')) {
  715. findMacroValues(macroStr, &eMacros, NULL, NULL, 0, 0, 0);
  716. m = eMacros;
  717. macroStr = expandMacros(macroStr, &eMacros);
  718. while (eMacros = m) {
  719. m = m->next;
  720. FREE_STRINGLIST(eMacros);
  721. }
  722. }
  723. return(macroStr);
  724. }
  725. // expandMacros -- expand all macros in a string s
  726. //
  727. // arguments: s string to expand
  728. // macros list of macros being expanded (for recursive calls)
  729. //
  730. // actions: allocate room for expanded string
  731. // look for macros in string (handling ESCH properly (v1.5))
  732. // parse macro--determine its type
  733. // use putSpecial to handle special macros
  734. // recurse on list of macros
  735. // use putValue to put value of just-found macro in string
  736. // return expanded string
  737. //
  738. // returns: string with all macros expanded
  739. //
  740. // CALLER CHECKS TO SEE IF _tcschr(STRING, '$') IN ORER TO CALL THIS.
  741. // this doesn't work for HUGE macros yet. need to make data far.
  742. //
  743. // we save the original string and the list of ptrs to macro values
  744. // to be substituted.
  745. // the caller has to free the expansion buffer
  746. //
  747. // expandMacros updates the macros pointer and frees the skipped elements
  748. char *
  749. expandMacros(
  750. char *s, // text to expand
  751. STRINGLIST **macros
  752. )
  753. {
  754. STRINGLIST *p;
  755. char *t, *end;
  756. char *text, *xresult;
  757. BOOL inQuotes = (BOOL) FALSE; // flag when inside quote marks
  758. char *w;
  759. BOOL freeFlag = FALSE;
  760. char resultbuffer[MAXBUF];
  761. unsigned len = MAXBUF;
  762. char *result = resultbuffer;
  763. end = result + MAXBUF;
  764. for (t = result; *s;) { // look for macros
  765. for (; *s && *s != '$'; *t++ = *s++) { // as we copy the string
  766. if (t == end) {
  767. increaseBuffer(&result, &t, &end, &len, &resultbuffer[0]);
  768. }
  769. if (*s == '\"')
  770. inQuotes = (BOOL) !inQuotes;
  771. if (!inQuotes && *s == ESCH) {
  772. *t++ = ESCH;
  773. if (t == end) {
  774. increaseBuffer(&result, &t, &end, &len, &resultbuffer[0]);
  775. }
  776. s++;
  777. if (*s == '\"')
  778. inQuotes = (BOOL) !inQuotes;
  779. }
  780. }
  781. if (t == end) { // string
  782. increaseBuffer(&result, &t, &end, &len, &resultbuffer[0]);
  783. }
  784. if (!*s)
  785. break; // s exhausted
  786. w = (s+1); // don't check for ^ here; already did in findMacroValues
  787. if (*w == '(' // found a macro
  788. && _tcschr(special1, *(w+1))) {
  789. putSpecial(&result, &s, &t, &end, &len, X_SPECIAL_MACRO, &resultbuffer[0]);
  790. continue;
  791. } else
  792. if (*w++ == '$') { // double ($$)
  793. if (*w == ESCH) // $$^...
  794. putSpecial(&result, &s, &t, &end, &len, DOLLAR_MACRO, &resultbuffer[0]);
  795. else if (*w == '@') // $$@
  796. putSpecial(&result, &s, &t, &end, &len, DYNAMIC_MACRO, &resultbuffer[0]);
  797. else if ((*w == '(') && (*++w == '@') && (*w == ')'))
  798. putSpecial(&result, &s, &t, &end, &len, DYNAMIC_MACRO, &resultbuffer[0]);
  799. else if (((*++w=='F') || (*w=='D') || (*w=='B') || (*w=='R')) && (*++w == ')'))
  800. putSpecial(&result, &s, &t, &end, &len, X_DYNAMIC_MACRO, &resultbuffer[0]);
  801. else // $$
  802. putSpecial(&result, &s, &t, &end, &len, DOLLAR_MACRO, &resultbuffer[0]);
  803. continue;
  804. } else
  805. if (_tcschr(special1, s[1])) { // $?*<
  806. putSpecial(&result, &s, &t, &end, &len, SPECIAL_MACRO, &resultbuffer[0]);
  807. continue;
  808. }
  809. if (!*macros)
  810. makeError(currentLine, MACRO_INTERNAL);
  811. // skip this element in the macros list
  812. if (_tcschr((*macros)->text, '$')) { // recurse
  813. p = *macros;
  814. *macros = (*macros)->next;
  815. text = expandMacros(p->text, macros);
  816. freeFlag = TRUE;
  817. } else {
  818. text = (*macros)->text;
  819. *macros = (*macros)->next;
  820. }
  821. putValue(&result, &s, &t, &end, text, &len, &resultbuffer[0]);
  822. if (freeFlag) {
  823. FREE(text);
  824. freeFlag = FALSE;
  825. }
  826. }
  827. if (t == end) {
  828. increaseBuffer(&result, &t, &end, &len, &resultbuffer[0]);
  829. }
  830. *t++ = '\0';
  831. // Allocate result buffer
  832. if (!(xresult = (char *) rallocate((size_t) (t - result)))) {
  833. makeError(currentLine, MACRO_TOO_LONG);
  834. }
  835. memcpy(xresult, result, (size_t) (t - result));
  836. return(xresult);
  837. }
  838. // increaseBuffer -- increase the size of a string buffer, with error check
  839. //
  840. // arguments: result pointer to pointer to start of buffer
  841. // t pointer to pointer to end of buffer (before expansion)
  842. // end pointer to pointer to end of buffer (after expansion)
  843. // len pointer to amount by which to expand buffer
  844. // first address of initial stack buffer
  845. //
  846. // actions: check for out of memory
  847. // allocate new buffer
  848. // reset pointers properly
  849. //
  850. // modifies: t, end to point to previous end and new end of buffer
  851. //
  852. // uses 0 as line number because by the time we hit an error in this routine,
  853. // the line number will be set at the last line of the makefile (because we'll
  854. // have already read and parsed the file)
  855. void
  856. increaseBuffer(
  857. char **result,
  858. char **t,
  859. char **end,
  860. unsigned *len,
  861. char *first
  862. )
  863. {
  864. unsigned newSize;
  865. // determine if result points to the firstbuffer and make a dynamic copy first.
  866. if (*result == first) {
  867. char *p = (char *) rallocate(*len);
  868. memcpy(p, *result, *len);
  869. *result = p;
  870. }
  871. newSize = *len + MAXBUF;
  872. #ifdef DEBUG
  873. if (fDebug) {
  874. fprintf(stderr,"\t\tAttempting to reallocate %d bytes to %d\n", *len, newSize);
  875. }
  876. #endif
  877. if (!(*result =(char *) REALLOC(*result, newSize))) {
  878. makeError(currentLine, MACRO_TOO_LONG);
  879. }
  880. *t = *result + *len; // reset pointers, len
  881. *len = newSize;
  882. *end = *result + *len;
  883. }
  884. // putSpecial -- expand value of special macro
  885. //
  886. // arguments: result ppointer to start of string being expanded
  887. // name ppointer to macro name being expanded
  888. // dest ppointer to place to store expanded value
  889. // end ppointer to end of dest's buffer
  890. // length pointer to amount by which to increase dest's buffer
  891. // which ype of special macro
  892. // first address of initial stack buffer
  893. //
  894. // actions: depending on type of macro, set "value" equal to macro's value
  895. // if macro expands to a list, store whole list in "value" ($?, $*)
  896. // otherwise, modify value according to F, B, D, R flag
  897. // use putValue to insert the value in dest
  898. //
  899. // has to detect error if user tries $* etc. when they aren't defined
  900. // fix to handle string substitutions, whitespace around names, etc
  901. // right now list macros are limited to 1024 bytes total
  902. void
  903. putSpecial(
  904. char **result,
  905. char **name,
  906. char **dest,
  907. char **end,
  908. unsigned *length,
  909. unsigned which,
  910. char *first
  911. )
  912. {
  913. char *value = 0;
  914. STRINGLIST *p;
  915. BOOL listMacro = FALSE, modifier = FALSE, star = FALSE;
  916. unsigned i = 1;
  917. char c, nameBuf[MAXNAME], *temp;
  918. switch (which) {
  919. case X_SPECIAL_MACRO:
  920. i = 2;
  921. modifier = TRUE;
  922. case SPECIAL_MACRO:
  923. switch ((*name)[i]) {
  924. case '<':
  925. value = dollarLessThan;
  926. break;
  927. case '@':
  928. value = dollarAt;
  929. break;
  930. case '?':
  931. value = (char*) dollarQuestion;
  932. listMacro = TRUE;
  933. break;
  934. case '*':
  935. if ((*name)[i+1] != '*') {
  936. value = dollarStar;
  937. star = TRUE;
  938. break;
  939. }
  940. value = (char*) dollarStarStar;
  941. listMacro = TRUE;
  942. ++i;
  943. break;
  944. default:
  945. break;
  946. }
  947. ++i;
  948. break;
  949. case X_DYNAMIC_MACRO:
  950. i = 4;
  951. modifier = TRUE;
  952. case DYNAMIC_MACRO:
  953. value = dollarDollarAt;
  954. break;
  955. case DOLLAR_MACRO:
  956. if (*dest == *end)
  957. increaseBuffer(result, dest, end, length, first);
  958. *(*dest)++ = '$';
  959. *name += 2;
  960. return;
  961. default:
  962. return; // can't happen
  963. }
  964. if (!value) {
  965. for (temp = *name; *temp && *temp != ' ' && *temp != '\t'; temp++)
  966. ;
  967. c = *temp; *temp = '\0';
  968. makeError(currentLine, ILLEGAL_SPECIAL_MACRO, *name);
  969. *temp = c;
  970. listMacro = FALSE;
  971. value = makeString(""); // value is freed below, must be on heap [rm]
  972. }
  973. if (listMacro) {
  974. char *pVal, *endVal;
  975. unsigned lenVal = MAXBUF;
  976. p = (STRINGLIST*) value;
  977. pVal = (char *)allocate(MAXBUF);
  978. endVal = pVal + MAXBUF;
  979. for (value = pVal; p; p = p->next) {
  980. temp = p->text;
  981. if (modifier)
  982. temp = modifySpecialValue((*name)[i], nameBuf, temp);
  983. while(*temp) {
  984. if (value == endVal)
  985. increaseBuffer(&pVal, &value, &endVal, &lenVal, NULL);
  986. *value++ = *temp++;
  987. }
  988. if (value == endVal)
  989. increaseBuffer(&pVal, &value, &endVal, &lenVal, NULL);
  990. *value = '\0';
  991. // Append a space if there are more elements in the list. [RB]
  992. if (p->next) {
  993. *value++ = ' ';
  994. if (value == endVal)
  995. increaseBuffer(&pVal, &value, &endVal, &lenVal, NULL);
  996. *value = '\0';
  997. }
  998. }
  999. value = pVal;
  1000. } else {
  1001. //For some reason 'buf' was being used here clobbering global 'buf
  1002. // instead of nameBuf
  1003. if (star)
  1004. value = modifySpecialValue('R', nameBuf, value);
  1005. if (modifier)
  1006. value = modifySpecialValue((*name)[i], nameBuf, value);
  1007. }
  1008. putValue(result, name, dest, end, value, length, first);
  1009. if (value != dollarAt &&
  1010. value != dollarDollarAt &&
  1011. value != dollarLessThan &&
  1012. (value < nameBuf || value >= nameBuf + MAXNAME)
  1013. )
  1014. FREE(value);
  1015. }
  1016. // modifySpecialValue -- alter path name according to modifier
  1017. //
  1018. // Scope: Local.
  1019. //
  1020. // Purpose:
  1021. // The dynamic macros of NMAKE have modifiers F,B,D & R. This routine does the
  1022. // job of producing a modified special value for a given filename.
  1023. //
  1024. // Input:
  1025. // c -- determines the type of modification (modifier is one of F,B,D & R
  1026. // buf -- location for storing modified value
  1027. // value -- The path specification to be modified
  1028. //
  1029. // Output: Returns a pointer to the modified value
  1030. //
  1031. // Assumes: That initially buf pointed to previously allocated memory of size MAXNAME.
  1032. //
  1033. // Notes:
  1034. // Given a path specification of the type "<drive:><path><filename><.ext>", the
  1035. // modifiers F,B,D and R stand for following --
  1036. // F - <filename><.ext> - actual Filename
  1037. // B - <filename> - Base filename
  1038. // D - <drive:><path> - Directory
  1039. // R - <drive:><path><filename> - Real filename (filename without extension)
  1040. // This routine handles OS/2 1.20 filenames as well. The last period in the
  1041. // path specification is the start of the extension. When directory part is null
  1042. // the function returns '.' for current directory.
  1043. //
  1044. // This function now handles quoted filenames too
  1045. char *
  1046. modifySpecialValue(
  1047. char c,
  1048. char *buf,
  1049. char *value
  1050. )
  1051. {
  1052. char *lastSlash, // last path separator from "\\/"
  1053. *extension; // points to the extension
  1054. char *saveBuf;
  1055. BOOL fQuoted;
  1056. lastSlash = extension = NULL;
  1057. saveBuf=buf;
  1058. _tcscpy(buf, value);
  1059. fQuoted = (BOOL) (buf[0] == '"');
  1060. value = buf + _tcslen(buf) - 1; // start from the end of pathname
  1061. for (;value >= buf; value--) {
  1062. if (PATH_SEPARATOR(*value)) { // scan upto first path separator
  1063. lastSlash = value;
  1064. break;
  1065. } else
  1066. if (*value == '.' && !extension) //last '.' is extension
  1067. extension = value;
  1068. }
  1069. switch(c) {
  1070. case 'D':
  1071. if (lastSlash) {
  1072. if (buf[1] == ':' && lastSlash == buf + 2)
  1073. ++lastSlash; // 'd:\foo.obj' --> 'd:\'
  1074. *lastSlash = '\0';
  1075. } else if (buf[1] == ':')
  1076. buf[2] = '\0'; // 'd:foo.obj' --> 'd:'
  1077. else
  1078. _tcscpy(buf, "."); // 'foo.obj' --> '.'
  1079. break;
  1080. case 'B':
  1081. if (extension) // for 'B' extension is clobbered
  1082. *extension = '\0';
  1083. case 'F':
  1084. if (lastSlash)
  1085. buf = lastSlash + 1;
  1086. else if (buf[1] == ':') // 'd:foo.obj' --> foo for B
  1087. buf+=2; // 'd:foo.obj' --> foo.obj for F
  1088. break;
  1089. case 'R':
  1090. if (extension)
  1091. *extension = '\0'; // extension clobbered
  1092. }
  1093. if (fQuoted) { // [fabriced] make sure we have quotes
  1094. char *pEnd; // at both ends
  1095. if(*buf!='"' && buf>saveBuf) { // make sure we can go back one char
  1096. buf--;
  1097. *buf='"';
  1098. }
  1099. pEnd = _tcschr(buf, '\0');
  1100. if(*(pEnd-1)!='"') {
  1101. *pEnd++ = '"';
  1102. *pEnd = '\0';
  1103. }
  1104. }
  1105. return(buf);
  1106. }
  1107. // putValue -- store expanded macro's value in dest and advance past it
  1108. //
  1109. // arguments: result ppointer to start of string being expanded
  1110. // name ppointer to macro name being expanded
  1111. // dest ppointer to place to store expanded value
  1112. // end ppointer to end of dest's buffer
  1113. // source pointer to text of expanded macro
  1114. // length pointer to amount by which to increase dest's buffer
  1115. // first address of initial stack buffer
  1116. //
  1117. // actions: if there is a substitution, call substituteStrings to do it
  1118. // else copy source text into dest
  1119. // advance *name past end of macro's invocation
  1120. //
  1121. // already did error checking in lexer
  1122. void
  1123. putValue(
  1124. char **result,
  1125. char **name,
  1126. char **dest,
  1127. char **end,
  1128. char *source,
  1129. unsigned *length,
  1130. char *first
  1131. )
  1132. {
  1133. char *s;
  1134. char *t; // temporary pointer
  1135. if (*++*name == ESCH)
  1136. ++*name; // go past $ & ESCH if any
  1137. s = _tcschr(*name, ':');
  1138. for (t = *name; *t && *t != ')'; t++) // go find first non-escaped )
  1139. if (*t == ESCH)
  1140. t++;
  1141. if ((**name == '(') // substitute only if there is
  1142. && s // a : before a non-escaped )
  1143. && (s < t)
  1144. ) {
  1145. substituteStrings(result, &s, dest, end, source, length, first);
  1146. *name = s;
  1147. } else {
  1148. for (; *source; *(*dest)++ = *source++) // copy source into dest
  1149. if (*dest == *end)
  1150. increaseBuffer(result, dest, end, length, first);
  1151. if (**name == '$')
  1152. ++*name; // go past $$
  1153. if (**name == '(') // advance from ( to )
  1154. while (*++*name != ')');
  1155. else
  1156. if (**name == '*' && *(*name + 1) == '*')
  1157. ++*name; // skip $**
  1158. ++*name; // move all the way past
  1159. }
  1160. }
  1161. // substituteStrings -- perform macro substitution
  1162. //
  1163. // arguments: result ppointer to start of string being expanded
  1164. // name ppointer to macro name being expanded
  1165. // dest ppointer to place to store substituted value
  1166. // end ppointer to end of dest's buffer
  1167. // source pointer to text of expanded macro (before sub.)
  1168. // length pointer to amount by which to increase dest's buffer
  1169. // first address of initial stack buffer
  1170. //
  1171. // changes: [SB]
  1172. // old, new now dynamically allocated; saves memory; 3 errors detected
  1173. // for macro syntax in script files.
  1174. //
  1175. // note: [SB]
  1176. // we could use lexer routines recursively if we get rid of the globals
  1177. // and then these errors needn't be flagged. [?]
  1178. //
  1179. // actions: store text to convert from in old
  1180. // store text to convert to in new
  1181. // scan source text
  1182. // when a match is found, copy new text into dest &
  1183. // skip over old text
  1184. // else copy one character from source text into dest
  1185. //
  1186. // returns: nothing
  1187. void
  1188. substituteStrings(
  1189. char **result,
  1190. char **name,
  1191. char **dest,
  1192. char **end,
  1193. char *source,
  1194. unsigned *length,
  1195. char *first
  1196. )
  1197. {
  1198. char *oldString, *newString;
  1199. char *pEq, *pPar, *t;
  1200. char *s;
  1201. size_t i;
  1202. ++*name;
  1203. for (pEq = *name; *pEq && *pEq != '='; pEq++)
  1204. if (*pEq == ESCH)
  1205. pEq++;
  1206. if (*pEq != '=')
  1207. makeError(line, SYNTAX_NO_EQUALS);
  1208. if (pEq == *name)
  1209. makeError(line, SYNTAX_NO_SEQUENCE);
  1210. for (pPar = pEq; *pPar && *pPar != ')'; pPar++)
  1211. if (*pPar == ESCH)
  1212. pPar++;
  1213. if (*pPar != ')')
  1214. makeError(line, SYNTAX_NO_PAREN);
  1215. oldString = (char *) allocate((size_t) ((pEq - *name) + 1));
  1216. for (s = oldString, t = *name; *t != '='; *s++ = *t++)
  1217. if (*t == ESCH)
  1218. ++t;
  1219. *s = '\0';
  1220. i = _tcslen(oldString);
  1221. newString = (char *) allocate((size_t) (pPar - pEq));
  1222. for (s = newString, t++; *t != ')'; *s++ = *t++)
  1223. if (*t == ESCH)
  1224. ++t;
  1225. *s = '\0';
  1226. *name = pPar + 1;
  1227. while (*source) {
  1228. if ((*source == *oldString) // check for match
  1229. && !_tcsncmp(source, oldString, i)) { // copy new in for
  1230. for (s = newString; *s; *(*dest)++ = *s++) // old string
  1231. if (*dest == *end)
  1232. increaseBuffer(result, dest, end, length, first);
  1233. source += i;
  1234. continue;
  1235. }
  1236. if (*dest == *end)
  1237. increaseBuffer(result, dest, end, length, first);
  1238. *(*dest)++ = *source++; // else copy 1 char
  1239. }
  1240. FREE(oldString);
  1241. FREE(newString);
  1242. }
  1243. // prependPath -- prepend the path from pszWildcard to pszFilename
  1244. //
  1245. // Scope: Global.
  1246. //
  1247. // Purpose:
  1248. // This function is called to first extract the path (drive & dir parts) from
  1249. // pszWildcard, the prepend that path to pszFilename. The result string is
  1250. // a reconstruction of the full pathname. Normally, the pszWildcard parameter
  1251. // is the same as the first parameter supplied to findFirst(), and pszFilename
  1252. // is what returned by findFirst/findNext.
  1253. //
  1254. // Input:
  1255. // pszWildcard -- Same as the first parameter supplied to findFirst()
  1256. // pszFilename -- Same as the return value of findFirst/FindNext()
  1257. //
  1258. // Output:
  1259. // Return the reconstructed full pathname. The user must be responsible to
  1260. // free up the memory allocated by this string.
  1261. //
  1262. // Assumes:
  1263. // Since pszWildcard, the first parameter to findFirst() must include a filename
  1264. // part; this is what I assume. If the filename part is missing, then
  1265. // _splitpath will mistaken the directory part of pszWildcard as the filename
  1266. // part and things will be very ugly.
  1267. //
  1268. // History:
  1269. // 08-Apr-1993 HV Rewrite prependPath() to use _splitpath() and _makepath()
  1270. char *
  1271. prependPath(
  1272. const char *pszWildcard,
  1273. const char *pszFilename
  1274. )
  1275. {
  1276. // The following are the components when breaking up pszWildcard
  1277. char szDrive[_MAX_DRIVE];
  1278. char szDir[_MAX_DIR];
  1279. // The following are the resulting full pathname.
  1280. char szPath[_MAX_PATH];
  1281. char *pszResultPath;
  1282. // First break up the pszWildcard, throwing away the filename and the
  1283. // extension parts.
  1284. _splitpath(pszWildcard, szDrive, szDir, NULL, NULL);
  1285. // Then, glue the drive & dir components of pszWildcard to pszFilename
  1286. _makepath(szPath, szDrive, szDir, pszFilename, NULL);
  1287. // Make a copy of the resulting string and return it.
  1288. pszResultPath = makeString(szPath);
  1289. return (pszResultPath);
  1290. }
  1291. // isRule -- examines a string to determine whether it's a rule definition
  1292. //
  1293. // arguments: s string to examine for rule-ness
  1294. //
  1295. // actions: assume it's not a rule
  1296. // skip past first brace pair (if any)
  1297. // if next character is a period,
  1298. // look for next brace
  1299. // if there are no path separators between second brace pair,
  1300. // and there's just a suffix after them, it's a rule
  1301. // else if there's another period later on, and no path seps
  1302. // after it, then it's a rule.
  1303. //
  1304. // returns: TRUE if it's a rule, FALSE otherwise.
  1305. BOOL
  1306. isRule(
  1307. char *s
  1308. )
  1309. {
  1310. char *t = s, *u;
  1311. BOOL result = FALSE;
  1312. if (*t == '{') { // 1st char is {, so
  1313. while (*++t && *t != '}') // we skip over rest
  1314. if (*t == ESCH)
  1315. ++t;
  1316. if (*t)
  1317. ++t; // of path (no error
  1318. } // checking)
  1319. if (*t == '.') {
  1320. for (u = t; *u && *u != '{'; ++u) // find first non-escaped {
  1321. if (*u == ESCH)
  1322. ++u;
  1323. s = t;
  1324. while (t < u) { // look for path seps.
  1325. if (PATH_SEPARATOR(*t))
  1326. break; // if we find any, it's
  1327. ++t; // not a rule (they
  1328. } // can't be in suffix)
  1329. if (*u && (t == u)) { // if not at end & no path sep
  1330. while (*++u && *u != '}') // find first non-esc }
  1331. if (*u == ESCH)
  1332. ++u;
  1333. if (*u) {
  1334. ++u;
  1335. if (*u == '.' // if you find it, with . just
  1336. && !_tcschr(u+1, '/' ) // next to it & no path seps.,
  1337. && !_tcschr(u+1, '\\')) // it's a rule
  1338. if (_tcschr(u+1, '.')) // too many suffixes
  1339. makeError(currentLine, TOO_MANY_RULE_NAMES);
  1340. else
  1341. result = TRUE;
  1342. }
  1343. } else if (((u = _tcspbrk(s+1, "./\\")) && (*u == '.'))
  1344. && !_tcschr(u+1, '/')
  1345. && !_tcschr(u+1, '\\'))
  1346. if (_tcschr(u+1, '.')) // too many suffixes
  1347. makeError(currentLine, TOO_MANY_RULE_NAMES);
  1348. else
  1349. result = TRUE;
  1350. }
  1351. return(result);
  1352. }
  1353. // ZFormat - extmake syntax worker routine.
  1354. //
  1355. // pStr destination string where formatted result is placed.
  1356. // fmt formatting string. The valid extmake syntax is ...
  1357. // %% is always %
  1358. // %s is the first dependent filename
  1359. // %|<dpfe>F is the appropriate portion out of %s
  1360. // d drive
  1361. // p path
  1362. // f filename
  1363. // e extension
  1364. // %|F same as %s
  1365. // One needn't escape a %, unless it is a valid extmake syntax
  1366. // pFirstDep is the dependent filename used for expansion
  1367. BOOL
  1368. ZFormat(
  1369. char *pStr,
  1370. unsigned limit,
  1371. char *fmt,
  1372. char *pFirstDep
  1373. )
  1374. {
  1375. char c;
  1376. char *pEnd = pStr + limit;
  1377. char *s;
  1378. BOOL fError;
  1379. BOOL fDrive;
  1380. BOOL fPath;
  1381. BOOL fFilename;
  1382. BOOL fExtension;
  1383. char buf[_MAX_PATH];
  1384. for (; (c = *fmt) && (pStr < pEnd); fmt++) {
  1385. if (c != '%') {
  1386. *pStr++ = c;
  1387. } else {
  1388. switch (*++fmt) {
  1389. case '%': // '%%' -> '%'
  1390. *pStr++ = '%';
  1391. break;
  1392. case 's':
  1393. for (s = pFirstDep; s && *s && pStr < pEnd; *pStr++ = *s++)
  1394. ;
  1395. break;
  1396. case '|':
  1397. s = fmt-1;
  1398. fError = fDrive = fPath = fFilename = fExtension = FALSE;
  1399. *buf = '\0';
  1400. do {
  1401. switch (*++fmt) {
  1402. case 'd':
  1403. fDrive = TRUE;
  1404. break;
  1405. case 'p':
  1406. fPath = TRUE;
  1407. break;
  1408. case 'f':
  1409. fFilename = TRUE;
  1410. break;
  1411. case 'e':
  1412. fExtension = TRUE;
  1413. break;
  1414. case 'F':
  1415. if (fmt[-1] == '|') {
  1416. fDrive = TRUE;
  1417. fPath = TRUE;
  1418. fFilename = TRUE;
  1419. fExtension = TRUE;
  1420. }
  1421. break;
  1422. case '\0':
  1423. // backtrack, so that we don't read past
  1424. // the end of the string in the for loop
  1425. // [msdev96 #4057]
  1426. fmt--;
  1427. // fall trhough
  1428. default :
  1429. fError = TRUE;
  1430. break;
  1431. }
  1432. if (fError) {
  1433. break;
  1434. }
  1435. } while (*fmt != 'F');
  1436. if (fError) {
  1437. for (; s <= fmt && pStr < pEnd; *pStr++ = *s++)
  1438. ;
  1439. break;
  1440. }
  1441. if (!pFirstDep) {
  1442. makeError(0, EXTMAKE_NO_FILENAME);
  1443. }
  1444. if (fDrive) {
  1445. drive(pFirstDep, buf);
  1446. }
  1447. if (fPath) {
  1448. path(pFirstDep, strend(buf));
  1449. }
  1450. if (fFilename) {
  1451. filenamepart(pFirstDep, strend(buf));
  1452. }
  1453. if (fExtension) {
  1454. extension(pFirstDep, strend(buf));
  1455. }
  1456. for (s = buf; *s && pStr < pEnd; *pStr++ = *s++)
  1457. ;
  1458. break;
  1459. case '\0':
  1460. // backtrack, so that we don't read past
  1461. // the end of the string in the for loop
  1462. // [msdev96 #4057]
  1463. fmt--;
  1464. // *pStr++ = '%';
  1465. break;
  1466. default:
  1467. *pStr++ = '%';
  1468. if (pStr == pEnd) {
  1469. return(TRUE);
  1470. }
  1471. *pStr++ = *fmt;
  1472. break;
  1473. }
  1474. }
  1475. }
  1476. if (pStr < pEnd) {
  1477. *pStr = '\0';
  1478. return(FALSE);
  1479. }
  1480. return(TRUE);
  1481. }
  1482. void
  1483. expandExtmake(
  1484. char *buf,
  1485. char *fmt,
  1486. char *pFirstDep
  1487. )
  1488. {
  1489. if (ZFormat(buf, MAXCMDLINELENGTH, fmt, pFirstDep))
  1490. makeError(0, COMMAND_TOO_LONG, fmt);
  1491. }
  1492. // drive -- copy a drive from source to dest if present
  1493. //
  1494. // Scope: Local.
  1495. //
  1496. // Purpose: copy a drive from source to dest if present, return TRUE if we found one
  1497. //
  1498. // Input:
  1499. // const char *src -- The full path to extract the drive from.
  1500. // char *dst -- The buffer to copy the drive to, must be alloc'd before.
  1501. //
  1502. // Output: Return TRUE if a drive part is found, else return FALSE.
  1503. //
  1504. // Assumes:
  1505. // 1. src is a legal pathname.
  1506. // 2. src does not contain network path (i.e. \\foo\bar)
  1507. // 3. The buffer dst is large enough to contain the result.
  1508. // 4. src does not contain quote since _splitpath() treat quotes a normal char.
  1509. //
  1510. // History:
  1511. // 31-Mar-1993 HV Rewrite drive(), path(), filenamepart(), and extension() to use
  1512. // _splitpath() instead of parsing the pathname by itself.
  1513. int
  1514. drive(
  1515. const char *src,
  1516. char *dst
  1517. )
  1518. {
  1519. _splitpath(src, dst, NULL, NULL, NULL);
  1520. return (0 != _tcslen(dst));
  1521. }
  1522. // extension -- copy a extension from source to dest if present
  1523. //
  1524. // Scope: Local.
  1525. //
  1526. // Purpose: copy a drive from source to dest if present, return TRUE if we found one
  1527. //
  1528. // Input:
  1529. // const char *src -- The full path to extract the extension from.
  1530. // char *dst -- The buffer to copy the extension to.
  1531. //
  1532. // Output: Return TRUE if a extension part is found, else return FALSE.
  1533. //
  1534. // Assumes:
  1535. // 1. src is a legal pathname.
  1536. // 2. src does not contain network path (i.e. \\foo\bar)
  1537. // 3. The buffer dst is large enough to contain the result.
  1538. // 4. src does not contain quote since _splitpath() treat quotes a normal char.
  1539. //
  1540. // History:
  1541. // 31-Mar-1993 HV Rewrite drive(), path(), filenamepart(), and extension() to use
  1542. // _splitpath() instead of parsing the pathname by itself.
  1543. int
  1544. extension(
  1545. const char *src,
  1546. char *dst
  1547. )
  1548. {
  1549. _splitpath(src, NULL, NULL, NULL, dst);
  1550. return (0 != _tcslen(dst));
  1551. }
  1552. // filename -- copy a filename from source to dest if present
  1553. //
  1554. // Scope: Local.
  1555. //
  1556. // Purpose: copy a filename from source to dest if present, return TRUE if we found one
  1557. //
  1558. // Input:
  1559. // const char *src -- The full path to extract the filename from.
  1560. // char *dst -- The buffer to copy the filename to.
  1561. //
  1562. // Output: Return TRUE if a filename part is found, else return FALSE.
  1563. //
  1564. // Assumes:
  1565. // 1. src is a legal pathname.
  1566. // 2. src does not contain network path (i.e. \\foo\bar)
  1567. // 3. The buffer dst is large enough to contain the result.
  1568. // 4. src does not contain quote since _splitpath() treat quotes a normal char.
  1569. //
  1570. // Notes:
  1571. // BUGBUG: (posible) when src == '..' --> dst = '.', src == '.', dst = ''
  1572. // This is the way _splitpath works.
  1573. //
  1574. // History:
  1575. // 31-Mar-1993 HV Rewrite drive(), path(), filenamepart(), and extension() to use
  1576. // _splitpath() instead of parsing the pathname by itself.
  1577. int
  1578. filenamepart(
  1579. const char *src,
  1580. char *dst
  1581. )
  1582. {
  1583. _splitpath(src, NULL, NULL, dst, NULL);
  1584. return (0 != _tcslen(dst));
  1585. }
  1586. // path -- copy a path from source to dest if present
  1587. //
  1588. // Scope: Local.
  1589. //
  1590. // Purpose: copy a path from source to dest if present, return TRUE if we found one
  1591. //
  1592. // Input:
  1593. // const char *src -- The full path to extract the path from.
  1594. // char *dst -- The buffer to copy the path to.
  1595. //
  1596. // Output: Return TRUE if a path part is found, else return FALSE.
  1597. //
  1598. // Assumes:
  1599. // 1. src is a legal pathname.
  1600. // 2. src does not contain network path (i.e. \\foo\bar)
  1601. // 3. The buffer dst is large enough to contain the result.
  1602. // 4. src does not contain quote since _splitpath() treat quotes a normal char.
  1603. //
  1604. // History:
  1605. // 31-Mar-1993 HV Rewrite drive(), path(), filenamepart(), and extension() to use
  1606. // _splitpath() instead of parsing the pathname by itself.
  1607. int
  1608. path(
  1609. const char *src,
  1610. char *dst
  1611. )
  1612. {
  1613. _splitpath(src, NULL, dst, NULL, NULL);
  1614. return (0 != _tcslen(dst));
  1615. }
  1616. STRINGLIST *
  1617. searchBucket(
  1618. char *string,
  1619. STRINGLIST *table[],
  1620. unsigned hash
  1621. )
  1622. {
  1623. char *s, *t;
  1624. STRINGLIST *p;
  1625. for (p = table[hash]; p; p = p->next) {
  1626. #if defined(STATISTICS)
  1627. CnttargetChains++;
  1628. #endif
  1629. for (s = string, t = p->text; *s && *t; s++, t++) {
  1630. if (*s == '\\' || *s == '/') // / == \ in targets
  1631. if (*t == '\\' || *t == '/')
  1632. continue;
  1633. else
  1634. break;
  1635. else if (_totupper(*s) == _totupper(*t)) // lc == UC
  1636. continue;
  1637. else
  1638. break;
  1639. }
  1640. if (!*s && !*t)
  1641. return(p);
  1642. }
  1643. return(NULL);
  1644. }
  1645. int
  1646. strcmpiquote(
  1647. char *str1,
  1648. char *str2
  1649. )
  1650. {
  1651. int rc;
  1652. char *s1, *s2;
  1653. char *t;
  1654. #if defined(STATISTICS)
  1655. CntStriCmp++;
  1656. #endif
  1657. s1 = (char *) _alloca(_tcslen(str1) + 1);
  1658. s2 = (char *) _alloca(_tcslen(str2) + 1);
  1659. if (*str1 == '"')
  1660. str1++;
  1661. for (t = s1;*str1;*t++=*str1++)
  1662. ;
  1663. if (t[-1] == '"')
  1664. t--;
  1665. *t = '\0';
  1666. if (*str2 == '"')
  1667. str2++;
  1668. for (t = s2;*str2;*t++=*str2++)
  1669. ;
  1670. if (t[-1] == '"')
  1671. t--;
  1672. *t = '\0';
  1673. rc = _tcsicmp(s1, s2);
  1674. return(rc);
  1675. }
  1676. // Remove quotes from a string, if any
  1677. // Returns a copy of the string
  1678. // Note that there may be quotes at the start, the end or either side.
  1679. char *
  1680. unQuote(
  1681. char *str
  1682. )
  1683. {
  1684. char *s = (char *) rallocate(_tcslen(str) + 1);
  1685. char *t;
  1686. #if defined(STATISTICS)
  1687. CntunQuotes++;
  1688. #endif
  1689. if (*str == '"') {
  1690. str++;
  1691. }
  1692. for (t = s;*str;*t++=*str++)
  1693. ;
  1694. if (t[-1] == '"') {
  1695. t--;
  1696. }
  1697. *t = '\0';
  1698. return(s);
  1699. }
  1700. FILE *
  1701. open_file(
  1702. char *name,
  1703. char *mode
  1704. )
  1705. {
  1706. // If name contains Quotes, remove these before opening the file
  1707. if (*name == '"') {
  1708. *(_tcsrchr(name, '"')) = '\0';
  1709. _tcscpy(name, name+1);
  1710. }
  1711. // Allow sharing between makes running at the same time
  1712. return(_fsopen(name, mode, _SH_DENYWR));
  1713. }
  1714. // TruncateString -- Truncate a string to certain size, take care of MBCS
  1715. //
  1716. // Scope: GLOBAL.
  1717. //
  1718. // Purpose:
  1719. // Since an MBCS string can mix double-byte & single-byte characters, simply
  1720. // truncating the string by terminate it with a NULL byte won't work.
  1721. // TruncateString will make sure that the string is cut off at the character
  1722. // boundary.
  1723. //
  1724. // Input:
  1725. // pszString -- The string to be truncated.
  1726. // uLen -- The length to truncate. The final string's length might be
  1727. // less than this be cause of double-byte character.
  1728. //
  1729. // Output: pszString -- The truncated string.
  1730. //
  1731. // History:
  1732. // 03-Jun-1993 HV Add helper local function TruncateString for findFirst.
  1733. void
  1734. TruncateString(
  1735. char *pszString,
  1736. unsigned uLen
  1737. )
  1738. {
  1739. char *pEnd = pszString; // Points to the end of the string
  1740. unsigned cByte; // Number of bytes to advance depend on lead
  1741. // byte or not
  1742. // Loop to get to the end of the string, exit only when we have exhausted
  1743. // the string, or when the length limit is reached.
  1744. while(*pEnd) {
  1745. // If the the character is a lead byte, advance 2 bytes,
  1746. // else, just advance 1 byte.
  1747. #ifdef _MBCS
  1748. cByte = _ismbblead(*pEnd) ? 2 : 1;
  1749. #else
  1750. cByte = 1;
  1751. #endif
  1752. // If we hit the limit by advancing, stop now.
  1753. if (pEnd - pszString + cByte > uLen) {
  1754. *pEnd = '\0'; // Truncate it.
  1755. break;
  1756. }
  1757. // Otherwise, advance the pointer to the next character (not byte)
  1758. pEnd += cByte;
  1759. }
  1760. }
  1761. // IsValidMakefile - Checks if the makefile is in plain ascii text format.
  1762. //
  1763. // Scope: GLOBAL.
  1764. //
  1765. // Purpose:
  1766. // We don't want to open UTF8 or unicode makefiles, only to report an
  1767. // error at some random place in the makefile.
  1768. //
  1769. // Input:
  1770. // file -- File pointer.
  1771. //
  1772. // Output: -- Returns FALSE if in UTF8 or Unicode format
  1773. //
  1774. // History:
  1775. BOOL IsValidMakefile(FILE *fp)
  1776. {
  1777. const char sigUTF8[] = { '\xef', '\xbb', '\xbf' };
  1778. const char sigUnicode[] = { '\xff', '\xfe' };
  1779. char sig[4];
  1780. const unsigned int len = sizeof sig;
  1781. BOOL fResult = fp != NULL;
  1782. if (fp != NULL && fread(sig, len, 1, fp)) {
  1783. fResult = memcmp(sig, sigUTF8, __min(len, sizeof sigUTF8))
  1784. && memcmp(sig, sigUnicode, __min(len, sizeof sigUnicode));
  1785. }
  1786. fseek(fp, 0, SEEK_SET);
  1787. return fResult;
  1788. }
  1789. // OpenValidateMakefile - Open a makefile, only if it's valid.
  1790. //
  1791. // Scope: GLOBAL.
  1792. //
  1793. // Purpose:
  1794. // We don't want to open UTF8 or unicode makefiles, only to report an
  1795. // error at some random place in the makefile.
  1796. //
  1797. // Input:
  1798. // file -- File pointer.
  1799. //
  1800. // Output: -- Returns FALSE if in UTF8 or Unicode format
  1801. //
  1802. // History:
  1803. FILE *OpenValidateMakefile(char *name,char *mode)
  1804. {
  1805. FILE *fp = open_file(name, mode);
  1806. if (fp != NULL && !IsValidMakefile(fp))
  1807. {
  1808. fclose(fp);
  1809. makeError(0, CANT_SUPPORT_UNICODE, 0);
  1810. }
  1811. return fp;
  1812. }