add declaration on n to be an integer
[unix-history] / usr / src / usr.bin / diff / diff / diffreg.c
CommitLineData
745638c1 1static char sccsid[] = "@(#)diffreg.c 4.8 %G%";
43454f97
BJ
2
3#include "diff.h"
4/*
5 * diff - compare two files.
6 */
7
8/*
9 * Uses an algorithm due to Harold Stone, which finds
10 * a pair of longest identical subsequences in the two
11 * files.
12 *
13 * The major goal is to generate the match vector J.
14 * J[i] is the index of the line in file1 corresponding
15 * to line i file0. J[i] = 0 if there is no
16 * such line in file1.
17 *
18 * Lines are hashed so as to work in core. All potential
19 * matches are located by sorting the lines of each file
20 * on the hash (called ``value''). In particular, this
21 * collects the equivalence classes in file1 together.
22 * Subroutine equiv replaces the value of each line in
23 * file0 by the index of the first element of its
24 * matching equivalence in (the reordered) file1.
25 * To save space equiv squeezes file1 into a single
26 * array member in which the equivalence classes
27 * are simply concatenated, except that their first
28 * members are flagged by changing sign.
29 *
30 * Next the indices that point into member are unsorted into
31 * array class according to the original order of file0.
32 *
33 * The cleverness lies in routine stone. This marches
34 * through the lines of file0, developing a vector klist
35 * of "k-candidates". At step i a k-candidate is a matched
36 * pair of lines x,y (x in file0 y in file1) such that
37 * there is a common subsequence of length k
38 * between the first i lines of file0 and the first y
39 * lines of file1, but there is no such subsequence for
40 * any smaller y. x is the earliest possible mate to y
41 * that occurs in such a subsequence.
42 *
43 * Whenever any of the members of the equivalence class of
44 * lines in file1 matable to a line in file0 has serial number
45 * less than the y of some k-candidate, that k-candidate
46 * with the smallest such y is replaced. The new
47 * k-candidate is chained (via pred) to the current
48 * k-1 candidate so that the actual subsequence can
49 * be recovered. When a member has serial number greater
50 * that the y of all k-candidates, the klist is extended.
51 * At the end, the longest subsequence is pulled out
52 * and placed in the array J by unravel
53 *
54 * With J in hand, the matches there recorded are
55 * check'ed against reality to assure that no spurious
56 * matches have crept in due to hashing. If they have,
57 * they are broken, and "jackpot" is recorded--a harmless
58 * matter except that a true match for a spuriously
59 * mated line may now be unnecessarily reported as a change.
60 *
61 * Much of the complexity of the program comes simply
62 * from trying to minimize core utilization and
63 * maximize the range of doable problems by dynamically
64 * allocating what is needed and reusing what is not.
65 * The core requirements for problems larger than somewhat
66 * are (in words) 2*length(file0) + length(file1) +
67 * 3*(number of k-candidates installed), typically about
68 * 6n words for files of length n.
69 */
70
71#define prints(s) fputs(s,stdout)
72
73FILE *input[2];
74FILE *fopen();
75
76struct cand {
77 int x;
78 int y;
79 int pred;
80} cand;
81struct line {
82 int serial;
83 int value;
84} *file[2], line;
85int len[2];
86struct line *sfile[2]; /* shortened by pruning common prefix and suffix */
87int slen[2];
88int pref, suff; /* length of prefix and suffix */
89int *class; /* will be overlaid on file[0] */
90int *member; /* will be overlaid on file[1] */
91int *klist; /* will be overlaid on file[0] after class */
92struct cand *clist; /* merely a free storage pot for candidates */
93int clen = 0;
94int *J; /* will be overlaid on class */
95long *ixold; /* will be overlaid on klist */
96long *ixnew; /* will be overlaid on file[1] */
97
98diffreg()
99{
87f863b7
KM
100 register int i, j;
101 FILE *f1, *f2;
102 char buf1[BUFSIZ], buf2[BUFSIZ];
43454f97
BJ
103
104 if (hflag) {
105 diffargv[0] = "diffh";
106 execv(diffh, diffargv);
107 fprintf(stderr, "diff: ");
108 perror(diffh);
109 done();
110 }
111 dummy = malloc(1);
112 if ((stb1.st_mode & S_IFMT) == S_IFDIR)
113 file1 = splice(file1, file2);
114 else if ((stb2.st_mode & S_IFMT) == S_IFDIR)
115 file2 = splice(file2, file1);
116 else if (!strcmp(file1, "-")) {
117 if (!strcmp(file2, "-")) {
118 fprintf(stderr, "diff: can't specify - -\n");
119 done();
120 }
121 file1 = copytemp();
122 } else if (!strcmp(file2, "-"))
123 file2 = copytemp();
87f863b7
KM
124 if ((f1 = fopen(file1, "r")) == NULL) {
125 fprintf(stderr, "diff: ");
126 perror(file1);
87f863b7
KM
127 done();
128 }
129 if ((f2 = fopen(file2, "r")) == NULL) {
130 fprintf(stderr, "diff: ");
131 perror(file2);
132 fclose(f1);
87f863b7
KM
133 done();
134 }
135 if (stb1.st_size != stb2.st_size)
136 goto notsame;
137 for (;;) {
6f7a12ee
RH
138 i = fread(buf1, 1, BUFSIZ, f1);
139 j = fread(buf2, 1, BUFSIZ, f2);
87f863b7
KM
140 if (i < 0 || j < 0 || i != j)
141 goto notsame;
142 if (i == 0 && j == 0) {
143 fclose(f1);
144 fclose(f2);
d6790f57 145 status = 0; /* files don't differ */
87f863b7
KM
146 goto same;
147 }
148 for (j = 0; j < i; j++)
149 if (buf1[j] != buf2[j])
150 goto notsame;
151 }
152notsame:
d6790f57
RH
153 /*
154 * Files certainly differ at this point; set status accordingly
155 */
156 status = 1;
46235152 157 if (!asciifile(f1) || !asciifile(f2)) {
87f863b7
KM
158 printf("Binary files %s and %s differ\n", file1, file2);
159 fclose(f1);
160 fclose(f2);
161 done();
162 }
163 prepare(0, f1);
164 prepare(1, f2);
165 fclose(f1);
166 fclose(f2);
43454f97
BJ
167 prune();
168 sort(sfile[0],slen[0]);
169 sort(sfile[1],slen[1]);
170
171 member = (int *)file[1];
172 equiv(sfile[0], slen[0], sfile[1], slen[1], member);
173 member = (int *)ralloc((char *)member,(slen[1]+2)*sizeof(int));
174
175 class = (int *)file[0];
176 unsort(sfile[0], slen[0], class);
177 class = (int *)ralloc((char *)class,(slen[0]+2)*sizeof(int));
178
179 klist = (int *)talloc((slen[0]+2)*sizeof(int));
180 clist = (struct cand *)talloc(sizeof(cand));
87f863b7 181 i = stone(class, slen[0], member, klist);
43454f97
BJ
182 free((char *)member);
183 free((char *)class);
184
185 J = (int *)talloc((len[0]+2)*sizeof(int));
87f863b7 186 unravel(klist[i]);
43454f97
BJ
187 free((char *)clist);
188 free((char *)klist);
189
190 ixold = (long *)talloc((len[0]+2)*sizeof(long));
191 ixnew = (long *)talloc((len[1]+2)*sizeof(long));
192 check();
193 output();
194 status = anychange;
87f863b7 195same:
43454f97
BJ
196 if (opt == D_CONTEXT && anychange == 0)
197 printf("No differences encountered\n");
198 done();
199}
200
201char *
202copytemp()
203{
204 char buf[BUFSIZ];
205 register int i, f;
206
207 signal(SIGHUP,done);
208 signal(SIGINT,done);
209 signal(SIGPIPE,done);
210 signal(SIGTERM,done);
211 tempfile = mktemp("/tmp/dXXXXX");
212 f = creat(tempfile,0600);
213 if (f < 0) {
804c14e9 214 fprintf(stderr, "diff: ");
43454f97
BJ
215 perror(tempfile);
216 done();
217 }
218 while ((i = read(0,buf,BUFSIZ)) > 0)
219 if (write(f,buf,i) != i) {
220 fprintf(stderr, "diff: ");
221 perror(tempfile);
222 done();
223 }
224 close(f);
225 return (tempfile);
226}
227
228char *
229splice(dir, file)
230 char *dir, *file;
231{
232 char *tail;
233 char buf[BUFSIZ];
234
235 if (!strcmp(file, "-")) {
236 fprintf(stderr, "diff: can't specify - with other arg directory\n");
237 done();
238 }
239 tail = rindex(file, '/');
240 if (tail == 0)
241 tail = file;
242 else
243 tail++;
244 sprintf(buf, "%s/%s", dir, tail);
245 return (savestr(buf));
246}
247
87f863b7
KM
248prepare(i, fd)
249 int i;
250 FILE *fd;
43454f97
BJ
251{
252 register struct line *p;
253 register j,h;
87f863b7 254
87f863b7 255 fseek(fd, (long)0, 0);
43454f97 256 p = (struct line *)talloc(3*sizeof(line));
87f863b7 257 for(j=0; h=readhash(fd);) {
43454f97
BJ
258 p = (struct line *)ralloc((char *)p,(++j+3)*sizeof(line));
259 p[j].value = h;
260 }
261 len[i] = j;
262 file[i] = p;
43454f97
BJ
263}
264
265prune()
266{
267 register i,j;
268 for(pref=0;pref<len[0]&&pref<len[1]&&
269 file[0][pref+1].value==file[1][pref+1].value;
270 pref++ ) ;
271 for(suff=0;suff<len[0]-pref&&suff<len[1]-pref&&
272 file[0][len[0]-suff].value==file[1][len[1]-suff].value;
273 suff++) ;
274 for(j=0;j<2;j++) {
275 sfile[j] = file[j]+pref;
276 slen[j] = len[j]-pref-suff;
277 for(i=0;i<=slen[j];i++)
278 sfile[j][i].serial = i;
279 }
280}
281
282equiv(a,n,b,m,c)
283struct line *a, *b;
284int *c;
285{
286 register int i, j;
287 i = j = 1;
288 while(i<=n && j<=m) {
289 if(a[i].value <b[j].value)
290 a[i++].value = 0;
291 else if(a[i].value == b[j].value)
292 a[i++].value = j;
293 else
294 j++;
295 }
296 while(i <= n)
297 a[i++].value = 0;
298 b[m+1].value = 0;
299 j = 0;
300 while(++j <= m) {
301 c[j] = -b[j].serial;
302 while(b[j+1].value == b[j].value) {
303 j++;
304 c[j] = b[j].serial;
305 }
306 }
307 c[j] = -1;
308}
309
310stone(a,n,b,c)
311int *a;
312int *b;
745638c1 313register int *c;
43454f97
BJ
314{
315 register int i, k,y;
316 int j, l;
317 int oldc, tc;
318 int oldl;
319 k = 0;
320 c[0] = newcand(0,0,0);
321 for(i=1; i<=n; i++) {
322 j = a[i];
323 if(j==0)
324 continue;
325 y = -b[j];
326 oldl = 0;
327 oldc = c[0];
328 do {
329 if(y <= clist[oldc].y)
330 continue;
331 l = search(c, k, y);
332 if(l!=oldl+1)
333 oldc = c[l-1];
334 if(l<=k) {
335 if(clist[c[l]].y <= y)
336 continue;
337 tc = c[l];
338 c[l] = newcand(i,y,oldc);
339 oldc = tc;
340 oldl = l;
341 } else {
342 c[l] = newcand(i,y,oldc);
343 k++;
344 break;
345 }
346 } while((y=b[++j]) > 0);
347 }
348 return(k);
349}
350
351newcand(x,y,pred)
352{
353 register struct cand *q;
354 clist = (struct cand *)ralloc((char *)clist,++clen*sizeof(cand));
355 q = clist + clen -1;
356 q->x = x;
357 q->y = y;
358 q->pred = pred;
359 return(clen-1);
360}
361
362search(c, k, y)
363int *c;
364{
365 register int i, j, l;
366 int t;
367 if(clist[c[k]].y<y) /*quick look for typical case*/
368 return(k+1);
369 i = 0;
370 j = k+1;
745638c1
RC
371 while (1) {
372 l = i + j;
373 if ((l >>= 1) <= i)
374 break;
43454f97
BJ
375 t = clist[c[l]].y;
376 if(t > y)
377 j = l;
378 else if(t < y)
379 i = l;
380 else
381 return(l);
382 }
383 return(l+1);
384}
385
386unravel(p)
387{
388 register int i;
389 register struct cand *q;
390 for(i=0; i<=len[0]; i++)
391 J[i] = i<=pref ? i:
392 i>len[0]-suff ? i+len[1]-len[0]:
393 0;
394 for(q=clist+p;q->y!=0;q=clist+q->pred)
395 J[q->x+pref] = q->y+pref;
396}
397
398/* check does double duty:
3991. ferret out any fortuitous correspondences due
400to confounding by hashing (which result in "jackpot")
4012. collect random access indexes to the two files */
402
403check()
404{
405 register int i, j;
406 int jackpot;
407 long ctold, ctnew;
408 char c,d;
46235152
KM
409
410 if ((input[0] = fopen(file1,"r")) == NULL) {
411 perror(file1);
412 done();
413 }
414 if ((input[1] = fopen(file2,"r")) == NULL) {
415 perror(file2);
416 done();
417 }
43454f97
BJ
418 j = 1;
419 ixold[0] = ixnew[0] = 0;
420 jackpot = 0;
421 ctold = ctnew = 0;
422 for(i=1;i<=len[0];i++) {
423 if(J[i]==0) {
424 ixold[i] = ctold += skipline(0);
425 continue;
426 }
427 while(j<J[i]) {
428 ixnew[j] = ctnew += skipline(1);
429 j++;
430 }
431 for(;;) {
432 c = getc(input[0]);
433 d = getc(input[1]);
434 ctold++;
435 ctnew++;
436 if(bflag && isspace(c) && isspace(d)) {
437 do {
438 if(c=='\n') break;
439 ctold++;
440 } while(isspace(c=getc(input[0])));
441 do {
442 if(d=='\n') break;
443 ctnew++;
444 } while(isspace(d=getc(input[1])));
445 }
446 if(c!=d) {
447 jackpot++;
448 J[i] = 0;
449 if(c!='\n')
450 ctold += skipline(0);
451 if(d!='\n')
452 ctnew += skipline(1);
453 break;
454 }
455 if(c=='\n')
456 break;
457 }
458 ixold[i] = ctold;
459 ixnew[j] = ctnew;
460 j++;
461 }
462 for(;j<=len[1];j++) {
463 ixnew[j] = ctnew += skipline(1);
464 }
465 fclose(input[0]);
466 fclose(input[1]);
467/*
468 if(jackpot)
469 fprintf(stderr, "jackpot\n");
470*/
471}
472
473sort(a,n) /*shellsort CACM #201*/
474struct line *a;
475{
476 struct line w;
477 register int j,m;
478 struct line *ai;
479 register struct line *aim;
480 int k;
481 for(j=1;j<=n;j*= 2)
482 m = 2*j - 1;
483 for(m/=2;m!=0;m/=2) {
484 k = n-m;
485 for(j=1;j<=k;j++) {
486 for(ai = &a[j]; ai > a; ai -= m) {
487 aim = &ai[m];
488 if(aim < ai)
489 break; /*wraparound*/
490 if(aim->value > ai[0].value ||
491 aim->value == ai[0].value &&
492 aim->serial > ai[0].serial)
493 break;
494 w.value = ai[0].value;
495 ai[0].value = aim->value;
496 aim->value = w.value;
497 w.serial = ai[0].serial;
498 ai[0].serial = aim->serial;
499 aim->serial = w.serial;
500 }
501 }
502 }
503}
504
505unsort(f, l, b)
506struct line *f;
507int *b;
508{
509 register int *a;
510 register int i;
511 a = (int *)talloc((l+1)*sizeof(int));
512 for(i=1;i<=l;i++)
513 a[f[i].serial] = f[i].value;
514 for(i=1;i<=l;i++)
515 b[i] = a[i];
516 free((char *)a);
517}
518
519skipline(f)
520{
521 register i;
46235152
KM
522 char c;
523
524 for(i=1;(c=getc(input[f]))!='\n';i++)
525 if (c < 0)
526 return(i);
43454f97
BJ
527 return(i);
528}
529
530output()
531{
532 int m;
533 register int i0, i1, j1;
534 int j0;
535 input[0] = fopen(file1,"r");
536 input[1] = fopen(file2,"r");
537 m = len[0];
538 J[0] = 0;
539 J[m+1] = len[1]+1;
540 if(opt!=D_EDIT) for(i0=1;i0<=m;i0=i1+1) {
541 while(i0<=m&&J[i0]==J[i0-1]+1) i0++;
542 j0 = J[i0-1]+1;
543 i1 = i0-1;
544 while(i1<m&&J[i1+1]==0) i1++;
545 j1 = J[i1+1]-1;
546 J[i1] = j1;
547 change(i0,i1,j0,j1);
548 } else for(i0=m;i0>=1;i0=i1-1) {
549 while(i0>=1&&J[i0]==J[i0+1]-1&&J[i0]!=0) i0--;
550 j0 = J[i0+1]-1;
551 i1 = i0+1;
552 while(i1>1&&J[i1-1]==0) i1--;
553 j1 = J[i1-1]+1;
554 J[i1] = j1;
555 change(i1,i0,j1,j0);
556 }
557 if(m==0)
558 change(1,0,1,len[1]);
559 if (opt==D_IFDEF) {
560 for (;;) {
561#define c i0
562 c = getc(input[0]);
563 if (c < 0)
564 return;
565 putchar(c);
566 }
567#undef c
568 }
569}
570
571/* indicate that there is a difference between lines a and b of the from file
572 to get to lines c to d of the to file.
573 If a is greater then b then there are no lines in the from file involved
574 and this means that there were lines appended (beginning at b).
575 If c is greater than d then there are lines missing from the to file.
576*/
577change(a,b,c,d)
578{
579 char ch;
580 int lowa,upb,lowc,upd;
581 struct stat stbuf;
582
583 if (opt != D_IFDEF && a>b && c>d)
584 return;
585 if (anychange == 0) {
586 anychange = 1;
587 if(opt == D_CONTEXT) {
588 printf("*** %s ", file1);
589 stat(file1, &stbuf);
590 printf("%s--- %s ",
591 ctime(&stbuf.st_mtime), file2);
592 stat(file2, &stbuf);
593 printf("%s", ctime(&stbuf.st_mtime));
594 }
595 }
596 if (a <= b && c <= d)
597 ch = 'c';
598 else
599 ch = (a <= b) ? 'd' : 'a';
600 if(opt == D_CONTEXT) {
601 lowa = max(1, a-context);
602 upb = min(len[0], b+context);
603 lowc = max(1, c-context);
604 upd = min(len[1], d+context);
605
606 /* print out from file */
607 printf("***************\n*** ");
608 range(lowa,upb,",");
609 printf("\n");
610 if (ch == 'a')
611 fetch(ixold,lowa,upb,input[0]," ");
612 else {
613 fetch(ixold,lowa,a-1,input[0]," ");
614 fetch(ixold,a,b,input[0],ch == 'c' ? "! " : "- ");
615 fetch(ixold,b+1,upb,input[0]," ");
616 }
617 putchar('\n');
618 printf("--- ");
619 range(lowc,upd,",");
620 printf(" -----\n");
621 if (ch == 'd')
622 fetch(ixnew,lowc,upd,input[1]," ");
623 else {
624 fetch(ixnew,lowc,c-1,input[1]," ");
625 fetch(ixnew,c,d,input[1],ch == 'c' ? "! " : "+ ");
626 fetch(ixnew,d+1,upd,input[1]," ");
627 }
628 return;
629 }
630 switch (opt) {
631
632 case D_NORMAL:
633 case D_EDIT:
634 range(a,b,",");
635 putchar(a>b?'a':c>d?'d':'c');
636 if(opt==D_NORMAL)
637 range(c,d,",");
638 putchar('\n');
639 break;
640 case D_REVERSE:
641 putchar(a>b?'a':c>d?'d':'c');
642 range(a,b," ");
643 putchar('\n');
644 break;
645 }
646 if(opt == D_NORMAL || opt == D_IFDEF) {
647 fetch(ixold,a,b,input[0],"< ", 1);
648 if(a<=b&&c<=d && opt == D_NORMAL)
649 prints("---\n");
650 }
651 fetch(ixnew,c,d,input[1],opt==D_NORMAL?"> ":"", 0);
652 if ((opt ==D_EDIT || opt == D_REVERSE) && c<=d)
653 prints(".\n");
654 if (inifdef) {
655 fprintf(stdout, "#endif %s\n", endifname);
656 inifdef = 0;
657 }
658}
659
660range(a,b,separator)
661char *separator;
662{
663 printf("%d", a>b?b:a);
664 if(a<b) {
665 printf("%s%d", separator, b);
666 }
667}
668
669fetch(f,a,b,lb,s,oldfile)
670long *f;
671FILE *lb;
672char *s;
673{
674 register int i, j;
675 register int nc;
676 int oneflag = (*ifdef1!='\0') != (*ifdef2!='\0');
677
678 /*
679 * When doing #ifdef's, copy down to current line
680 * if this is the first file, so that stuff makes it to output.
681 */
682 if (opt == D_IFDEF && oldfile){
683 long curpos = ftell(lb);
684 /* print through if append (a>b), else to (nb: 0 vs 1 orig) */
685 nc = f[a>b? b : a-1 ] - curpos;
686 for (i = 0; i < nc; i++)
687 putchar(getc(lb));
688 }
689 if (a > b)
690 return;
691 if (opt == D_IFDEF) {
692 if (inifdef)
693 fprintf(stdout, "#else %s%s\n", oneflag && oldfile==1 ? "!" : "", ifdef2);
694 else {
695 if (oneflag) {
696 /* There was only one ifdef given */
697 endifname = ifdef2;
698 if (oldfile)
699 fprintf(stdout, "#ifndef %s\n", endifname);
700 else
701 fprintf(stdout, "#ifdef %s\n", endifname);
702 }
703 else {
704 endifname = oldfile ? ifdef1 : ifdef2;
705 fprintf(stdout, "#ifdef %s\n", endifname);
706 }
707 }
708 inifdef = 1+oldfile;
709 }
710 for(i=a;i<=b;i++) {
711 fseek(lb,f[i-1],0);
712 nc = f[i]-f[i-1];
713 if (opt != D_IFDEF)
714 prints(s);
715 for(j=0;j<nc;j++)
716 putchar(getc(lb));
717 }
718 if (inifdef && !wantelses) {
719 fprintf(stdout, "#endif %s\n", endifname);
720 inifdef = 0;
721 }
722}
723
724#define HALFLONG 16
725#define low(x) (x&((1L<<HALFLONG)-1))
726#define high(x) (x>>HALFLONG)
727
728/*
729 * hashing has the effect of
730 * arranging line in 7-bit bytes and then
731 * summing 1-s complement in 16-bit hunks
732 */
733readhash(f)
745638c1 734register FILE *f;
43454f97
BJ
735{
736 long sum;
737 register unsigned shift;
738 register space;
739 register t;
740 sum = 1;
741 space = 0;
742 if(!bflag) for(shift=0;(t=getc(f))!='\n';shift+=7) {
743 if(t==-1)
744 return(0);
745638c1 745 sum += (long)t << (shift &= HALFLONG - 1);
43454f97
BJ
746 }
747 else for(shift=0;;) {
748 switch(t=getc(f)) {
749 case -1:
750 return(0);
751 case '\t':
752 case ' ':
753 space++;
754 continue;
755 default:
756 if(space) {
757 shift += 7;
758 space = 0;
759 }
745638c1 760 sum += (long)t << (shift &= HALFLONG - 1);
43454f97
BJ
761 shift += 7;
762 continue;
763 case '\n':
764 break;
765 }
766 break;
767 }
768 sum = low(sum) + high(sum);
769 return((short)low(sum) + (short)high(sum));
770}
46235152
KM
771
772#include <a.out.h>
773
774asciifile(f)
775 FILE *f;
776{
777 char buf[BUFSIZ];
778 register int cnt;
779 register char *cp;
780
781 fseek(f, (long)0, 0);
6f7a12ee 782 cnt = fread(buf, 1, BUFSIZ, f);
46235152
KM
783 if (cnt >= sizeof (struct exec)) {
784 struct exec hdr;
785 hdr = *(struct exec *)buf;
786 if (!N_BADMAG(hdr))
787 return (0);
788 }
789 cp = buf;
790 while (--cnt >= 0)
791 if (*cp++ & 0200)
792 return (0);
793 return (1);
794}