xref: /freebsd/usr.bin/bsdiff/bsdiff/bsdiff.c (revision 8f94ce2876bc295ec05b664711b7d807c134bc31)
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 		errno = EFBIG;
242 		err(1, "%s", argv[1]);
243 	}
244 
245 	if (((old=malloc(oldsize+1))==NULL) ||
246 		(lseek(fd,0,SEEK_SET)!=0) ||
247 		(read(fd,old,oldsize)!=oldsize) ||
248 		(close(fd)==-1)) err(1,"%s",argv[1]);
249 
250 	if(((I=malloc((oldsize+1)*sizeof(off_t)))==NULL) ||
251 		((V=malloc((oldsize+1)*sizeof(off_t)))==NULL)) err(1,NULL);
252 
253 	qsufsort(I,V,old,oldsize);
254 
255 	free(V);
256 
257 	/* Allocate newsize+1 bytes instead of newsize bytes to ensure
258 		that we never try to malloc(0) and get a NULL pointer */
259 	if(((fd=open(argv[2],O_RDONLY|O_BINARY,0))<0) ||
260 	    ((newsize=lseek(fd,0,SEEK_END))==-1))
261 		err(1, "%s", argv[2]);
262 
263 	if (newsize > SSIZE_MAX || (uintmax_t)newsize >= SIZE_T_MAX) {
264 		errno = EFBIG;
265 		err(1, "%s", argv[2]);
266 	}
267 
268 	if (((new=malloc(newsize+1))==NULL) ||
269 		(lseek(fd,0,SEEK_SET)!=0) ||
270 		(read(fd,new,newsize)!=newsize) ||
271 		(close(fd)==-1)) err(1,"%s",argv[2]);
272 
273 	if(((db=malloc(newsize+1))==NULL) ||
274 		((eb=malloc(newsize+1))==NULL)) err(1,NULL);
275 	dblen=0;
276 	eblen=0;
277 
278 	/* Create the patch file */
279 	if ((pf = fopen(argv[3], "wb")) == NULL)
280 		err(1, "%s", argv[3]);
281 
282 	/* Header is
283 		0	8	 "BSDIFF40"
284 		8	8	length of bzip2ed ctrl block
285 		16	8	length of bzip2ed diff block
286 		24	8	length of new file */
287 	/* File is
288 		0	32	Header
289 		32	??	Bzip2ed ctrl block
290 		??	??	Bzip2ed diff block
291 		??	??	Bzip2ed extra block */
292 	memcpy(header,"BSDIFF40",8);
293 	offtout(0, header + 8);
294 	offtout(0, header + 16);
295 	offtout(newsize, header + 24);
296 	if (fwrite(header, 32, 1, pf) != 1)
297 		err(1, "fwrite(%s)", argv[3]);
298 
299 	/* Compute the differences, writing ctrl as we go */
300 	if ((pfbz2 = BZ2_bzWriteOpen(&bz2err, pf, 9, 0, 0)) == NULL)
301 		errx(1, "BZ2_bzWriteOpen, bz2err = %d", bz2err);
302 	scan=0;len=0;pos=0;
303 	lastscan=0;lastpos=0;lastoffset=0;
304 	while(scan<newsize) {
305 		oldscore=0;
306 
307 		for(scsc=scan+=len;scan<newsize;scan++) {
308 			len=search(I,old,oldsize,new+scan,newsize-scan,
309 					0,oldsize,&pos);
310 
311 			for(;scsc<scan+len;scsc++)
312 			if((scsc+lastoffset<oldsize) &&
313 				(old[scsc+lastoffset] == new[scsc]))
314 				oldscore++;
315 
316 			if(((len==oldscore) && (len!=0)) ||
317 				(len>oldscore+8)) break;
318 
319 			if((scan+lastoffset<oldsize) &&
320 				(old[scan+lastoffset] == new[scan]))
321 				oldscore--;
322 		};
323 
324 		if((len!=oldscore) || (scan==newsize)) {
325 			s=0;Sf=0;lenf=0;
326 			for(i=0;(lastscan+i<scan)&&(lastpos+i<oldsize);) {
327 				if(old[lastpos+i]==new[lastscan+i]) s++;
328 				i++;
329 				if(s*2-i>Sf*2-lenf) { Sf=s; lenf=i; };
330 			};
331 
332 			lenb=0;
333 			if(scan<newsize) {
334 				s=0;Sb=0;
335 				for(i=1;(scan>=lastscan+i)&&(pos>=i);i++) {
336 					if(old[pos-i]==new[scan-i]) s++;
337 					if(s*2-i>Sb*2-lenb) { Sb=s; lenb=i; };
338 				};
339 			};
340 
341 			if(lastscan+lenf>scan-lenb) {
342 				overlap=(lastscan+lenf)-(scan-lenb);
343 				s=0;Ss=0;lens=0;
344 				for(i=0;i<overlap;i++) {
345 					if(new[lastscan+lenf-overlap+i]==
346 					   old[lastpos+lenf-overlap+i]) s++;
347 					if(new[scan-lenb+i]==
348 					   old[pos-lenb+i]) s--;
349 					if(s>Ss) { Ss=s; lens=i+1; };
350 				};
351 
352 				lenf+=lens-overlap;
353 				lenb-=lens;
354 			};
355 
356 			for(i=0;i<lenf;i++)
357 				db[dblen+i]=new[lastscan+i]-old[lastpos+i];
358 			for(i=0;i<(scan-lenb)-(lastscan+lenf);i++)
359 				eb[eblen+i]=new[lastscan+lenf+i];
360 
361 			dblen+=lenf;
362 			eblen+=(scan-lenb)-(lastscan+lenf);
363 
364 			offtout(lenf,buf);
365 			BZ2_bzWrite(&bz2err, pfbz2, buf, 8);
366 			if (bz2err != BZ_OK)
367 				errx(1, "BZ2_bzWrite, bz2err = %d", bz2err);
368 
369 			offtout((scan-lenb)-(lastscan+lenf),buf);
370 			BZ2_bzWrite(&bz2err, pfbz2, buf, 8);
371 			if (bz2err != BZ_OK)
372 				errx(1, "BZ2_bzWrite, bz2err = %d", bz2err);
373 
374 			offtout((pos-lenb)-(lastpos+lenf),buf);
375 			BZ2_bzWrite(&bz2err, pfbz2, buf, 8);
376 			if (bz2err != BZ_OK)
377 				errx(1, "BZ2_bzWrite, bz2err = %d", bz2err);
378 
379 			lastscan=scan-lenb;
380 			lastpos=pos-lenb;
381 			lastoffset=pos-scan;
382 		};
383 	};
384 	BZ2_bzWriteClose(&bz2err, pfbz2, 0, NULL, NULL);
385 	if (bz2err != BZ_OK)
386 		errx(1, "BZ2_bzWriteClose, bz2err = %d", bz2err);
387 
388 	/* Compute size of compressed ctrl data */
389 	if ((len = ftello(pf)) == -1)
390 		err(1, "ftello");
391 	offtout(len-32, header + 8);
392 
393 	/* Write compressed diff data */
394 	if ((pfbz2 = BZ2_bzWriteOpen(&bz2err, pf, 9, 0, 0)) == NULL)
395 		errx(1, "BZ2_bzWriteOpen, bz2err = %d", bz2err);
396 	BZ2_bzWrite(&bz2err, pfbz2, db, dblen);
397 	if (bz2err != BZ_OK)
398 		errx(1, "BZ2_bzWrite, bz2err = %d", bz2err);
399 	BZ2_bzWriteClose(&bz2err, pfbz2, 0, NULL, NULL);
400 	if (bz2err != BZ_OK)
401 		errx(1, "BZ2_bzWriteClose, bz2err = %d", bz2err);
402 
403 	/* Compute size of compressed diff data */
404 	if ((newsize = ftello(pf)) == -1)
405 		err(1, "ftello");
406 	offtout(newsize - len, header + 16);
407 
408 	/* Write compressed extra data */
409 	if ((pfbz2 = BZ2_bzWriteOpen(&bz2err, pf, 9, 0, 0)) == NULL)
410 		errx(1, "BZ2_bzWriteOpen, bz2err = %d", bz2err);
411 	BZ2_bzWrite(&bz2err, pfbz2, eb, eblen);
412 	if (bz2err != BZ_OK)
413 		errx(1, "BZ2_bzWrite, bz2err = %d", bz2err);
414 	BZ2_bzWriteClose(&bz2err, pfbz2, 0, NULL, NULL);
415 	if (bz2err != BZ_OK)
416 		errx(1, "BZ2_bzWriteClose, bz2err = %d", bz2err);
417 
418 	/* Seek to the beginning, write the header, and close the file */
419 	if (fseeko(pf, 0, SEEK_SET))
420 		err(1, "fseeko");
421 	if (fwrite(header, 32, 1, pf) != 1)
422 		err(1, "fwrite(%s)", argv[3]);
423 	if (fclose(pf))
424 		err(1, "fclose");
425 
426 	/* Free the memory we used */
427 	free(db);
428 	free(eb);
429 	free(I);
430 	free(old);
431 	free(new);
432 
433 	return 0;
434 }
435