fixincl.c 36.6 KB
Newer Older
1

korbb's avatar
korbb committed
2 3 4 5
/* Install modified versions of certain ANSI-incompatible system header
   files which are fixed to work correctly with ANSI C and placed in a
   directory that GNU C will search.

law's avatar
law committed
6
   Copyright (C) 1997, 1998, 1999, 2000 Free Software Foundation, Inc.
korbb's avatar
korbb committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

This file is part of GNU CC.

GNU CC is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU CC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU CC; see the file COPYING.  If not, write to
the Free Software Foundation, 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.  */

korbb's avatar
korbb committed
25 26
#include "fixlib.h"

27
#if defined( HAVE_MMAP_FILE )
28 29 30
#include <sys/mman.h>
#define  BAD_ADDR ((void*)-1)
#endif
korbb's avatar
korbb committed
31

32
#include <signal.h>
33
#ifndef __MSDOS__
34
#include "server.h"
35
#endif
36

korbb's avatar
korbb committed
37 38
/*  The contents of this string are not very important.  It is mostly
    just used as part of the "I am alive and working" test.  */
39

korbb's avatar
korbb committed
40
static const char program_id[] = "fixincl version 1.1";
41

42 43 44 45 46 47 48 49 50
/*  This format will be used at the start of every generated file */

static const char z_std_preamble[] =
"/*  DO NOT EDIT THIS FILE.\n\n\
    It has been auto-edited by fixincludes from:\n\n\
\t\"%s/%s\"\n\n\
    This had to be done to correct non-standard usages in the\n\
    original, manufacturer supplied header file.  */\n\n";

korbb's avatar
korbb committed
51
/*  Working environment strings.  Essentially, invocation 'options'.  */
52 53 54 55 56

#define _ENV_(v,m,n,t)   tCC* v = NULL;
ENV_TABLE
#undef _ENV_

57
int find_base_len = 0;
korbb's avatar
korbb committed
58

59 60 61 62 63 64 65 66 67 68
typedef enum {
  VERB_SILENT = 0,
  VERB_FIXES,
  VERB_APPLIES,
  VERB_PROGRESS,
  VERB_TESTS,
  VERB_EVERYTHING
} te_verbose;

te_verbose  verbose_level = VERB_PROGRESS;
69
int have_tty = 0;
70 71 72 73

#define VLEVEL(l)  (verbose_level >= l)
#define NOT_SILENT VLEVEL(VERB_FIXES)

korbb's avatar
korbb committed
74 75
pid_t process_chain_head = (pid_t) -1;

korbb's avatar
korbb committed
76 77
char*  pz_curr_file;  /*  name of the current file under test/fix  */
char*  pz_curr_data;  /*  original contents of that file  */
78 79
char*  pz_temp_file;  /*  for DOS, a place to stash the temporary
                          fixed data between system(3) calls  */
korbb's avatar
korbb committed
80 81 82 83
t_bool curr_data_mapped;
int    data_map_fd;
size_t data_map_size;
size_t ttl_data_size = 0;
84

korbb's avatar
korbb committed
85 86 87 88 89 90 91
#ifdef DO_STATS
int process_ct = 0;
int apply_ct = 0;
int fixed_ct = 0;
int altered_ct = 0;
#endif /* DO_STATS */

korbb's avatar
korbb committed
92
const char incl_quote_pat[] = "^[ \t]*#[ \t]*include[ \t]*\"[^/]";
korbb's avatar
korbb committed
93
tSCC z_fork_err[] = "Error %d (%s) starting filter process for %s\n";
korbb's avatar
korbb committed
94 95
regex_t incl_quote_re;

korbb's avatar
korbb committed
96
void do_version ();
97 98
char *load_file  _P_((const char *));
void process  _P_((char *, const char *));
korbb's avatar
korbb committed
99
void run_compiles ();
100
void initialize _P_((int argc,char** argv));
korbb's avatar
korbb committed
101 102 103
void process ();

/*  External Source Code */
104 105 106

#include "fixincl.x"

korbb's avatar
korbb committed
107 108 109 110
/* * * * * * * * * * * * * * * * * * *
 *
 *  MAIN ROUTINE
 */
111 112 113 114 115
int
main (argc, argv)
     int argc;
     char **argv;
{
korbb's avatar
korbb committed
116
  char *file_name_buf;
117

118
  initialize ( argc, argv );
korbb's avatar
korbb committed
119

120 121
  have_tty = isatty (fileno (stderr));

korbb's avatar
korbb committed
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
  /* Before anything else, ensure we can allocate our file name buffer. */
  file_name_buf = load_file_data (stdin);

  /*  Because of the way server shells work, you have to keep stdin, out
      and err open so that the proper input file does not get closed
      by accident  */

  freopen ("/dev/null", "r", stdin);

  if (file_name_buf == (char *) NULL)
    {
      fputs ("No file names listed for fixing\n", stderr);
      exit (EXIT_FAILURE);
    }

korbb's avatar
korbb committed
137 138
  for (;;)
    {
korbb's avatar
korbb committed
139
      char* pz_end;
korbb's avatar
korbb committed
140

korbb's avatar
korbb committed
141
      /*  skip to start of name, past any "./" prefixes */
korbb's avatar
korbb committed
142

korbb's avatar
korbb committed
143 144 145
      while (ISSPACE (*file_name_buf))  file_name_buf++;
      while ((file_name_buf[0] == '.') && (file_name_buf[1] == '/'))
        file_name_buf += 2;
korbb's avatar
korbb committed
146

korbb's avatar
korbb committed
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
      /*  Check for end of list  */

      if (*file_name_buf == NUL)
        break;

      /*  Set global file name pointer and find end of name */

      pz_curr_file = file_name_buf;
      pz_end = strchr( pz_curr_file, '\n' );
      if (pz_end == (char*)NULL)
        pz_end = file_name_buf = pz_curr_file + strlen (pz_curr_file);
      else
        file_name_buf = pz_end + 1;

      while ((pz_end > pz_curr_file) && ISSPACE( pz_end[-1]))  pz_end--;

      /*  IF no name is found (blank line) or comment marker, skip line  */

      if ((pz_curr_file == pz_end) || (*pz_curr_file == '#'))
        continue;
      *pz_end = NUL;
korbb's avatar
korbb committed
168

korbb's avatar
korbb committed
169 170
      process ();
    } /*  for (;;) */
korbb's avatar
korbb committed
171

korbb's avatar
korbb committed
172
#ifdef DO_STATS
173
  if (VLEVEL( VERB_PROGRESS )) {
korbb's avatar
korbb committed
174 175 176 177 178 179 180 181 182 183
    tSCC zFmt[] =
      "\
Processed %5d files containing %d bytes    \n\
Applying  %5d fixes to %d files\n\
Altering  %5d of them\n";

    fprintf (stderr, zFmt, process_ct, ttl_data_size, apply_ct,
             fixed_ct, altered_ct);
  }
#endif /* DO_STATS */
184 185 186 187

# ifdef __MSDOS__
  unlink( pz_temp_file );
# endif
korbb's avatar
korbb committed
188 189 190 191
  return EXIT_SUCCESS;
}


korbb's avatar
korbb committed
192 193 194 195 196 197 198 199
void
do_version ()
{
  static const char zFmt[] = "echo '%s'";
  char zBuf[ 1024 ];

  /* The 'version' option is really used to test that:
     1.  The program loads correctly (no missing libraries)
200 201
     2.  that we can compile all the regular expressions.
     3.  we can correctly run our server shell process
korbb's avatar
korbb committed
202 203 204
  */
  run_compiles ();
  sprintf (zBuf, zFmt, program_id);
205
#ifndef __MSDOS__
206
  puts (zBuf + 5);
korbb's avatar
korbb committed
207
  exit (strcmp (run_shell (zBuf), program_id));
208 209 210
#else
  exit (system (zBuf));
#endif
korbb's avatar
korbb committed
211 212
}

korbb's avatar
korbb committed
213 214 215
/* * * * * * * * * * * * */

void
216 217 218
initialize ( argc, argv )
  int argc;
  char** argv;
korbb's avatar
korbb committed
219 220
{
  static const char var_not_found[] =
221 222 223 224 225 226 227 228
    "fixincl ERROR:  %s environment variable not defined\n"
#ifdef __STDC__
    "each of these must be defined:\n"
#define _ENV_(v,m,n,t) "\t" n "  - " t "\n"
ENV_TABLE
#undef _ENV_
#endif
    ;
korbb's avatar
korbb committed
229

230 231
  xmalloc_set_program_name (argv[0]);

232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
  switch (argc)
    {
    case 1:
      break;

    case 2:
      if (strcmp (argv[1], "-v") == 0)
        do_version ();
      if (freopen (argv[1], "r", stdin) == (FILE*)NULL)
        {
          fprintf (stderr, "Error %d (%s) reopening %s as stdin\n",
                   errno, xstrerror (errno), argv[1] );
          exit (EXIT_FAILURE);
        }
      break;

    default:
      fputs ("fixincl ERROR:  too many command line arguments\n", stderr);
      exit (EXIT_FAILURE);
    }

253 254 255 256
#define _ENV_(v,m,n,t)   { tSCC var[] = n;  \
  v = getenv (var); if (m && (v == NULL)) { \
  fprintf (stderr, var_not_found, var);     \
  exit (EXIT_FAILURE); } }
257

258
ENV_TABLE
259

260
#undef _ENV_
261

262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
  if (isdigit( *pz_verbose ))
    verbose_level = (te_verbose)atoi( pz_verbose );
  else
    switch (*pz_verbose) {
    case 's':
    case 'S':
      verbose_level = VERB_SILENT;     break;

    case 'f':
    case 'F':
      verbose_level = VERB_FIXES;      break;

    case 'a':
    case 'A':
      verbose_level = VERB_APPLIES;    break;

    case 'p':
    case 'P':
      verbose_level = VERB_PROGRESS;   break;

    case 't':
    case 'T':
      verbose_level = VERB_TESTS;      break;

    case 'e':
    case 'E':
      verbose_level = VERB_EVERYTHING; break;
    }
290

291 292 293 294
 while ((pz_find_base[0] == '.') && (pz_find_base[1] == '/'))
   pz_find_base += 2;
 if ((pz_find_base[0] != '.') || (pz_find_base[1] != NUL))
   find_base_len = strlen( pz_find_base );
295

korbb's avatar
korbb committed
296 297 298 299
  /*  Compile all the regular expressions now.
      That way, it is done only once for the whole run.
      */
  run_compiles ();
300

301 302 303 304 305 306
# ifdef __MSDOS__
  /* NULL as the first argument to `tempnam' causes it to DTRT
     wrt the temporary directory where the file will be created.  */
  pz_temp_file = tempnam( NULL, "fxinc" );
# endif

korbb's avatar
korbb committed
307
  signal (SIGQUIT, SIG_IGN);
308
#ifdef SIGIOT
korbb's avatar
korbb committed
309
  signal (SIGIOT,  SIG_IGN);
310
#endif
311
#ifdef SIGPIPE
korbb's avatar
korbb committed
312
  signal (SIGPIPE, SIG_IGN);
313
#endif
korbb's avatar
korbb committed
314 315
  signal (SIGALRM, SIG_IGN);
  signal (SIGTERM, SIG_IGN);
316 317
}

korbb's avatar
korbb committed
318
/* * * * * * * * * * * * *
korbb's avatar
korbb committed
319

korbb's avatar
korbb committed
320 321 322 323
   load_file loads all the contents of a file into malloc-ed memory.
   Its argument is the name of the file to read in; the returned
   result is the NUL terminated contents of the file.  The file
   is presumed to be an ASCII text file containing no NULs.  */
324
char *
korbb's avatar
korbb committed
325 326
load_file ( fname )
    const char* fname;
327
{
korbb's avatar
korbb committed
328 329
  struct stat stbf;
  char* res;
330

korbb's avatar
korbb committed
331
  if (stat (fname, &stbf) != 0)
332
    {
333 334
      if (NOT_SILENT)
        fprintf (stderr, "error %d (%s) stat-ing %s\n",
335
                 errno, xstrerror (errno), fname );
korbb's avatar
korbb committed
336
      return (char *) NULL;
337
    }
korbb's avatar
korbb committed
338 339
  if (stbf.st_size == 0)
    return (char*)NULL;
340

341 342 343 344
  /*  Make the data map size one larger than the file size for documentation
      purposes.  Truth is that there will be a following NUL character if
      the file size is not a multiple of the page size.  If it is a multiple,
      then this adjustment sometimes fails anyway.  */
korbb's avatar
korbb committed
345 346 347
  data_map_size = stbf.st_size+1;
  data_map_fd   = open (fname, O_RDONLY);
  ttl_data_size += data_map_size-1;
348

korbb's avatar
korbb committed
349 350
  if (data_map_fd < 0)
    {
351 352
      if (NOT_SILENT)
        fprintf (stderr, "error %d (%s) opening %s for read\n",
353
                 errno, xstrerror (errno), fname);
korbb's avatar
korbb committed
354 355
      return (char*)NULL;
    }
356

357
#ifdef HAVE_MMAP_FILE
korbb's avatar
korbb committed
358
  curr_data_mapped = BOOL_TRUE;
359 360 361

  /*  IF the file size is a multiple of the page size,
      THEN sometimes you will seg fault trying to access a trailing byte */
korbb's avatar
korbb committed
362
  if ((stbf.st_size & (getpagesize()-1)) == 0)
363 364 365 366
    res = (char*)BAD_ADDR;
  else
    res = (char*)mmap ((void*)NULL, data_map_size, PROT_READ,
                       MAP_PRIVATE, data_map_fd, 0);
korbb's avatar
korbb committed
367 368 369 370 371 372 373 374 375
  if (res == (char*)BAD_ADDR)
    {
      curr_data_mapped = BOOL_FALSE;
      res = load_file_data ( fdopen (data_map_fd, "r"));
    }
#else
  curr_data_mapped = BOOL_FALSE;
  res = load_file_data ( fdopen (data_map_fd, "r"));
#endif
376

korbb's avatar
korbb committed
377
  return res;
378 379
}

380 381 382
int
machine_matches( p_fixd )
  tFixDesc *p_fixd;
korbb's avatar
korbb committed
383
        {
384
# ifndef __MSDOS__
korbb's avatar
korbb committed
385
          tSCC case_fmt[] = "case %s in\n";     /*  9 bytes, plus string */
386 387
          tSCC esac_fmt[] =
               " )\n    echo %s ;;\n* ) echo %s ;;\nesac";/*  4 bytes */
korbb's avatar
korbb committed
388 389 390 391
          tSCC skip[] = "skip";                 /*  4 bytes */
          tSCC run[] = "run";                   /*  3 bytes */
          /* total bytes to add to machine sum:    49 - see fixincl.tpl */

korbb's avatar
korbb committed
392
          const char **papz_machs = p_fixd->papz_machs;
korbb's avatar
korbb committed
393
          char *pz;
korbb's avatar
korbb committed
394 395 396
          char *pz_sep = "";
          tCC *pz_if_true;
          tCC *pz_if_false;
korbb's avatar
korbb committed
397
          char cmd_buf[ MACH_LIST_SIZE_LIMIT ]; /* size lim from fixincl.tpl */
korbb's avatar
korbb committed
398

korbb's avatar
korbb committed
399
          /* Start the case statement */
korbb's avatar
korbb committed
400

korbb's avatar
korbb committed
401 402
          sprintf (cmd_buf, case_fmt, pz_machine);
          pz = cmd_buf + strlen (cmd_buf);
korbb's avatar
korbb committed
403

korbb's avatar
korbb committed
404
          /*  Determine if a match means to apply the fix or not apply it */
korbb's avatar
korbb committed
405 406 407 408 409 410 411 412 413 414 415 416

          if (p_fixd->fd_flags & FD_MACH_IFNOT)
            {
              pz_if_true  = skip;
              pz_if_false = run;
            }
          else
            {
              pz_if_true  = run;
              pz_if_false = skip;
            }

korbb's avatar
korbb committed
417 418
          /*  Emit all the machine names.  If there are more than one,
              then we will insert " | \\\n" between the names  */
korbb's avatar
korbb committed
419 420 421 422 423 424 425

          for (;;)
            {
              const char* pz_mach = *(papz_machs++);

              if (pz_mach == (const char*) NULL)
                break;
korbb's avatar
korbb committed
426
              sprintf (pz, "%s%s", pz_sep, pz_mach);
korbb's avatar
korbb committed
427 428 429
              pz += strlen (pz);
              pz_sep = " | \\\n";
            }
korbb's avatar
korbb committed
430 431 432 433

          /* Now emit the match and not-match actions and the esac */

          sprintf (pz, esac_fmt, pz_if_true, pz_if_false);
korbb's avatar
korbb committed
434 435 436 437

          /*  Run the script.
              The result will start either with 's' or 'r'.  */

korbb's avatar
korbb committed
438 439
          {
            int skip;
korbb's avatar
korbb committed
440
            pz = run_shell (cmd_buf);
korbb's avatar
korbb committed
441 442 443 444 445
            skip = (*pz == 's');
            free ( (void*)pz );
            if (skip)
              {
                p_fixd->fd_flags |= FD_SKIP_TEST;
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
		return BOOL_FALSE;
	      }
	  }

  return BOOL_TRUE;
# else /* is __MSDOS__ */
  const char **papz_machs = p_fixd->papz_machs;
  int invert = (p_fixd->fd_flags & FD_MACH_IFNOT) != 0;
  for (;;)
    {
      const char* pz_mach = *(papz_machs++);

      if (pz_mach == (const char*) NULL)
        break;
      if (strstr (pz_mach, "dos") != NULL && !invert)
	return BOOL_TRUE;
    }

  p_fixd->fd_flags |= FD_SKIP_TEST;
  return BOOL_FALSE;
# endif
}

/* * * * * * * * * * * * *

   run_compiles   run all the regexp compiles for all the fixes once.
   */
void
run_compiles ()
{
  tFixDesc *p_fixd = fixDescList;
  int fix_ct = FIX_COUNT;
  regex_t *p_re = (regex_t *) malloc (REGEX_COUNT * sizeof (regex_t));

  if (p_re == (regex_t *) NULL)
    {
      fprintf (stderr, "fixincl ERROR:  cannot allocate %d bytes for regex\n",
               REGEX_COUNT * sizeof (regex_t));
      exit (EXIT_FAILURE);
    }

  /*  Make sure compile_re does not stumble across invalid data */

  memset ( (void*)p_re, '\0', REGEX_COUNT * sizeof (regex_t) );
  memset ( (void*)&incl_quote_re, '\0', sizeof (regex_t) );

  compile_re (incl_quote_pat, &incl_quote_re, 1,
              "quoted include", "run_compiles");

  /*  Allow machine name tests to be ignored (testing, mainly) */

  if (pz_machine && ((*pz_machine == '\0') || (*pz_machine == '*')))
    pz_machine = (char*)NULL;

  /* FOR every fixup, ...  */
  do
    {
      tTestDesc *p_test = p_fixd->p_test_desc;
      int test_ct = p_fixd->test_ct;

      /*  IF the machine type pointer is not NULL (we are not in test mode)
             AND this test is for or not done on particular machines
          THEN ...   */

      if (  (pz_machine != NULL)
         && (p_fixd->papz_machs != (const char**) NULL)
         && ! machine_matches (p_fixd) )
        continue;
514

korbb's avatar
korbb committed
515 516 517
      /* FOR every test for the fixup, ...  */

      while (--test_ct >= 0)
518
        {
korbb's avatar
korbb committed
519
          switch (p_test->type)
520 521 522
            {
            case TT_EGREP:
            case TT_NEGREP:
korbb's avatar
korbb committed
523
              p_test->p_test_regex = p_re++;
524 525 526
              compile_re (p_test->pz_test_text, p_test->p_test_regex, 0,
                          "select test", p_fixd->fix_name);
            }
korbb's avatar
korbb committed
527
          p_test++;
528 529
        }
    }
korbb's avatar
korbb committed
530
  while (p_fixd++, --fix_ct > 0);
531 532 533
}


korbb's avatar
korbb committed
534
/* * * * * * * * * * * * *
korbb's avatar
korbb committed
535

korbb's avatar
korbb committed
536 537 538 539
   create_file  Create the output modified file.
   Input:    the name of the file to create
   Returns:  a file pointer to the new, open file  */

540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
#if defined(S_IRUSR) && defined(S_IWUSR) && \
    defined(S_IRGRP) && defined(S_IROTH)

#   define S_IRALL (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
#else
#   define S_IRALL 0644
#endif

#if defined(S_IRWXU) && defined(S_IRGRP) && defined(S_IXGRP) && \
    defined(S_IROTH) && defined(S_IXOTH)

#   define S_DIRALL (S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
#else
#   define S_DIRALL 0755
#endif

korbb's avatar
korbb committed
556

557
FILE *
korbb's avatar
korbb committed
558
create_file ()
559 560 561 562 563
{
  int fd;
  FILE *pf;
  char fname[MAXPATHLEN];

korbb's avatar
korbb committed
564
  sprintf (fname, "%s/%s", pz_dest_dir, pz_curr_file + find_base_len);
565

korbb's avatar
korbb committed
566
  fd = open (fname, O_WRONLY | O_CREAT | O_TRUNC, S_IRALL);
567

korbb's avatar
korbb committed
568
  /*  We may need to create the directories needed... */
569 570
  if ((fd < 0) && (errno == ENOENT))
    {
korbb's avatar
korbb committed
571
      char *pz_dir = strchr (fname + 1, '/');
572 573
      struct stat stbf;

korbb's avatar
korbb committed
574
      while (pz_dir != (char *) NULL)
575
        {
korbb's avatar
korbb committed
576
          *pz_dir = NUL;
577 578
          if (stat (fname, &stbf) < 0)
            {
579
              mkdir (fname, S_IFDIR | S_DIRALL);
580 581
            }

korbb's avatar
korbb committed
582 583
          *pz_dir = '/';
          pz_dir = strchr (pz_dir + 1, '/');
584
        }
korbb's avatar
korbb committed
585 586 587

      /*  Now, lets try the open again... */
      fd = open (fname, O_WRONLY | O_CREAT | O_TRUNC, S_IRALL);
588 589 590 591
    }
  if (fd < 0)
    {
      fprintf (stderr, "Error %d (%s) creating %s\n",
592
               errno, xstrerror (errno), fname);
593 594
      exit (EXIT_FAILURE);
    }
595 596
  if (NOT_SILENT)
    fprintf (stderr, "Fixed:  %s\n", pz_curr_file);
597 598
  pf = fdopen (fd, "w");

599 600 601 602 603 604 605 606 607
  /*
   *  IF pz_machine is NULL, then we are in some sort of test mode.
   *  Do not insert the current directory name.  Use a constant string.
   */
  fprintf (pf, z_std_preamble,
           (pz_machine == NULL)
           ? "fixinc/tests/inc"
           : pz_input_dir,
           pz_curr_file);
korbb's avatar
korbb committed
608

609 610 611 612
  return pf;
}


korbb's avatar
korbb committed
613
/* * * * * * * * * * * * *
614

korbb's avatar
korbb committed
615 616 617
  test_test   make sure a shell-style test expression passes.
  Input:  a pointer to the descriptor of the test to run and
          the name of the file that we might want to fix
korbb's avatar
korbb committed
618
  Result: APPLY_FIX or SKIP_FIX, depending on the result of the
korbb's avatar
korbb committed
619
          shell script we run.  */
620
#ifndef __MSDOS__
korbb's avatar
korbb committed
621 622
int
test_test (p_test, pz_test_file)
korbb's avatar
korbb committed
623
     tTestDesc *p_test;
korbb's avatar
korbb committed
624
     char*      pz_test_file;
korbb's avatar
korbb committed
625
{
626 627 628 629 630 631 632
  tSCC cmd_fmt[] =
"file=%s\n\
if ( test %s ) > /dev/null 2>&1\n\
then echo TRUE\n\
else echo FALSE\n\
fi";

korbb's avatar
korbb committed
633
  char *pz_res;
634
  int res;
korbb's avatar
korbb committed
635 636 637

  static char cmd_buf[4096];

korbb's avatar
korbb committed
638
  sprintf (cmd_buf, cmd_fmt, pz_test_file, p_test->pz_test_text);
korbb's avatar
korbb committed
639
  pz_res = run_shell (cmd_buf);
640 641 642

  switch (*pz_res) {
  case 'T':
korbb's avatar
korbb committed
643
    res = APPLY_FIX;
644 645 646 647 648 649 650 651 652 653 654
    break;

  case 'F':
    res = SKIP_FIX;
    break;

  default:
    fprintf (stderr, "Script yielded bogus result of `%s':\n%s\n\n",
             pz_res, cmd_buf );
  }

korbb's avatar
korbb committed
655
  free ((void *) pz_res);
656 657
  return res;
}
658 659 660 661 662 663 664
#else
/*
 *  IF we are in MS-DOS land, then whatever shell-type test is required
 *  will, by definition, fail
 */
#define test_test(t,tf)  SKIP_FIX
#endif
665

korbb's avatar
korbb committed
666
/* * * * * * * * * * * * *
korbb's avatar
korbb committed
667

korbb's avatar
korbb committed
668 669 670
  egrep_test   make sure an egrep expression is found in the file text.
  Input:  a pointer to the descriptor of the test to run and
          the pointer to the contents of the file under suspicion
korbb's avatar
korbb committed
671
  Result: APPLY_FIX if the pattern is found, SKIP_FIX otherwise
korbb's avatar
korbb committed
672

korbb's avatar
korbb committed
673
  The caller may choose to reverse meaning if the sense of the test
korbb's avatar
korbb committed
674 675
  is inverted.  */

korbb's avatar
korbb committed
676
int
korbb's avatar
korbb committed
677 678 679
egrep_test (pz_data, p_test)
     char *pz_data;
     tTestDesc *p_test;
680
{
korbb's avatar
korbb committed
681
#ifdef DEBUG
korbb's avatar
korbb committed
682 683 684
  if (p_test->p_test_regex == 0)
    fprintf (stderr, "fixincl ERROR RE not compiled:  `%s'\n",
             p_test->pz_test_text);
685
#endif
686
  if (regexec (p_test->p_test_regex, pz_data, 0, 0, 0) == 0)
korbb's avatar
korbb committed
687 688
    return APPLY_FIX;
  return SKIP_FIX;
689 690 691
}


692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
/* * * * * * * * * * * * *

  quoted_file_exists  Make sure that a file exists before we emit
  the file name.  If we emit the name, our invoking shell will try
  to copy a non-existing file into the destination directory.  */

int
quoted_file_exists (pz_src_path, pz_file_path, pz_file)
     char* pz_src_path;
     char* pz_file_path;
     char* pz_file;
{
  char z[ MAXPATHLEN ];
  char* pz;
  sprintf (z, "%s/%s/", pz_src_path, pz_file_path);
  pz = z + strlen ( z );

  for (;;) {
    char ch = *pz_file++;
korbb's avatar
korbb committed
711
    if (! ISGRAPH( ch ))
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
      return 0;
    if (ch == '"')
      break;
    *pz++ = ch;
  }
  *pz = '\0';
  {
    struct stat s;
    if (stat (z, &s) != 0)
      return 0;
    return S_ISREG( s.st_mode );
  }
}


korbb's avatar
korbb committed
727 728 729
/* * * * * * * * * * * * *
 *
   extract_quoted_files
korbb's avatar
korbb committed
730

korbb's avatar
korbb committed
731 732 733 734 735 736 737
   The syntax, `#include "file.h"' specifies that the compiler is to
   search the local directory of the current file before the include
   list.  Consequently, if we have modified a header and stored it in
   another directory, any files that are included by that modified
   file in that fashion must also be copied into this new directory.
   This routine finds those flavors of #include and for each one found
   emits a triple of:
korbb's avatar
korbb committed
738

korbb's avatar
korbb committed
739 740 741 742 743 744 745 746
    1.  source directory of the original file
    2.  the relative path file name of the #includ-ed file
    3.  the full destination path for this file

   Input:  the text of the file, the file name and a pointer to the
           match list where the match information was stored.
   Result: internally nothing.  The results are written to stdout
           for interpretation by the invoking shell  */
747

748

749
void
korbb's avatar
korbb committed
750
extract_quoted_files (pz_data, pz_fixed_file, p_re_match)
korbb's avatar
korbb committed
751
     char *pz_data;
korbb's avatar
korbb committed
752
     const char *pz_fixed_file;
korbb's avatar
korbb committed
753
     regmatch_t *p_re_match;
754
{
korbb's avatar
korbb committed
755
  char *pz_dir_end = strrchr (pz_fixed_file, '/');
korbb's avatar
korbb committed
756
  char *pz_incl_quot = pz_data;
757

758 759
  if (VLEVEL( VERB_APPLIES ))
    fprintf (stderr, "Quoted includes in %s\n", pz_fixed_file);
760

korbb's avatar
korbb committed
761
  /*  Set "pz_fixed_file" to point to the containing subdirectory of the source
762
      If there is none, then it is in our current directory, ".".   */
korbb's avatar
korbb committed
763 764

  if (pz_dir_end == (char *) NULL)
korbb's avatar
korbb committed
765
    pz_fixed_file = ".";
766
  else
korbb's avatar
korbb committed
767
    *pz_dir_end = '\0';
768 769 770

  for (;;)
    {
korbb's avatar
korbb committed
771 772 773
      pz_incl_quot += p_re_match->rm_so;

      /*  Skip forward to the included file name */
774
      while (ISSPACE (*pz_incl_quot))
korbb's avatar
korbb committed
775
        pz_incl_quot++;
776
      /* ISSPACE() may evaluate its argument more than once!  */
korbb's avatar
korbb committed
777
      while (++pz_incl_quot, ISSPACE (*pz_incl_quot))
korbb's avatar
korbb committed
778 779 780 781 782
        ;
      pz_incl_quot += sizeof ("include") - 1;
      while (*pz_incl_quot++ != '"')
        ;

korbb's avatar
korbb committed
783
      if (quoted_file_exists (pz_src_dir, pz_fixed_file, pz_incl_quot))
784 785 786
        {
          /* Print the source directory and the subdirectory
             of the file in question.  */
korbb's avatar
korbb committed
787
          printf ("%s  %s/", pz_src_dir, pz_fixed_file);
788 789 790 791 792 793 794 795
          pz_dir_end = pz_incl_quot;

          /* Append to the directory the relative path of the desired file */
          while (*pz_incl_quot != '"')
            putc (*pz_incl_quot++, stdout);

          /* Now print the destination directory appended with the
             relative path of the desired file */
korbb's avatar
korbb committed
796
          printf ("  %s/%s/", pz_dest_dir, pz_fixed_file);
797 798 799 800 801 802
          while (*pz_dir_end != '"')
            putc (*pz_dir_end++, stdout);

          /* End of entry */
          putc ('\n', stdout);
        }
803

korbb's avatar
korbb committed
804 805
      /* Find the next entry */
      if (regexec (&incl_quote_re, pz_incl_quot, 1, p_re_match, 0) != 0)
806 807 808 809 810
        break;
    }
}


korbb's avatar
korbb committed
811 812 813 814
/* * * * * * * * * * * * *

    Somebody wrote a *_fix subroutine that we must call.
    */
815
#ifndef __MSDOS__
korbb's avatar
korbb committed
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
int
internal_fix (read_fd, p_fixd)
  int read_fd;
  tFixDesc* p_fixd;
{
  int fd[2];

  if (pipe( fd ) != 0)
    {
      fprintf (stderr, "Error %d on pipe(2) call\n", errno );
      exit (EXIT_FAILURE);
    }

  for (;;)
    {
      pid_t childid = fork();

      switch (childid)
        {
        case -1:
          break;

        case 0:
          close (fd[0]);
          goto do_child_task;

        default:
          /*
           *  Parent process
           */
          close (read_fd);
          close (fd[1]);
          return fd[0];
        }

      /*
       *  Parent in error
       */
854
      fprintf (stderr, z_fork_err, errno, xstrerror (errno),
korbb's avatar
korbb committed
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
               p_fixd->fix_name);
      {
        static int failCt = 0;
        if ((errno != EAGAIN) || (++failCt > 10))
          exit (EXIT_FAILURE);
        sleep (1);
      }
    } do_child_task:;

  /*
   *  Close our current stdin and stdout
   */
  close (STDIN_FILENO);
  close (STDOUT_FILENO);
  UNLOAD_DATA();

  /*
   *  Make the fd passed in the stdin, and the write end of
   *  the new pipe become the stdout.
   */
  fcntl (fd[1], F_DUPFD, STDOUT_FILENO);
  fcntl (read_fd, F_DUPFD, STDIN_FILENO);

878
  apply_fix (p_fixd, pz_curr_file);
korbb's avatar
korbb committed
879 880
  exit (0);
}
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
#endif /* !__MSDOS__ */


#ifdef __MSDOS__
static void
fix_with_system (p_fixd, pz_fix_file, pz_file_source, pz_temp_file)
  tFixDesc* p_fixd;
  tCC* pz_fix_file;
  tCC* pz_file_source;
  tCC* pz_temp_file;
{
  char*  pz_cmd;
  char*  pz_scan;
  size_t argsize;

  if (p_fixd->fd_flags & FD_SUBROUTINE)
    {
      tSCC z_applyfix_prog[] = "/fixinc/applyfix";

      argsize = 32
              + strlen( pz_orig_dir )
              + sizeof( z_applyfix_prog )
              + strlen( pz_fix_file )
              + strlen( pz_file_source )
              + strlen( pz_temp_file );

      pz_cmd = (char*)xmalloc( argsize );
korbb's avatar
korbb committed
908

909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
      strcpy( pz_cmd, pz_orig_dir );
      pz_scan = pz_cmd + strlen( pz_orig_dir );
      strcpy( pz_scan, z_applyfix_prog );
      pz_scan += sizeof( z_applyfix_prog ) - 1;
      *(pz_scan++) = ' ';

      /*
       *  Now add the fix number and file names that may be needed
       */
      sprintf (pz_scan, "%ld %s %s %s", p_fixd - fixDescList,
	       pz_fix_file, pz_file_source, pz_temp_file);
    }
  else /* NOT an "internal" fix: */
    {
      size_t parg_size;
      /* Don't use the "src > dstX; rm -f dst; mv -f dstX dst" trick:
	 dst is a temporary file anyway, so we know there's no other
	 file by that name; and DOS's system(3) doesn't mind to
927 928 929 930 931 932 933
         clobber existing file in redirection.  Besides, with DOS 8+3
         limited file namespace, we can easily lose if dst already has
         an extension that is 3 or more characters long.
         The following bizarre use of 'cat' only works on DOS boxes.
         It is causing the file to be dropped into a temporary file for
         'cat' to read (pipes do not work on DOS).  */
      tSCC   z_cmd_fmt[] = " %s | cat > %s";
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
      tCC**  ppArgs = p_fixd->patch_args;

      argsize = sizeof( z_cmd_fmt ) + strlen( pz_temp_file )
              + strlen( pz_file_source );
      parg_size = argsize;
      

      /*
       *  Compute the size of the command line.  Add lotsa extra space
       *  because some of the args to sed use lotsa single quotes.
       *  (This requires three extra bytes per quote.  Here we allow
       *  for up to 8 single quotes for each argument, including the
       *  command name "sed" itself.  Nobody will *ever* need more. :)
       */
      for (;;)
        {
          tCC* p_arg = *(ppArgs++);
          if (p_arg == NULL)
            break;
          argsize += 24 + strlen( p_arg );
        }

      /* Estimated buffer size we will need.  */
      pz_scan = pz_cmd = (char*)xmalloc( argsize );
      /* How much of it do we allot to the program name and its
         arguments.  */
      parg_size = argsize - parg_size;

      ppArgs = p_fixd->patch_args;

      /*
       *  Copy the program name, unquoted
       */
      {
        tCC*   pArg = *(ppArgs++);
        for (;;)
          {
            char ch = *(pArg++);
            if (ch == NUL)
              break;
            *(pz_scan++) = ch;
          }
      }

      /*
       *  Copy the program arguments, quoted
       */
      for (;;)
        {
          tCC*   pArg = *(ppArgs++);
	  char*  pz_scan_save;
          if (pArg == NULL)
            break;
          *(pz_scan++) = ' ';
          pz_scan = make_raw_shell_str( pz_scan_save = pz_scan, pArg,
					parg_size - (pz_scan - pz_cmd) );
	  /*
	   *  Make sure we don't overflow the buffer due to sloppy
	   *  size estimation.
	   */
	  while (pz_scan == (char*)NULL)
	    {
	      size_t already_filled = pz_scan_save - pz_cmd;
	      pz_cmd = (char*)xrealloc( pz_cmd, argsize += 100 );
	      pz_scan_save = pz_scan = pz_cmd + already_filled;
	      parg_size += 100;
	      pz_scan = make_raw_shell_str( pz_scan, pArg,
					    parg_size - (pz_scan - pz_cmd) );
	    }
        }

      /*
       *  add the file machinations.
       */
      sprintf( pz_scan, z_cmd_fmt, pz_file_source, pz_temp_file );
    }
  system( pz_cmd );
  free( (void*)pz_cmd );
}
korbb's avatar
korbb committed
1013 1014 1015 1016 1017 1018 1019 1020

/* * * * * * * * * * * * *

    This loop should only cycle for 1/2 of one loop.
    "chain_open" starts a process that uses "read_fd" as
    its stdin and returns the new fd this process will use
    for stdout.  */

1021
#else /* is *NOT* __MSDOS__ */
korbb's avatar
korbb committed
1022
int
korbb's avatar
korbb committed
1023
start_fixer (read_fd, p_fixd, pz_fix_file)
korbb's avatar
korbb committed
1024 1025
  int read_fd;
  tFixDesc* p_fixd;
korbb's avatar
korbb committed
1026
  char* pz_fix_file;
korbb's avatar
korbb committed
1027 1028 1029 1030
{
  tCC* pz_cmd_save;
  char* pz_cmd;

korbb's avatar
korbb committed
1031 1032 1033
  if ((p_fixd->fd_flags & FD_SUBROUTINE) != 0)
    return internal_fix (read_fd, p_fixd);

korbb's avatar
korbb committed
1034 1035 1036 1037 1038
  if ((p_fixd->fd_flags & FD_SHELL_SCRIPT) == 0)
    pz_cmd = (char*)NULL;
  else
    {
      tSCC z_cmd_fmt[] = "file='%s'\n%s";
korbb's avatar
korbb committed
1039
      pz_cmd = (char*)malloc (strlen (p_fixd->patch_args[2])
korbb's avatar
korbb committed
1040
                               + sizeof( z_cmd_fmt )
korbb's avatar
korbb committed
1041 1042 1043 1044 1045 1046 1047
                               + strlen( pz_fix_file ));
      if (pz_cmd == (char*)NULL)
        {
          fputs ("allocation failure\n", stderr);
          exit (EXIT_FAILURE);
        }
      sprintf (pz_cmd, z_cmd_fmt, pz_fix_file, p_fixd->patch_args[2]);
korbb's avatar
korbb committed
1048 1049 1050 1051
      pz_cmd_save = p_fixd->patch_args[2];
      p_fixd->patch_args[2] = pz_cmd;
    }

1052 1053 1054 1055 1056 1057
  /*  Start a fix process, handing off the  previous read fd for its
      stdin and getting a new fd that reads from the fix process' stdout.
      We normally will not loop, but we will up to 10 times if we keep
      getting "EAGAIN" errors.

      */
korbb's avatar
korbb committed
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
  for (;;)
    {
      static int failCt = 0;
      int fd;

      fd = chain_open (read_fd,
                       (t_pchar *) p_fixd->patch_args,
                       (process_chain_head == -1)
                       ? &process_chain_head : (pid_t *) NULL);

      if (fd != -1)
        {
          read_fd = fd;
          break;
        }

1074
      fprintf (stderr, z_fork_err, errno, xstrerror (errno),
korbb's avatar
korbb committed
1075 1076 1077 1078 1079 1080 1081
               p_fixd->fix_name);

      if ((errno != EAGAIN) || (++failCt > 10))
        exit (EXIT_FAILURE);
      sleep (1);
    }

1082 1083
  /*  IF we allocated a shell script command,
      THEN free it and restore the command format to the fix description */
korbb's avatar
korbb committed
1084 1085 1086 1087 1088 1089 1090 1091
  if (pz_cmd != (char*)NULL)
    {
      free ((void*)pz_cmd);
      p_fixd->patch_args[2] = pz_cmd_save;
    }

  return read_fd;
}
1092
#endif
korbb's avatar
korbb committed
1093

korbb's avatar
korbb committed
1094

korbb's avatar
korbb committed
1095 1096 1097 1098 1099 1100
/* * * * * * * * * * * * *

   Process the potential fixes for a particular include file.
   Input:  the original text of the file and the file's name
   Result: none.  A new file may or may not be created.  */

korbb's avatar
korbb committed
1101 1102 1103
t_bool
fix_applies (p_fixd)
  tFixDesc *p_fixd;
1104
{
1105 1106
  const char *pz_fname = pz_curr_file;
  const char *pz_scan = p_fixd->file_list;
korbb's avatar
korbb committed
1107 1108
  int test_ct;
  tTestDesc *p_test;
1109

1110 1111 1112 1113 1114 1115 1116 1117 1118
# ifdef __MSDOS__
  /*
   *  There is only one fix that uses a shell script as of this writing.
   *  I hope to nuke it anyway, it does not apply to DOS and it would
   *  be painful to implement.  Therefore, no "shell" fixes for DOS.
   */
  if (p_fixd->fd_flags & (FD_SHELL_SCRIPT | FD_SKIP_TEST))
    return BOOL_FALSE;
# else
korbb's avatar
korbb committed
1119 1120
  if (p_fixd->fd_flags & FD_SKIP_TEST)
    return BOOL_FALSE;
1121
# endif
1122

korbb's avatar
korbb committed
1123 1124 1125
  /*  IF there is a file name restriction,
      THEN ensure the current file name matches one in the pattern  */

1126
  if (pz_scan != (char *) NULL)
korbb's avatar
korbb committed
1127 1128
    {
      size_t name_len;
1129

korbb's avatar
korbb committed
1130 1131 1132
      while ((pz_fname[0] == '.') && (pz_fname[1] == '/'))
        pz_fname += 2;
      name_len = strlen (pz_fname);
korbb's avatar
korbb committed
1133

korbb's avatar
korbb committed
1134
      for (;;)
1135
        {
korbb's avatar
korbb committed
1136 1137 1138
          pz_scan = strstr (pz_scan + 1, pz_fname);
          /*  IF we can't match the string at all,
              THEN bail  */
1139
          if (pz_scan == (char *) NULL)
korbb's avatar
korbb committed
1140
            return BOOL_FALSE;
1141

korbb's avatar
korbb committed
1142 1143
          /*  IF the match is surrounded by the '|' markers,
              THEN we found a full match -- time to run the tests  */
1144

korbb's avatar
korbb committed
1145 1146 1147 1148
          if ((pz_scan[-1] == '|') && (pz_scan[name_len] == '|'))
            break;
        }
    }
1149

korbb's avatar
korbb committed
1150 1151
  /*  FOR each test, see if it fails.
      IF it does fail, then we go on to the next test */
korbb's avatar
korbb committed
1152

korbb's avatar
korbb committed
1153 1154 1155 1156 1157 1158 1159
  for (p_test = p_fixd->p_test_desc, test_ct = p_fixd->test_ct;
       test_ct-- > 0;
       p_test++)
    {
      switch (p_test->type)
        {
        case TT_TEST:
1160 1161 1162
          if (test_test (p_test, pz_curr_file) != APPLY_FIX) {
#ifdef DEBUG
            if (VLEVEL( VERB_EVERYTHING ))
1163 1164
              fprintf (stderr, z_failed, "TEST", p_fixd->fix_name,
                       pz_fname, p_fixd->test_ct - test_ct);
1165
#endif
korbb's avatar
korbb committed
1166
            return BOOL_FALSE;
1167
          }
korbb's avatar
korbb committed
1168 1169 1170
          break;

        case TT_EGREP:
1171 1172 1173
          if (egrep_test (pz_curr_data, p_test) != APPLY_FIX) {
#ifdef DEBUG
            if (VLEVEL( VERB_EVERYTHING ))
1174 1175
              fprintf (stderr, z_failed, "EGREP", p_fixd->fix_name,
                       pz_fname, p_fixd->test_ct - test_ct);
1176
#endif
korbb's avatar
korbb committed
1177
            return BOOL_FALSE;
1178
          }
korbb's avatar
korbb committed
1179 1180 1181
          break;

        case TT_NEGREP:
1182 1183 1184
          if (egrep_test (pz_curr_data, p_test) == APPLY_FIX) {
#ifdef DEBUG
            if (VLEVEL( VERB_EVERYTHING ))
1185 1186
              fprintf (stderr, z_failed, "NEGREP", p_fixd->fix_name,
                       pz_fname, p_fixd->test_ct - test_ct);
1187
#endif
korbb's avatar
korbb committed
1188 1189
            /*  Negated sense  */
            return BOOL_FALSE;
1190
          }
korbb's avatar
korbb committed
1191 1192 1193 1194
          break;

        case TT_FUNCTION:
          if (run_test (p_test->pz_test_text, pz_curr_file, pz_curr_data)
1195 1196 1197
              != APPLY_FIX) {
#ifdef DEBUG
            if (VLEVEL( VERB_EVERYTHING ))
1198 1199
              fprintf (stderr, z_failed, "FTEST", p_fixd->fix_name,
                       pz_fname, p_fixd->test_ct - test_ct);
1200
#endif
korbb's avatar
korbb committed
1201
            return BOOL_FALSE;
1202
          }
korbb's avatar
korbb committed
1203
          break;
1204
        }
korbb's avatar
korbb committed
1205
    }
1206

korbb's avatar
korbb committed
1207 1208
  return BOOL_TRUE;
}
1209 1210


korbb's avatar
korbb committed
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
/* * * * * * * * * * * * *

   Write out a replacement file  */

void
write_replacement (p_fixd)
  tFixDesc *p_fixd;
{
   const char* pz_text = p_fixd->patch_args[0];

   if ((pz_text == (char*)NULL) || (*pz_text == NUL))
     return;

   {
     FILE* out_fp = create_file (pz_curr_file);
     fputs (pz_text, out_fp);
     fclose (out_fp);
   }
}


/* * * * * * * * * * * * *

    We have work to do.  Read back in the output
    of the filtering chain.  Compare each byte as we read it with
    the contents of the original file.  As soon as we find any
    difference, we will create the output file, write out all
    the matched text and then copy any remaining data from the
    output of the filter chain.
    */
void
test_for_changes (read_fd)
  int read_fd;
{
  FILE *in_fp = fdopen (read_fd, "r");
  FILE *out_fp = (FILE *) NULL;
  char *pz_cmp = pz_curr_data;

#ifdef DO_STATS
  fixed_ct++;
korbb's avatar
korbb committed
1251
#endif
korbb's avatar
korbb committed
1252 1253 1254
  for (;;)
    {
      int ch;
1255

korbb's avatar
korbb committed
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
      ch = getc (in_fp);
      if (ch == EOF)
        break;

      /*  IF we are emitting the output
          THEN emit this character, too.
      */
      if (out_fp != (FILE *) NULL)
        putc (ch, out_fp);

      /*  ELSE if this character does not match the original,
          THEN now is the time to start the output.
      */
      else if (ch != *pz_cmp)
        {
          out_fp = create_file (pz_curr_file);

#ifdef DO_STATS
          altered_ct++;
korbb's avatar
korbb committed
1275
#endif
korbb's avatar
korbb committed
1276 1277 1278 1279 1280 1281
          /*  IF there are matched data, write the matched part now. */
          if (pz_cmp != pz_curr_data)
            fwrite (pz_curr_data, (size_t)(pz_cmp - pz_curr_data), 1, out_fp);

          /*  Emit the current unmatching character */
          putc (ch, out_fp);
1282
        }
korbb's avatar
korbb committed
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
      else
        /*  ELSE the character matches.  Advance the compare ptr */
        pz_cmp++;
    }

  /*  IF we created the output file, ... */
  if (out_fp != (FILE *) NULL)
    {
      regmatch_t match;

      /* Close the file and see if we have to worry about
         `#include "file.h"' constructs.  */
      fclose (out_fp);
      if (regexec (&incl_quote_re, pz_curr_data, 1, &match, 0) == 0)
        extract_quoted_files (pz_curr_data, pz_curr_file, &match);
    }

  fclose (in_fp);
  close (read_fd);  /* probably redundant, but I'm paranoid */
}


/* * * * * * * * * * * * *

   Process the potential fixes for a particular include file.
   Input:  the original text of the file and the file's name
   Result: none.  A new file may or may not be created.  */

void
process ()
{
  tFixDesc *p_fixd = fixDescList;
  int todo_ct = FIX_COUNT;
  int read_fd = -1;
1317
# ifndef __MSDOS__
korbb's avatar
korbb committed
1318
  int num_children = 0;
1319 1320 1321
# else /* is __MSDOS__ */
  char* pz_file_source = pz_curr_file;
# endif
korbb's avatar
korbb committed
1322 1323 1324 1325 1326 1327

  if (access (pz_curr_file, R_OK) != 0)
    {
      int erno = errno;
      fprintf (stderr, "Cannot access %s from %s\n\terror %d (%s)\n",
               pz_curr_file, getcwd ((char *) NULL, MAXPATHLEN),
1328
               erno, xstrerror (erno));
korbb's avatar
korbb committed
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
      return;
    }

  pz_curr_data = load_file (pz_curr_file);
  if (pz_curr_data == (char *) NULL)
    return;

#ifdef DO_STATS
  process_ct++;
#endif
1339
  if (VLEVEL( VERB_PROGRESS ) && have_tty)
1340
    fprintf (stderr, "%6d %-50s   \r", data_map_size, pz_curr_file );
korbb's avatar
korbb committed
1341

1342
# ifndef __MSDOS__
korbb's avatar
korbb committed
1343 1344 1345 1346 1347 1348 1349
  process_chain_head = NOPROCESS;

  /* For every fix in our fix list, ...  */
  for (; todo_ct > 0; p_fixd++, todo_ct--)
    {
      if (! fix_applies (p_fixd))
        continue;
1350

1351 1352 1353
      if (VLEVEL( VERB_APPLIES ))
        fprintf (stderr, "Applying %-24s to %s\n",
                 p_fixd->fix_name, pz_curr_file);
korbb's avatar
korbb committed
1354 1355 1356 1357 1358 1359 1360

      if (p_fixd->fd_flags & FD_REPLACEMENT)
        {
          write_replacement (p_fixd);
          UNLOAD_DATA();
          return;
        }
korbb's avatar
korbb committed
1361 1362 1363 1364 1365

      /*  IF we do not have a read pointer,
          THEN this is the first fix for the current file.
          Open the source file.  That will be used as stdin for
          the first fix.  Any subsequent fixes will use the
korbb's avatar
korbb committed
1366
          stdout descriptor of the previous fix for its stdin.  */
1367

1368
      if (read_fd == -1)
korbb's avatar
korbb committed
1369
        {
korbb's avatar
korbb committed
1370
          read_fd = open (pz_curr_file, O_RDONLY);
1371
          if (read_fd < 0)
1372
            {
korbb's avatar
korbb committed
1373
              fprintf (stderr, "Error %d (%s) opening %s\n", errno,
1374
                       xstrerror (errno), pz_curr_file);
korbb's avatar
korbb committed
1375
              exit (EXIT_FAILURE);
1376
            }
korbb's avatar
korbb committed
1377 1378 1379 1380

          /*  Ensure we do not get duplicate output */

          fflush (stdout);
korbb's avatar
korbb committed
1381
        }
1382

korbb's avatar
korbb committed
1383
      read_fd = start_fixer (read_fd, p_fixd, pz_curr_file);
korbb's avatar
korbb committed
1384
      num_children++;
1385 1386
    }

korbb's avatar
korbb committed
1387 1388
  /*  IF we have a read-back file descriptor,
      THEN check for changes and write output if changed.   */
korbb's avatar
korbb committed
1389

korbb's avatar
korbb committed
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
  if (read_fd >= 0)
    {
      test_for_changes (read_fd);
#ifdef DO_STATS
      apply_ct += num_children;
#endif
      /* Wait for child processes created by chain_open()
         to avoid leaving zombies.  */
      do  {
        wait ((int *) NULL);
      } while (--num_children > 0);
    }
korbb's avatar
korbb committed
1402

1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
# else /* is __MSDOS__ */

  for (; todo_ct > 0; p_fixd++, todo_ct--)
    {
      if (! fix_applies (p_fixd))
        continue;

      if (VLEVEL( VERB_APPLIES ))
        fprintf (stderr, "Applying %-24s to %s\n",
                 p_fixd->fix_name, pz_curr_file);

      if (p_fixd->fd_flags & FD_REPLACEMENT)
        {
          write_replacement (p_fixd);
          UNLOAD_DATA();
          return;
        }
      fix_with_system (p_fixd, pz_curr_file, pz_file_source, pz_temp_file);
      pz_file_source = pz_temp_file;
    }

  read_fd = open( pz_temp_file, O_RDONLY );
  test_for_changes( read_fd );
  /* Unlinking a file while it is still open is a Bad Idea on
     DOS/Windows.  */
  close( read_fd );
  unlink( pz_temp_file );

# endif
korbb's avatar
korbb committed
1432
  UNLOAD_DATA();
1433
}