xref: /freebsd/usr.bin/bsdiff/bsdiff/bsdiff.c (revision 0b3105a37d7adcadcb720112fed4dc4e8040be99)
1 /*-
2  * Copyright 2003-2005 Colin Percival
3  * All rights reserved
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted providing that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
18  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
22  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
23  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
24  * POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include <sys/types.h>
31 
32 #include <bzlib.h>
33 #include <err.h>
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <limits.h>
37 #include <stdint.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <unistd.h>
42 
43 #ifndef O_BINARY
44 #define O_BINARY 0
45 #endif
46 
47 #define MIN(x,y) (((x)<(y)) ? (x) : (y))
48 
49 static void split(off_t *I,off_t *V,off_t start,off_t len,off_t h)
50 {
51 	off_t i,j,k,x,tmp,jj,kk;
52 
53 	if(len<16) {
54 		for(k=start;k<start+len;k+=j) {
55 			j=1;x=V[I[k]+h];
56 			for(i=1;k+i<start+len;i++) {
57 				if(V[I[k+i]+h]<x) {
58 					x=V[I[k+i]+h];
59 					j=0;
60 				};
61 				if(V[I[k+i]+h]==x) {
62 					tmp=I[k+j];I[k+j]=I[k+i];I[k+i]=tmp;
63 					j++;
64 				};
65 			};
66 			for(i=0;i<j;i++) V[I[k+i]]=k+j-1;
67 			if(j==1) I[k]=-1;
68 		};
69 		return;
70 	};
71 
72 	x=V[I[start+len/2]+h];
73 	jj=0;kk=0;
74 	for(i=start;i<start+len;i++) {
75 		if(V[I[i]+h]<x) jj++;
76 		if(V[I[i]+h]==x) kk++;
77 	};
78 	jj+=start;kk+=jj;
79 
80 	i=start;j=0;k=0;
81 	while(i<jj) {
82 		if(V[I[i]+h]<x) {
83 			i++;
84 		} else if(V[I[i]+h]==x) {
85 			tmp=I[i];I[i]=I[jj+j];I[jj+j]=tmp;
86 			j++;
87 		} else {
88 			tmp=I[i];I[i]=I[kk+k];I[kk+k]=tmp;
89 			k++;
90 		};
91 	};
92 
93 	while(jj+j<kk) {
94 		if(V[I[jj+j]+h]==x) {
95 			j++;
96 		} else {
97 			tmp=I[jj+j];I[jj+j]=I[kk+k];I[kk+k]=tmp;
98 			k++;
99 		};
100 	};
101 
102 	if(jj>start) split(I,V,start,jj-start,h);
103 
104 	for(i=0;i<kk-jj;i++) V[I[jj+i]]=kk-1;
105 	if(jj==kk-1) I[jj]=-1;
106 
107 	if(start+len>kk) split(I,V,kk,start+len-kk,h);
108 }
109 
110 static void qsufsort(off_t *I,off_t *V,u_char *old,off_t oldsize)
111 {
112 	off_t buckets[256];
113 	off_t i,h,len;
114 
115 	for(i=0;i<256;i++) buckets[i]=0;
116 	for(i=0;i<oldsize;i++) buckets[old[i]]++;
117 	for(i=1;i<256;i++) buckets[i]+=buckets[i-1];
118 	for(i=255;i>0;i--) buckets[i]=buckets[i-1];
119 	buckets[0]=0;
120 
121 	for(i=0;i<oldsize;i++) I[++buckets[old[i]]]=i;
122 	I[0]=oldsize;
123 	for(i=0;i<oldsize;i++) V[i]=buckets[old[i]];
124 	V[oldsize]=0;
125 	for(i=1;i<256;i++) if(buckets[i]==buckets[i-1]+1) I[buckets[i]]=-1;
126 	I[0]=-1;
127 
128 	for(h=1;I[0]!=-(oldsize+1);h+=h) {
129 		len=0;
130 		for(i=0;i<oldsize+1;) {
131 			if(I[i]<0) {
132 				len-=I[i];
133 				i-=I[i];
134 			} else {
135 				if(len) I[i-len]=-len;
136 				len=V[I[i]]+1-i;
137 				split(I,V,i,len,h);
138 				i+=len;
139 				len=0;
140 			};
141 		};
142 		if(len) I[i-len]=-len;
143 	};
144 
145 	for(i=0;i<oldsize+1;i++) I[V[i]]=i;
146 }
147 
148 static off_t matchlen(u_char *old,off_t oldsize,u_char *new,off_t newsize)
149 {
150 	off_t i;
151 
152 	for(i=0;(i<oldsize)&&(i<newsize);i++)
153 		if(old[i]!=new[i]) break;
154 
155 	return i;
156 }
157 
158 static off_t search(off_t *I,u_char *old,off_t oldsize,
159 		u_char *new,off_t newsize,off_t st,off_t en,off_t *pos)
160 {
161 	off_t x,y;
162 
163 	if(en-st<2) {
164 		x=matchlen(old+I[st],oldsize-I[st],new,newsize);
165 		y=matchlen(old+I[en],oldsize-I[en],new,newsize);
166 
167 		if(x>y) {
168 			*pos=I[st];
169 			return x;
170 		} else {
171 			*pos=I[en];
172 			return y;
173 		}
174 	};
175 
176 	x=st+(en-st)/2;
177 	if(memcmp(old+I[x],new,MIN(oldsize-I[x],newsize))<0) {
178 		return search(I,old,oldsize,new,newsize,x,en,pos);
179 	} else {
180 		return search(I,old,oldsize,new,newsize,st,x,pos);
181 	};
182 }
183 
184 static void offtout(off_t x,u_char *buf)
185 {
186 	off_t y;
187 
188 	if(x<0) y=-x; else y=x;
189 
190 		buf[0]=y%256;y-=buf[0];
191 	y=y/256;buf[1]=y%256;y-=buf[1];
192 	y=y/256;buf[2]=y%256;y-=buf[2];
193 	y=y/256;buf[3]=y%256;y-=buf[3];
194 	y=y/256;buf[4]=y%256;y-=buf[4];
195 	y=y/256;buf[5]=y%256;y-=buf[5];
196 	y=y/256;buf[6]=y%256;y-=buf[6];
197 	y=y/256;buf[7]=y%256;
198 
199 	if(x<0) buf[7]|=0x80;
200 }
201 
202 static void
203 usage(void)
204 {
205 
206 	fprintf(stderr, "usage: bsdiff oldfile newfile patchfile\n");
207 	exit(1);
208 }
209 
210 int main(int argc,char *argv[])
211 {
212 	int fd;
213 	u_char *old,*new;
214 	off_t oldsize,newsize;
215 	off_t *I,*V;
216 	off_t scan,pos,len;
217 	off_t lastscan,lastpos,lastoffset;
218 	off_t oldscore,scsc;
219 	off_t s,Sf,lenf,Sb,lenb;
220 	off_t overlap,Ss,lens;
221 	off_t i;
222 	off_t dblen,eblen;
223 	u_char *db,*eb;
224 	u_char buf[8];
225 	u_char header[32];
226 	FILE * pf;
227 	BZFILE * pfbz2;
228 	int bz2err;
229 
230 	if (argc != 4)
231 		usage();
232 
233 	/* Allocate oldsize+1 bytes instead of oldsize bytes to ensure
234 		that we never try to malloc(0) and get a NULL pointer */
235 	if(((fd=open(argv[1],O_RDONLY|O_BINARY,0))<0) ||
236 	    ((oldsize=lseek(fd,0,SEEK_END))==-1))
237 		err(1, "%s", argv[1]);
238 
239 	if (oldsize > SSIZE_MAX ||
240 	    (uintmax_t)oldsize >= SIZE_T_MAX / sizeof(off_t) ||
241 	    oldsize == OFF_MAX) {
242 		errno = EFBIG;
243 		err(1, "%s", argv[1]);
244 	}
245 
246 	if (((old=malloc(oldsize+1))==NULL) ||
247 		(lseek(fd,0,SEEK_SET)!=0) ||
248 		(read(fd,old,oldsize)!=oldsize) ||
249 		(close(fd)==-1)) err(1,"%s",argv[1]);
250 
251 	if(((I=malloc((oldsize+1)*sizeof(off_t)))==NULL) ||
252 		((V=malloc((oldsize+1)*sizeof(off_t)))==NULL)) err(1,NULL);
253 
254 	qsufsort(I,V,old,oldsize);
255 
256 	free(V);
257 
258 	/* Allocate newsize+1 bytes instead of newsize bytes to ensure
259 		that we never try to malloc(0) and get a NULL pointer */
260 	if(((fd=open(argv[2],O_RDONLY|O_BINARY,0))<0) ||
261 	    ((newsize=lseek(fd,0,SEEK_END))==-1))
262 		err(1, "%s", argv[2]);
263 
264 	if (newsize > SSIZE_MAX || (uintmax_t)newsize >= SIZE_T_MAX ||
265 	    newsize == OFF_MAX) {
266 		errno = EFBIG;
267 		err(1, "%s", argv[2]);
268 	}
269 
270 	if (((new=malloc(newsize+1))==NULL) ||
271 		(lseek(fd,0,SEEK_SET)!=0) ||
272 		(read(fd,new,newsize)!=newsize) ||
273 		(close(fd)==-1)) err(1,"%s",argv[2]);
274 
275 	if(((db=malloc(newsize+1))==NULL) ||
276 		((eb=malloc(newsize+1))==NULL)) err(1,NULL);
277 	dblen=0;
278 	eblen=0;
279 
280 	/* Create the patch file */
281 	if ((pf = fopen(argv[3], "wb")) == NULL)
282 		err(1, "%s", argv[3]);
283 
284 	/* Header is
285 		0	8	 "BSDIFF40"
286 		8	8	length of bzip2ed ctrl block
287 		16	8	length of bzip2ed diff block
288 		24	8	length of new file */
289 	/* File is
290 		0	32	Header
291 		32	??	Bzip2ed ctrl block
292 		??	??	Bzip2ed diff block
293 		??	??	Bzip2ed extra block */
294 	memcpy(header,"BSDIFF40",8);
295 	offtout(0, header + 8);
296 	offtout(0, header + 16);
297 	offtout(newsize, header + 24);
298 	if (fwrite(header, 32, 1, pf) != 1)
299 		err(1, "fwrite(%s)", argv[3]);
300 
301 	/* Compute the differences, writing ctrl as we go */
302 	if ((pfbz2 = BZ2_bzWriteOpen(&bz2err, pf, 9, 0, 0)) == NULL)
303 		errx(1, "BZ2_bzWriteOpen, bz2err = %d", bz2err);
304 	scan=0;len=0;pos=0;
305 	lastscan=0;lastpos=0;lastoffset=0;
306 	while(scan<newsize) {
307 		oldscore=0;
308 
309 		for(scsc=scan+=len;scan<newsize;scan++) {
310 			len=search(I,old,oldsize,new+scan,newsize-scan,
311 					0,oldsize,&pos);
312 
313 			for(;scsc<scan+len;scsc++)
314 			if((scsc+lastoffset<oldsize) &&
315 				(old[scsc+lastoffset] == new[scsc]))
316 				oldscore++;
317 
318 			if(((len==oldscore) && (len!=0)) ||
319 				(len>oldscore+8)) break;
320 
321 			if((scan+lastoffset<oldsize) &&
322 				(old[scan+lastoffset] == new[scan]))
323 				oldscore--;
324 		};
325 
326 		if((len!=oldscore) || (scan==newsize)) {
327 			s=0;Sf=0;lenf=0;
328 			for(i=0;(lastscan+i<scan)&&(lastpos+i<oldsize);) {
329 				if(old[lastpos+i]==new[lastscan+i]) s++;
330 				i++;
331 				if(s*2-i>Sf*2-lenf) { Sf=s; lenf=i; };
332 			};
333 
334 			lenb=0;
335 			if(scan<newsize) {
336 				s=0;Sb=0;
337 				for(i=1;(scan>=lastscan+i)&&(pos>=i);i++) {
338 					if(old[pos-i]==new[scan-i]) s++;
339 					if(s*2-i>Sb*2-lenb) { Sb=s; lenb=i; };
340 				};
341 			};
342 
343 			if(lastscan+lenf>scan-lenb) {
344 				overlap=(lastscan+lenf)-(scan-lenb);
345 				s=0;Ss=0;lens=0;
346 				for(i=0;i<overlap;i++) {
347 					if(new[lastscan+lenf-overlap+i]==
348 					   old[lastpos+lenf-overlap+i]) s++;
349 					if(new[scan-lenb+i]==
350 					   old[pos-lenb+i]) s--;
351 					if(s>Ss) { Ss=s; lens=i+1; };
352 				};
353 
354 				lenf+=lens-overlap;
355 				lenb-=lens;
356 			};
357 
358 			for(i=0;i<lenf;i++)
359 				db[dblen+i]=new[lastscan+i]-old[lastpos+i];
360 			for(i=0;i<(scan-lenb)-(lastscan+lenf);i++)
361 				eb[eblen+i]=new[lastscan+lenf+i];
362 
363 			dblen+=lenf;
364 			eblen+=(scan-lenb)-(lastscan+lenf);
365 
366 			offtout(lenf,buf);
367 			BZ2_bzWrite(&bz2err, pfbz2, buf, 8);
368 			if (bz2err != BZ_OK)
369 				errx(1, "BZ2_bzWrite, bz2err = %d", bz2err);
370 
371 			offtout((scan-lenb)-(lastscan+lenf),buf);
372 			BZ2_bzWrite(&bz2err, pfbz2, buf, 8);
373 			if (bz2err != BZ_OK)
374 				errx(1, "BZ2_bzWrite, bz2err = %d", bz2err);
375 
376 			offtout((pos-lenb)-(lastpos+lenf),buf);
377 			BZ2_bzWrite(&bz2err, pfbz2, buf, 8);
378 			if (bz2err != BZ_OK)
379 				errx(1, "BZ2_bzWrite, bz2err = %d", bz2err);
380 
381 			lastscan=scan-lenb;
382 			lastpos=pos-lenb;
383 			lastoffset=pos-scan;
384 		};
385 	};
386 	BZ2_bzWriteClose(&bz2err, pfbz2, 0, NULL, NULL);
387 	if (bz2err != BZ_OK)
388 		errx(1, "BZ2_bzWriteClose, bz2err = %d", bz2err);
389 
390 	/* Compute size of compressed ctrl data */
391 	if ((len = ftello(pf)) == -1)
392 		err(1, "ftello");
393 	offtout(len-32, header + 8);
394 
395 	/* Write compressed diff data */
396 	if ((pfbz2 = BZ2_bzWriteOpen(&bz2err, pf, 9, 0, 0)) == NULL)
397 		errx(1, "BZ2_bzWriteOpen, bz2err = %d", bz2err);
398 	BZ2_bzWrite(&bz2err, pfbz2, db, dblen);
399 	if (bz2err != BZ_OK)
400 		errx(1, "BZ2_bzWrite, bz2err = %d", bz2err);
401 	BZ2_bzWriteClose(&bz2err, pfbz2, 0, NULL, NULL);
402 	if (bz2err != BZ_OK)
403 		errx(1, "BZ2_bzWriteClose, bz2err = %d", bz2err);
404 
405 	/* Compute size of compressed diff data */
406 	if ((newsize = ftello(pf)) == -1)
407 		err(1, "ftello");
408 	offtout(newsize - len, header + 16);
409 
410 	/* Write compressed extra data */
411 	if ((pfbz2 = BZ2_bzWriteOpen(&bz2err, pf, 9, 0, 0)) == NULL)
412 		errx(1, "BZ2_bzWriteOpen, bz2err = %d", bz2err);
413 	BZ2_bzWrite(&bz2err, pfbz2, eb, eblen);
414 	if (bz2err != BZ_OK)
415 		errx(1, "BZ2_bzWrite, bz2err = %d", bz2err);
416 	BZ2_bzWriteClose(&bz2err, pfbz2, 0, NULL, NULL);
417 	if (bz2err != BZ_OK)
418 		errx(1, "BZ2_bzWriteClose, bz2err = %d", bz2err);
419 
420 	/* Seek to the beginning, write the header, and close the file */
421 	if (fseeko(pf, 0, SEEK_SET))
422 		err(1, "fseeko");
423 	if (fwrite(header, 32, 1, pf) != 1)
424 		err(1, "fwrite(%s)", argv[3]);
425 	if (fclose(pf))
426 		err(1, "fclose");
427 
428 	/* Free the memory we used */
429 	free(db);
430 	free(eb);
431 	free(I);
432 	free(old);
433 	free(new);
434 
435 	return 0;
436 }
437