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.

590 lines
17KB

  1. /*===========================================================================
  2. Copyright (c) 1998-2000, The Santa Cruz Operation
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. *Redistributions of source code must retain the above copyright notice,
  7. this list of conditions and the following disclaimer.
  8. *Redistributions in binary form must reproduce the above copyright notice,
  9. this list of conditions and the following disclaimer in the documentation
  10. and/or other materials provided with the distribution.
  11. *Neither name of The Santa Cruz Operation nor the names of its contributors
  12. may be used to endorse or promote products derived from this software
  13. without specific prior written permission.
  14. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS
  15. IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT falseT LIMITED TO,
  16. THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  17. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
  18. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  19. CONSEQUENTIAL DAMAGES (INCLUDING, BUT falseT LIMITED TO, PROCUREMENT OF
  20. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  21. INTERRUPTION)
  22. HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  23. LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  24. OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
  25. DAMAGE.
  26. =========================================================================*/
  27. /* cscope - interactive C symbol cross-reference
  28. *
  29. * main functions
  30. */
  31. #include "global.h"
  32. #include "build.h"
  33. #include "vp.h"
  34. #include "version.h" /* FILEVERSION and FIXVERSION */
  35. #include "scanner.h"
  36. #include <stdlib.h> /* atoi */
  37. #include <ncurses.h>
  38. #include <sys/types.h> /* needed by stat.h */
  39. #include <sys/stat.h> /* stat */
  40. #include <signal.h>
  41. #include <getopt.h>
  42. /* defaults for unset environment variables */
  43. #define EDITOR "vi"
  44. #define HOME "/" /* no $HOME --> use root directory */
  45. #define SHELL "sh"
  46. #define LINEFLAG "+%s" /* default: used by vi and emacs */
  47. #define TMPDIR "/tmp"
  48. /* note: these digraph character frequencies were calculated from possible
  49. printable digraphs in the cross-reference for the C compiler */
  50. char dichar1[] = " teisaprnl(of)=c"; /* 16 most frequent first chars */
  51. char dichar2[] = " tnerpla"; /* 8 most frequent second chars
  52. using the above as first chars */
  53. char dicode1[256]; /* digraph first character code */
  54. char dicode2[256]; /* digraph second character code */
  55. char *editor, *shell, *lineflag; /* environment variables */
  56. char *home; /* Home directory */
  57. bool lineflagafterfile;
  58. char *argv0; /* command name */
  59. bool compress = true; /* compress the characters in the crossref */
  60. bool dbtruncated; /* database symbols are truncated to 8 chars */
  61. int dispcomponents = 1; /* file path components to display */
  62. bool editallprompt = true; /* prompt between editing files */
  63. unsigned int fileargc; /* file argument count */
  64. char **fileargv; /* file argument values */
  65. int fileversion; /* cross-reference file version */
  66. bool incurses = false; /* in curses */
  67. bool invertedindex; /* the database has an inverted index */
  68. bool isuptodate; /* consider the crossref up-to-date */
  69. bool kernelmode; /* don't use DFLT_INCDIR - bad for kernels */
  70. bool linemode = false; /* use line oriented user interface */
  71. bool verbosemode = false; /* print extra information on line mode */
  72. bool recurse_dir = false; /* recurse dirs when searching for src files */
  73. char *namefile; /* file of file names */
  74. bool ogs = false; /* display OGS book and subsystem names */
  75. char *prependpath; /* prepend path to file names */
  76. FILE *refsfound; /* references found file */
  77. char temp1[PATHLEN + 1]; /* temporary file name */
  78. char temp2[PATHLEN + 1]; /* temporary file name */
  79. char tempdirpv[PATHLEN + 1]; /* private temp directory */
  80. long totalterms; /* total inverted index terms */
  81. bool trun_syms; /* truncate symbols to 8 characters */
  82. char tempstring[TEMPSTRING_LEN + 1]; /* use this as a buffer, instead of 'yytext',
  83. * which had better be left alone */
  84. char *tmpdir; /* temporary directory */
  85. static char path[PATHLEN + 1]; /* file path */
  86. /* Internal prototypes: */
  87. static void skiplist(FILE *oldrefs);
  88. static void initcompress(void);
  89. static inline void readenv(void);
  90. static inline void linemode_event_loop(void);
  91. static inline void screenmode_event_loop(void);
  92. static inline void siginit(void) {
  93. /* if running in the foreground */
  94. if(signal(SIGINT, SIG_IGN) != SIG_IGN) {
  95. /* cleanup on the interrupt and quit signals */
  96. signal(SIGINT, myexit);
  97. signal(SIGQUIT, myexit);
  98. }
  99. /* cleanup on the hangup signal */
  100. signal(SIGHUP, myexit);
  101. /* ditto the TERM signal */
  102. signal(SIGTERM, myexit);
  103. /* ignore PIPE signal, so myexit() will have a chance to clean up in
  104. * linemode, while in curses mode the "|" command can cause a pipe signal
  105. * too
  106. */
  107. signal(SIGPIPE, SIG_IGN);
  108. //if(linemode == false) { signal(SIGWINCH, redisplay); }
  109. }
  110. void cannotopen(const char *const file) {
  111. posterr("Cannot open file %s", file);
  112. }
  113. /* FIXME MTE - should use postfatal here */
  114. void cannotwrite(const char *const file) {
  115. char msg[MSGLEN + 1];
  116. snprintf(msg, sizeof(msg), "Removed file %s because write failed", file);
  117. myperror(msg); /* display the reason */
  118. unlink(file);
  119. myexit(1); /* calls exit(2), which closes files */
  120. }
  121. /* set up the digraph character tables for text compression */
  122. static void initcompress(void) {
  123. int i;
  124. if(compress == true) {
  125. for(i = 0; i < 16; ++i) {
  126. dicode1[(unsigned char)(dichar1[i])] = i * 8 + 1;
  127. }
  128. for(i = 0; i < 8; ++i) {
  129. dicode2[(unsigned char)(dichar2[i])] = i + 1;
  130. }
  131. }
  132. }
  133. /* skip the list in the cross-reference file */
  134. static void skiplist(FILE *oldrefs) {
  135. int i;
  136. if(fscanf(oldrefs, "%d", &i) != 1) {
  137. postfatal(PROGRAM_NAME ": cannot read list size from file %s\n", reffile);
  138. /* NOTREACHED */
  139. }
  140. while(--i >= 0) {
  141. if(fscanf(oldrefs, "%*s") != 0) {
  142. postfatal(PROGRAM_NAME ": cannot read list name from file %s\n", reffile);
  143. /* NOTREACHED */
  144. }
  145. }
  146. }
  147. /* cleanup and exit */
  148. void myexit(int sig) {
  149. /* Close file before unlinking it. DOS absolutely needs it */
  150. if(refsfound != NULL) { fclose(refsfound); }
  151. /* remove any temporary files */
  152. if(temp1[0] != '\0') {
  153. unlink(temp1);
  154. unlink(temp2);
  155. rmdir(tempdirpv);
  156. }
  157. /* restore the terminal to its original mode */
  158. if(incurses == true) { exitcurses(); }
  159. /* dump core for debugging on the quit signal */
  160. if(sig == SIGQUIT) { abort(); }
  161. /* HBB 20000421: be nice: free allocated data */
  162. freefilelist();
  163. freeinclist();
  164. freesrclist();
  165. freecrossref();
  166. free_newbuildfiles();
  167. if(remove_symfile_onexit == true) {
  168. unlink(reffile);
  169. unlink(invname);
  170. unlink(invpost);
  171. }
  172. exit(sig);
  173. }
  174. static inline void readenv(void) {
  175. editor = mygetenv("EDITOR", EDITOR);
  176. editor = mygetenv("VIEWER", editor); /* use viewer if set */
  177. editor = mygetenv("CSCOPE_EDITOR", editor); /* has last word */
  178. home = mygetenv("HOME", HOME);
  179. shell = mygetenv("SHELL", SHELL);
  180. lineflag = mygetenv("CSCOPE_LINEFLAG", LINEFLAG);
  181. lineflagafterfile = getenv("CSCOPE_LINEFLAG_AFTER_FILE") ? 1 : 0;
  182. tmpdir = mygetenv("TMPDIR", TMPDIR);
  183. }
  184. static inline void linemode_event_loop(void) {
  185. int c;
  186. if(*input_line != '\0') { /* do any optional search */
  187. if(search(input_line) == true) {
  188. /* print the total number of lines in
  189. * verbose mode */
  190. if(verbosemode == true) printf(PROGRAM_NAME ": %d lines\n", totallines);
  191. while((c = getc(refsfound)) != EOF)
  192. putchar(c);
  193. }
  194. }
  195. if(onesearch == true) {
  196. myexit(0);
  197. /* NOTREACHED */
  198. }
  199. for(char *s;;) {
  200. char buf[PATLEN + 2];
  201. printf(">> ");
  202. fflush(stdout);
  203. if(fgets(buf, sizeof(buf), stdin) == NULL) { myexit(0); }
  204. /* remove any trailing newline character */
  205. if(*(s = buf + strlen(buf) - 1) == '\n') { *s = '\0'; }
  206. switch(*buf) {
  207. case '0':
  208. case '1':
  209. case '2':
  210. case '3':
  211. case '4':
  212. case '5':
  213. case '6':
  214. case '7':
  215. case '8':
  216. case '9': /* samuel only */
  217. field = *buf - '0';
  218. strcpy(input_line, buf + 1);
  219. if(search(input_line) == false) {
  220. printf("Unable to search database\n");
  221. } else {
  222. printf("cscope: %d lines\n", totallines);
  223. while((c = getc(refsfound)) != EOF) {
  224. putchar(c);
  225. }
  226. }
  227. break;
  228. case 'c': /* toggle caseless mode */
  229. case ctrl('C'):
  230. if(caseless == false) {
  231. caseless = true;
  232. } else {
  233. caseless = false;
  234. }
  235. egrepcaseless(caseless);
  236. break;
  237. case 'r': /* rebuild database cscope style */
  238. case ctrl('R'):
  239. freefilelist();
  240. makefilelist();
  241. /* FALLTHROUGH */
  242. case 'R': /* rebuild database samuel style */
  243. rebuild();
  244. putchar('\n');
  245. break;
  246. case 'C': /* clear file names */
  247. freefilelist();
  248. putchar('\n');
  249. break;
  250. case 'F': /* add a file name */
  251. strcpy(path, buf + 1);
  252. if(infilelist(path) == false && (s = inviewpath(path)) != NULL) {
  253. addsrcfile(s);
  254. }
  255. putchar('\n');
  256. break;
  257. case 'q': /* quit */
  258. case ctrl('D'):
  259. case ctrl('Z'):
  260. myexit(0);
  261. /* NOTREACHED */
  262. break;
  263. default:
  264. fprintf(stderr, PROGRAM_NAME ": unknown command '%s'\n", buf);
  265. break;
  266. }
  267. }
  268. }
  269. static inline void screenmode_event_loop(void) {
  270. for(;;) {
  271. display();
  272. handle_input(wgetch(stdscr)); // NOTE: getch() does not return KEY_* codes
  273. }
  274. }
  275. int main(int argc, char **argv) {
  276. FILE *names; /* name file pointer */
  277. int oldnum; /* number in old cross-ref */
  278. FILE *oldrefs; /* old cross-reference file */
  279. char *s;
  280. unsigned int i;
  281. pid_t pid;
  282. struct stat stat_buf;
  283. mode_t orig_umask;
  284. yyin = stdin;
  285. yyout = stdout;
  286. /* save the command name for messages */
  287. argv0 = argv[0];
  288. /* set the options */
  289. argv = parse_options(&argc, argv);
  290. /* read the environment */
  291. readenv();
  292. /* XXX remove if/when clearerr() in dir.c does the right thing. */
  293. if(namefile && strcmp(namefile, "-") == 0 && !buildonly) {
  294. postfatal(PROGRAM_NAME ": Must use -b if file list comes from stdin\n");
  295. /* NOTREACHED */
  296. }
  297. /* make sure that tmpdir exists */
  298. if(lstat(tmpdir, &stat_buf)) {
  299. fprintf(stderr,
  300. PROGRAM_NAME
  301. ": Temporary directory %s does not exist or cannot be accessed\n",
  302. tmpdir);
  303. fprintf(stderr,
  304. PROGRAM_NAME
  305. ": Please create the directory or set the environment variable\n" PROGRAM_NAME
  306. ": TMPDIR to a valid directory\n");
  307. myexit(1);
  308. }
  309. /* create the temporary file names */
  310. orig_umask = umask(S_IRWXG | S_IRWXO);
  311. pid = getpid();
  312. snprintf(tempdirpv, sizeof(tempdirpv), "%s/" PROGRAM_NAME ".%d", tmpdir, pid);
  313. if(mkdir(tempdirpv, S_IRWXU)) {
  314. fprintf(stderr,
  315. PROGRAM_NAME ": Could not create private temp dir %s\n",
  316. tempdirpv);
  317. myexit(1);
  318. }
  319. umask(orig_umask);
  320. snprintf(temp1, sizeof(temp1), "%s/" PROGRAM_NAME ".1", tempdirpv);
  321. snprintf(temp2, sizeof(temp2), "%s/" PROGRAM_NAME ".2", tempdirpv);
  322. /* if the database path is relative and it can't be created */
  323. if(reffile[0] != '/' && access(".", WRITE) != 0) {
  324. /* put it in the home directory if the database may not be
  325. * up-to-date or doesn't exist in the relative directory,
  326. * so a database in the current directory will be
  327. * used instead of failing to open a non-existant database in
  328. * the home directory
  329. */
  330. snprintf(path, sizeof(path), "%s/%s", home, reffile);
  331. if(isuptodate == false || access(path, READ) == 0) {
  332. reffile = strdup(path);
  333. snprintf(path, sizeof(path), "%s/%s", home, invname);
  334. invname = strdup(path);
  335. snprintf(path, sizeof(path), "%s/%s", home, invpost);
  336. invpost = strdup(path);
  337. }
  338. }
  339. siginit();
  340. if(linemode == false) {
  341. dispinit(); /* initialize display parameters */
  342. postmsg(""); /* clear any build progress message */
  343. display(); /* display the version number and input fields */
  344. }
  345. /* if the cross-reference is to be considered up-to-date */
  346. if(isuptodate == true) {
  347. if((oldrefs = vpfopen(reffile, "rb")) == NULL) {
  348. postfatal(PROGRAM_NAME ": cannot open file %s\n", reffile);
  349. /* NOTREACHED */
  350. }
  351. /* get the crossref file version but skip the current directory */
  352. if(fscanf(oldrefs, PROGRAM_NAME " %d %*s", &fileversion) != 1) {
  353. postfatal(PROGRAM_NAME ": cannot read file version from file %s\n", reffile);
  354. /* NOTREACHED */
  355. }
  356. if(fileversion >= 8) {
  357. /* override these command line options */
  358. compress = true;
  359. invertedindex = false;
  360. /* see if there are options in the database */
  361. for(int c;;) {
  362. getc(oldrefs); /* skip the blank */
  363. if((c = getc(oldrefs)) != '-') {
  364. ungetc(c, oldrefs);
  365. break;
  366. }
  367. switch(getc(oldrefs)) {
  368. case 'c': /* ASCII characters only */
  369. compress = false;
  370. break;
  371. case 'q': /* quick search */
  372. invertedindex = true;
  373. fscanf(oldrefs, "%ld", &totalterms);
  374. break;
  375. case 'T': /* truncate symbols to 8 characters */
  376. dbtruncated = true;
  377. trun_syms = true;
  378. break;
  379. }
  380. }
  381. initcompress();
  382. seek_to_trailer(oldrefs);
  383. }
  384. /* skip the source and include directory lists */
  385. skiplist(oldrefs);
  386. skiplist(oldrefs);
  387. /* get the number of source files */
  388. if(fscanf(oldrefs, "%lu", &nsrcfiles) != 1) {
  389. postfatal(PROGRAM_NAME ": cannot read source file size from file %s\n",
  390. reffile);
  391. /* NOTREACHED */
  392. }
  393. /* get the source file list */
  394. srcfiles = malloc(nsrcfiles * sizeof(*srcfiles));
  395. if(fileversion >= 9) {
  396. /* allocate the string space */
  397. if(fscanf(oldrefs, "%d", &oldnum) != 1) {
  398. postfatal(PROGRAM_NAME ": cannot read string space size from file %s\n",
  399. reffile);
  400. /* NOTREACHED */
  401. }
  402. s = malloc(oldnum);
  403. getc(oldrefs); /* skip the newline */
  404. /* read the strings */
  405. if(fread(s, oldnum, 1, oldrefs) != 1) {
  406. postfatal(PROGRAM_NAME ": cannot read source file names from file %s\n",
  407. reffile);
  408. /* NOTREACHED */
  409. }
  410. /* change newlines to nulls */
  411. for(i = 0; i < nsrcfiles; ++i) {
  412. srcfiles[i] = s;
  413. for(++s; *s != '\n'; ++s) {
  414. ;
  415. }
  416. *s = '\0';
  417. ++s;
  418. }
  419. /* if there is a file of source file names */
  420. if((namefile != NULL && (names = vpfopen(namefile, "r")) != NULL) ||
  421. (names = vpfopen(NAMEFILE, "r")) != NULL) {
  422. /* read any -p option from it */
  423. while(fgets(path, sizeof(path), names) != NULL && *path == '-') {
  424. i = path[1];
  425. s = path + 2; /* for "-Ipath" */
  426. if(*s == '\0') { /* if "-I path" */
  427. fgets(path, sizeof(path), names);
  428. s = path;
  429. }
  430. switch(i) {
  431. case 'p': /* file path components to display */
  432. if(*s < '0' || *s > '9') {
  433. posterr(PROGRAM_NAME
  434. ": -p option in file %s: missing or invalid numeric value\n",
  435. namefile);
  436. }
  437. dispcomponents = atoi(s);
  438. }
  439. }
  440. fclose(names);
  441. }
  442. } else {
  443. for(i = 0; i < nsrcfiles; ++i) {
  444. if(!fgets(path, sizeof(path), oldrefs)) {
  445. postfatal(PROGRAM_NAME
  446. ": cannot read source file name from file %s\n",
  447. reffile);
  448. /* NOTREACHED */
  449. }
  450. srcfiles[i] = strdup(path);
  451. }
  452. }
  453. fclose(oldrefs);
  454. } else {
  455. /* save the file arguments */
  456. fileargc = argc;
  457. fileargv = argv;
  458. /* get source directories from the environment */
  459. if((s = getenv("SOURCEDIRS")) != NULL) { sourcedir(s); }
  460. /* make the source file list */
  461. srcfiles = malloc(msrcfiles * sizeof(*srcfiles));
  462. makefilelist();
  463. if(nsrcfiles == 0) {
  464. postfatal(PROGRAM_NAME ": no source files found\n");
  465. /* NOTREACHED */
  466. }
  467. /* get include directories from the environment */
  468. if((s = getenv("INCLUDEDIRS")) != NULL) { includedir(s); }
  469. /* add /usr/include to the #include directory list,
  470. but not in kernelmode... kernels tend not to use it. */
  471. if(kernelmode == false) {
  472. if(NULL != (s = getenv("INCDIR"))) {
  473. includedir(s);
  474. } else {
  475. includedir(DFLT_INCDIR);
  476. }
  477. }
  478. /* initialize the C keyword table */
  479. initsymtab();
  480. /* Tell build.c about the filenames to create: */
  481. setup_build_filenames(reffile);
  482. /* build the cross-reference */
  483. initcompress();
  484. if(linemode == false || verbosemode == true) { /* display if verbose as well */
  485. postmsg("Building cross-reference...");
  486. }
  487. build();
  488. if(linemode == false) { postmsg(""); /* clear any build progress message */ }
  489. if(buildonly == true) {
  490. myexit(0);
  491. /* NOTREACHED */
  492. }
  493. }
  494. opendatabase();
  495. /* if using the line oriented user interface so cscope can be a
  496. subprocess to emacs or samuel */
  497. if(linemode == true) { linemode_event_loop(); }
  498. /* pause before clearing the screen if there have been error messages */
  499. if(errorsfound == true) {
  500. errorsfound = false;
  501. askforreturn();
  502. }
  503. /* do any optional search */
  504. if(*input_line != '\0') {
  505. // command(ctrl('Y')); /* search */ // XXX: fix
  506. } else if(reflines != NULL) {
  507. /* read any symbol reference lines file */
  508. readrefs(reflines);
  509. }
  510. screenmode_event_loop();
  511. /* cleanup and exit */
  512. myexit(0);
  513. /* NOTREACHED */
  514. return 0; /* avoid warning... */
  515. }