Blob


1 /* Generic infrastructure to implement various diff algorithms (implementation). */
2 /*
3 * Copyright (c) 2020 Neels Hofmeyr <neels@hofmeyr.de>
4 *
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 */
19 #include <sys/queue.h>
20 #include <ctype.h>
21 #include <errno.h>
22 #include <stdint.h>
23 #include <stdlib.h>
24 #include <stdbool.h>
25 #include <stdio.h>
26 #include <string.h>
27 #include <limits.h>
28 #include <unistd.h>
30 #include <assert.h>
32 #include <arraylist.h>
33 #include <diff_main.h>
35 #include "diff_internal.h"
36 #include "diff_debug.h"
38 static int
39 read_at(FILE *f, off_t at_pos, unsigned char *buf, size_t len)
40 {
41 int r;
42 if (fseeko(f, at_pos, SEEK_SET) == -1)
43 return errno;
44 r = fread(buf, sizeof(char), len, f);
45 if ((r == 0 || r < len) && ferror(f))
46 return errno;
47 if (r != len)
48 return EIO;
49 return 0;
50 }
52 static int
53 buf_cmp(const unsigned char *left, size_t left_len,
54 const unsigned char *right, size_t right_len,
55 bool ignore_whitespace)
56 {
57 int cmp;
59 if (ignore_whitespace) {
60 int il = 0, ir = 0;
61 while (il < left_len && ir < right_len) {
62 unsigned char cl = left[il];
63 unsigned char cr = right[ir];
65 if (isspace(cl) && il < left_len) {
66 il++;
67 continue;
68 }
69 if (isspace(cr) && ir < right_len) {
70 ir++;
71 continue;
72 }
74 if (cl > cr)
75 return 1;
76 if (cr > cl)
77 return -1;
78 il++;
79 ir++;
80 }
81 while (il < left_len) {
82 unsigned char cl = left[il++];
83 if (!isspace(cl))
84 return 1;
85 }
86 while (ir < right_len) {
87 unsigned char cr = right[ir++];
88 if (!isspace(cr))
89 return -1;
90 }
92 return 0;
93 }
95 cmp = memcmp(left, right, MIN(left_len, right_len));
96 if (cmp)
97 return cmp;
98 if (left_len == right_len)
99 return 0;
100 return (left_len > right_len) ? 1 : -1;
103 int
104 diff_atom_cmp(int *cmp,
105 const struct diff_atom *left,
106 const struct diff_atom *right)
108 off_t remain_left, remain_right;
109 int flags = (left->d->root->diff_flags | right->d->root->diff_flags);
110 bool ignore_whitespace = (flags & DIFF_FLAG_IGNORE_WHITESPACE);
112 if (!ignore_whitespace) {
113 if (!left->len && !right->len) {
114 *cmp = 0;
115 return 0;
117 if (!right->len) {
118 *cmp = 1;
119 return 0;
121 if (!left->len) {
122 *cmp = -1;
123 return 0;
127 if (left->at != NULL && right->at != NULL) {
128 *cmp = buf_cmp(left->at, left->len, right->at, right->len,
129 ignore_whitespace);
130 return 0;
133 remain_left = left->len;
134 remain_right = right->len;
135 while (remain_left > 0 || remain_right > 0) {
136 const size_t chunksz = 8192;
137 unsigned char buf_left[chunksz], buf_right[chunksz];
138 const uint8_t *p_left, *p_right;
139 off_t n_left, n_right;
140 ssize_t r;
142 if (!remain_right) {
143 *cmp = 1;
144 return 0;
146 if (!remain_left) {
147 *cmp = -1;
148 return 0;
151 n_left = MIN(chunksz, remain_left);
152 n_right = MIN(chunksz, remain_right);
154 if (left->at == NULL) {
155 r = read_at(left->d->root->f,
156 left->pos + (left->len - remain_left),
157 buf_left, n_left);
158 if (r) {
159 *cmp = 0;
160 return r;
162 p_left = buf_left;
163 } else {
164 p_left = left->at + (left->len - remain_left);
167 if (right->at == NULL) {
168 r = read_at(right->d->root->f,
169 right->pos + (right->len - remain_right),
170 buf_right, n_right);
171 if (r) {
172 *cmp = 0;
173 return r;
175 p_right = buf_right;
176 } else {
177 p_right = right->at + (right->len - remain_right);
180 r = buf_cmp(p_left, n_left, p_right, n_right,
181 ignore_whitespace);
182 if (r) {
183 *cmp = r;
184 return 0;
187 remain_left -= n_left;
188 remain_right -= n_right;
191 *cmp = 0;
192 return 0;
195 int
196 diff_atom_same(bool *same,
197 const struct diff_atom *left,
198 const struct diff_atom *right)
200 int cmp;
201 int r = diff_atom_cmp(&cmp, left, right);
202 if (r) {
203 *same = true;
204 return r;
206 *same = (cmp == 0);
207 return 0;
210 static struct diff_chunk *
211 diff_state_add_solved_chunk(struct diff_state *state,
212 const struct diff_chunk *chunk)
214 diff_chunk_arraylist_t *result;
215 struct diff_chunk *new_chunk;
216 enum diff_chunk_type last_t;
217 enum diff_chunk_type new_t;
219 /* Append to solved chunks; make sure that adjacent chunks of same type are combined, and that a minus chunk
220 * never directly follows a plus chunk. */
221 result = &state->result->chunks;
223 last_t = diff_chunk_type(&result->head[result->len - 1]);
224 new_t = diff_chunk_type(chunk);
226 debug("Add %s chunk:\n", chunk->solved ? "solved" : "UNSOLVED");
227 debug("L\n");
228 debug_dump_atoms(&state->left, chunk->left_start, chunk->left_count);
229 debug("R\n");
230 debug_dump_atoms(&state->right, chunk->right_start, chunk->right_count);
232 if (new_t == last_t) {
233 new_chunk = &result->head[result->len - 1];
234 new_chunk->left_count += chunk->left_count;
235 new_chunk->right_count += chunk->right_count;
236 debug(" - added chunk touches previous one of same type, joined:\n");
237 debug("L\n");
238 debug_dump_atoms(&state->left, new_chunk->left_start, new_chunk->left_count);
239 debug("R\n");
240 debug_dump_atoms(&state->right, new_chunk->right_start, new_chunk->right_count);
241 } else if (last_t == CHUNK_PLUS && new_t == CHUNK_MINUS) {
242 enum diff_chunk_type prev_last_t =
243 result->len > 1 ?
244 diff_chunk_type(&result->head[result->len - 2])
245 : CHUNK_EMPTY;
246 /* If a minus-chunk follows a plus-chunk, place it above the plus-chunk->
247 * Is the one before that also a minus? combine. */
248 if (prev_last_t == CHUNK_MINUS) {
249 new_chunk = &result->head[result->len - 2];
250 new_chunk->left_count += chunk->left_count;
251 new_chunk->right_count += chunk->right_count;
253 debug(" - added minus-chunk follows plus-chunk,"
254 " put before that plus-chunk and joined"
255 " with preceding minus-chunk:\n");
256 debug("L\n");
257 debug_dump_atoms(&state->left, new_chunk->left_start, new_chunk->left_count);
258 debug("R\n");
259 debug_dump_atoms(&state->right, new_chunk->right_start, new_chunk->right_count);
260 } else {
261 ARRAYLIST_INSERT(new_chunk, *result, result->len - 1);
262 if (!new_chunk)
263 return NULL;
264 *new_chunk = *chunk;
266 debug(" - added minus-chunk follows plus-chunk,"
267 " put before that plus-chunk\n");
269 } else {
270 ARRAYLIST_ADD(new_chunk, *result);
271 if (!new_chunk)
272 return NULL;
273 *new_chunk = *chunk;
275 return new_chunk;
278 /* Even if a left or right side is empty, diff output may need to know the
279 * position in that file.
280 * So left_start or right_start must never be NULL -- pass left_count or
281 * right_count as zero to indicate staying at that position without consuming
282 * any lines. */
283 struct diff_chunk *
284 diff_state_add_chunk(struct diff_state *state, bool solved,
285 struct diff_atom *left_start, unsigned int left_count,
286 struct diff_atom *right_start, unsigned int right_count)
288 diff_chunk_arraylist_t *result = NULL;
289 struct diff_chunk *new_chunk;
290 struct diff_chunk chunk = {
291 .solved = solved,
292 .left_start = left_start,
293 .left_count = left_count,
294 .right_start = right_start,
295 .right_count = right_count,
296 };
298 if (!solved || state->temp_result.len) {
299 /* Append to temp_result */
300 debug("append to temp_result\n");
301 result = &state->temp_result;
302 } else if (!state->result->chunks.len) {
303 /* Append to final result */
304 debug("first chunk\n");
305 result = &state->result->chunks;
307 if (result) {
308 ARRAYLIST_ADD(new_chunk, *result);
309 if (!new_chunk)
310 return NULL;
311 *new_chunk = chunk;
312 return new_chunk;
315 return diff_state_add_solved_chunk(state, &chunk);
318 void
319 diff_data_init_root(struct diff_data *d, FILE *f, const uint8_t *data,
320 unsigned long long len, int diff_flags)
322 *d = (struct diff_data){
323 .f = f,
324 .pos = 0,
325 .data = data,
326 .len = len,
327 .root = d,
328 .diff_flags = diff_flags,
329 };
332 void
333 diff_data_init_subsection(struct diff_data *d, struct diff_data *parent,
334 struct diff_atom *from_atom, unsigned int atoms_count)
336 struct diff_atom *last_atom;
338 if (atoms_count == 0) {
339 *d = (struct diff_data){
340 .f = NULL,
341 .pos = 0,
342 .data = "",
343 .len = 0,
344 .root = parent->root,
345 .atoms.head = NULL,
346 .atoms.len = atoms_count,
347 };
349 return;
352 last_atom = from_atom + atoms_count - 1;
353 *d = (struct diff_data){
354 .f = NULL,
355 .pos = from_atom->pos,
356 .data = from_atom->at,
357 .len = (last_atom->pos + last_atom->len) - from_atom->pos,
358 .root = parent->root,
359 .atoms.head = from_atom,
360 .atoms.len = atoms_count,
361 };
363 debug("subsection:\n");
364 debug_dump(d);
367 void
368 diff_data_free(struct diff_data *diff_data)
370 if (!diff_data)
371 return;
372 if (diff_data->atoms.allocated)
373 ARRAYLIST_FREE(diff_data->atoms);
376 int
377 diff_algo_none(const struct diff_algo_config *algo_config,
378 struct diff_state *state)
380 debug("\n** %s\n", __func__);
381 debug("left:\n");
382 debug_dump(&state->left);
383 debug("right:\n");
384 debug_dump(&state->right);
385 debug_dump_myers_graph(&state->left, &state->right, NULL, NULL, 0, NULL,
386 0);
388 /* Add a chunk of equal lines, if any */
389 struct diff_atom *l = state->left.atoms.head;
390 unsigned int l_len = state->left.atoms.len;
391 struct diff_atom *r = state->right.atoms.head;
392 unsigned int r_len = state->right.atoms.len;
393 unsigned int equal_atoms_start = 0;
394 unsigned int equal_atoms_end = 0;
395 unsigned int l_idx = 0;
396 unsigned int r_idx = 0;
398 while (equal_atoms_start < l_len
399 && equal_atoms_start < r_len) {
400 int err;
401 bool same;
402 err = diff_atom_same(&same, &l[equal_atoms_start],
403 &r[equal_atoms_start]);
404 if (err)
405 return err;
406 if (!same)
407 break;
408 equal_atoms_start++;
410 while (equal_atoms_end < (l_len - equal_atoms_start)
411 && equal_atoms_end < (r_len - equal_atoms_start)) {
412 int err;
413 bool same;
414 err = diff_atom_same(&same, &l[l_len - 1 - equal_atoms_end],
415 &r[r_len - 1 - equal_atoms_end]);
416 if (err)
417 return err;
418 if (!same)
419 break;
420 equal_atoms_end++;
423 /* Add a chunk of equal lines at the start */
424 if (equal_atoms_start) {
425 if (!diff_state_add_chunk(state, true,
426 &l[0],
427 equal_atoms_start,
428 &r[0],
429 equal_atoms_start))
430 return ENOMEM;
431 l_idx += equal_atoms_start;
432 r_idx += equal_atoms_start;
435 /* Add a "minus" chunk with all lines from the left. */
436 if (equal_atoms_start + equal_atoms_end < l_len) {
437 unsigned int add_len = l_len - equal_atoms_start - equal_atoms_end;
438 if (!diff_state_add_chunk(state, true,
439 &l[l_idx], add_len,
440 &r[r_idx], 0))
441 return ENOMEM;
442 l_idx += add_len;
445 /* Add a "plus" chunk with all lines from the right. */
446 if (equal_atoms_start + equal_atoms_end < r_len) {
447 unsigned int add_len = r_len - equal_atoms_start - equal_atoms_end;
448 if (!diff_state_add_chunk(state, true,
449 &l[equal_atoms_start], 0,
450 &r[equal_atoms_start], add_len))
451 return ENOMEM;
452 r_idx += add_len;
455 /* Add a chunk of equal lines at the end */
456 if (equal_atoms_end) {
457 if (!diff_state_add_chunk(state, true,
458 &l[l_idx], equal_atoms_end,
459 &r[r_idx], equal_atoms_end))
460 return ENOMEM;
463 return DIFF_RC_OK;
466 int
467 diff_run_algo(const struct diff_algo_config *algo_config,
468 struct diff_state *state)
470 int rc;
471 ARRAYLIST_FREE(state->temp_result);
473 if (!algo_config || !algo_config->impl
474 || !state->recursion_depth_left) {
475 debug("MAX RECURSION REACHED, just dumping diff chunks\n");
476 return diff_algo_none(algo_config, state);
479 ARRAYLIST_INIT(state->temp_result, DIFF_RESULT_ALLOC_BLOCKSIZE);
480 rc = algo_config->impl(algo_config, state);
481 switch (rc) {
482 case DIFF_RC_USE_DIFF_ALGO_FALLBACK:
483 debug("Got DIFF_RC_USE_DIFF_ALGO_FALLBACK (%p)\n",
484 algo_config->fallback_algo);
485 rc = diff_run_algo(algo_config->fallback_algo, state);
486 goto return_rc;
488 case DIFF_RC_OK:
489 /* continue below */
490 break;
492 default:
493 /* some error happened */
494 goto return_rc;
497 /* Pick up any diff chunks that are still unsolved and feed to
498 * inner_algo. inner_algo will solve unsolved chunks and append to
499 * result, and subsequent solved chunks on this level are then appended
500 * to result afterwards. */
501 int i;
502 for (i = 0; i < state->temp_result.len; i++) {
503 struct diff_chunk *c = &state->temp_result.head[i];
504 if (c->solved) {
505 diff_state_add_solved_chunk(state, c);
506 continue;
509 /* c is an unsolved chunk, feed to inner_algo */
510 struct diff_state inner_state = {
511 .result = state->result,
512 .recursion_depth_left = state->recursion_depth_left - 1,
513 };
514 diff_data_init_subsection(&inner_state.left, &state->left,
515 c->left_start, c->left_count);
516 diff_data_init_subsection(&inner_state.right, &state->right,
517 c->right_start, c->right_count);
519 rc = diff_run_algo(algo_config->inner_algo, &inner_state);
521 if (rc != DIFF_RC_OK)
522 goto return_rc;
525 rc = DIFF_RC_OK;
526 return_rc:
527 ARRAYLIST_FREE(state->temp_result);
528 return rc;
531 struct diff_result *
532 diff_main(const struct diff_config *config,
533 FILE *left_f, const uint8_t *left_data, off_t left_len,
534 FILE *right_f, const uint8_t *right_data, off_t right_len,
535 int diff_flags)
537 struct diff_result *result = malloc(sizeof(struct diff_result));
538 if (!result)
539 return NULL;
541 *result = (struct diff_result){};
542 diff_data_init_root(&result->left, left_f, left_data, left_len,
543 diff_flags);
544 diff_data_init_root(&result->right, right_f, right_data, right_len,
545 diff_flags);
547 if (!config->atomize_func) {
548 result->rc = EINVAL;
549 return result;
552 result->rc = config->atomize_func(config->atomize_func_data,
553 &result->left, &result->right);
554 if (result->rc != DIFF_RC_OK)
555 return result;
557 struct diff_state state = {
558 .result = result,
559 .recursion_depth_left = config->max_recursion_depth ? : 32,
560 };
561 diff_data_init_subsection(&state.left, &result->left,
562 result->left.atoms.head,
563 result->left.atoms.len);
564 diff_data_init_subsection(&state.right, &result->right,
565 result->right.atoms.head,
566 result->right.atoms.len);
568 result->rc = diff_run_algo(config->algo, &state);
570 return result;
573 void
574 diff_result_free(struct diff_result *result)
576 if (!result)
577 return;
578 diff_data_free(&result->left);
579 diff_data_free(&result->right);
580 ARRAYLIST_FREE(result->chunks);
581 free(result);