• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * runlist.c - Run list handling code. Originated from the Linux-NTFS project.
3  *
4  * Copyright (c) 2002-2005 Anton Altaparmakov
5  * Copyright (c) 2002-2005 Richard Russon
6  * Copyright (c) 2002-2008 Szabolcs Szakacsits
7  * Copyright (c) 2004 Yura Pakhuchiy
8  * Copyright (c) 2007-2022 Jean-Pierre Andre
9  *
10  * This program/include file is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License as published
12  * by the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program/include file is distributed in the hope that it will be
16  * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
17  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program (in the main directory of the NTFS-3G
22  * distribution in the file COPYING); if not, write to the Free Software
23  * Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24  */
25 
26 #ifdef HAVE_CONFIG_H
27 #include "config.h"
28 #endif
29 
30 #ifdef HAVE_STDIO_H
31 #include <stdio.h>
32 #endif
33 #ifdef HAVE_STRING_H
34 #include <string.h>
35 #endif
36 #ifdef HAVE_STDLIB_H
37 #include <stdlib.h>
38 #endif
39 #ifdef HAVE_ERRNO_H
40 #include <errno.h>
41 #endif
42 
43 #include "compat.h"
44 #include "types.h"
45 #include "volume.h"
46 #include "layout.h"
47 #include "debug.h"
48 #include "device.h"
49 #include "logging.h"
50 #include "misc.h"
51 
52 /**
53  * ntfs_rl_mm - runlist memmove
54  * @base:
55  * @dst:
56  * @src:
57  * @size:
58  *
59  * Description...
60  *
61  * Returns:
62  */
ntfs_rl_mm(runlist_element * base,int dst,int src,int size)63 static void ntfs_rl_mm(runlist_element *base, int dst, int src, int size)
64 {
65 	if ((dst != src) && (size > 0))
66 		memmove(base + dst, base + src, size * sizeof(*base));
67 }
68 
69 /**
70  * ntfs_rl_mc - runlist memory copy
71  * @dstbase:
72  * @dst:
73  * @srcbase:
74  * @src:
75  * @size:
76  *
77  * Description...
78  *
79  * Returns:
80  */
ntfs_rl_mc(runlist_element * dstbase,int dst,runlist_element * srcbase,int src,int size)81 static void ntfs_rl_mc(runlist_element *dstbase, int dst,
82 		       runlist_element *srcbase, int src, int size)
83 {
84 	if (size > 0)
85 		memcpy(dstbase + dst, srcbase + src, size * sizeof(*dstbase));
86 }
87 
88 /**
89  * ntfs_rl_realloc - Reallocate memory for runlists
90  * @rl:		original runlist
91  * @old_size:	number of runlist elements in the original runlist @rl
92  * @new_size:	number of runlist elements we need space for
93  *
94  * As the runlists grow, more memory will be required. To prevent large
95  * numbers of small reallocations of memory, this function returns a 4kiB block
96  * of memory.
97  *
98  * N.B.	If the new allocation doesn't require a different number of 4kiB
99  *	blocks in memory, the function will return the original pointer.
100  *
101  * On success, return a pointer to the newly allocated, or recycled, memory.
102  * On error, return NULL with errno set to the error code.
103  */
ntfs_rl_realloc(runlist_element * rl,int old_size,int new_size)104 static runlist_element *ntfs_rl_realloc(runlist_element *rl, int old_size,
105 					int new_size)
106 {
107 	old_size = (old_size * sizeof(runlist_element) + 0xfff) & ~0xfff;
108 	new_size = (new_size * sizeof(runlist_element) + 0xfff) & ~0xfff;
109 	if (old_size == new_size)
110 		return rl;
111 	return realloc(rl, new_size);
112 }
113 
114 /*
115  *		Extend a runlist by some entry count
116  *	The runlist may have to be reallocated
117  *
118  *	Returns the reallocated runlist
119  *		or NULL if reallocation was not possible (with errno set)
120  *		the runlist is left unchanged if the reallocation fails
121  */
122 
ntfs_rl_extend(ntfs_attr * na,runlist_element * rl,int more_entries)123 runlist_element *ntfs_rl_extend(ntfs_attr *na, runlist_element *rl,
124 			int more_entries)
125 {
126 	runlist_element *newrl;
127 	int last;
128 	int irl;
129 
130 	if (na->rl && rl) {
131 		irl = (int)(rl - na->rl);
132 		last = irl;
133 		while (na->rl[last].length)
134 			last++;
135 		newrl = ntfs_rl_realloc(na->rl,last+1,last+more_entries+1);
136 		if (!newrl) {
137 			errno = ENOMEM;
138 			rl = (runlist_element*)NULL;
139 		} else {
140 			na->rl = newrl;
141 			rl = &newrl[irl];
142 		}
143 	} else {
144 		ntfs_log_error("Cannot extend unmapped runlist");
145 		errno = EIO;
146 		rl = (runlist_element*)NULL;
147 	}
148 	return (rl);
149 }
150 
151 /**
152  * ntfs_rl_are_mergeable - test if two runlists can be joined together
153  * @dst:	original runlist
154  * @src:	new runlist to test for mergeability with @dst
155  *
156  * Test if two runlists can be joined together. For this, their VCNs and LCNs
157  * must be adjacent.
158  *
159  * Return: TRUE   Success, the runlists can be merged.
160  *	   FALSE  Failure, the runlists cannot be merged.
161  */
ntfs_rl_are_mergeable(runlist_element * dst,runlist_element * src)162 static BOOL ntfs_rl_are_mergeable(runlist_element *dst, runlist_element *src)
163 {
164 	if (!dst || !src) {
165 		ntfs_log_debug("Eeek. ntfs_rl_are_mergeable() invoked with NULL "
166 				"pointer!\n");
167 		return FALSE;
168 	}
169 
170 	/* We can merge unmapped regions even if they are misaligned. */
171 	if ((dst->lcn == LCN_RL_NOT_MAPPED) && (src->lcn == LCN_RL_NOT_MAPPED))
172 		return TRUE;
173 	/* If the runs are misaligned, we cannot merge them. */
174 	if ((dst->vcn + dst->length) != src->vcn)
175 		return FALSE;
176 	/* If both runs are non-sparse and contiguous, we can merge them. */
177 	if ((dst->lcn >= 0) && (src->lcn >= 0) &&
178 		((dst->lcn + dst->length) == src->lcn))
179 		return TRUE;
180 	/* If we are merging two holes, we can merge them. */
181 	if ((dst->lcn == LCN_HOLE) && (src->lcn == LCN_HOLE))
182 		return TRUE;
183 	/* Cannot merge. */
184 	return FALSE;
185 }
186 
187 /**
188  * __ntfs_rl_merge - merge two runlists without testing if they can be merged
189  * @dst:	original, destination runlist
190  * @src:	new runlist to merge with @dst
191  *
192  * Merge the two runlists, writing into the destination runlist @dst. The
193  * caller must make sure the runlists can be merged or this will corrupt the
194  * destination runlist.
195  */
__ntfs_rl_merge(runlist_element * dst,runlist_element * src)196 static void __ntfs_rl_merge(runlist_element *dst, runlist_element *src)
197 {
198 	dst->length += src->length;
199 }
200 
201 /**
202  * ntfs_rl_append - append a runlist after a given element
203  * @dst:	original runlist to be worked on
204  * @dsize:	number of elements in @dst (including end marker)
205  * @src:	runlist to be inserted into @dst
206  * @ssize:	number of elements in @src (excluding end marker)
207  * @loc:	append the new runlist @src after this element in @dst
208  *
209  * Append the runlist @src after element @loc in @dst.  Merge the right end of
210  * the new runlist, if necessary. Adjust the size of the hole before the
211  * appended runlist.
212  *
213  * On success, return a pointer to the new, combined, runlist. Note, both
214  * runlists @dst and @src are deallocated before returning so you cannot use
215  * the pointers for anything any more. (Strictly speaking the returned runlist
216  * may be the same as @dst but this is irrelevant.)
217  *
218  * On error, return NULL, with errno set to the error code. Both runlists are
219  * left unmodified.
220  */
ntfs_rl_append(runlist_element * dst,int dsize,runlist_element * src,int ssize,int loc)221 static runlist_element *ntfs_rl_append(runlist_element *dst, int dsize,
222 				       runlist_element *src, int ssize, int loc)
223 {
224 	BOOL right = FALSE;	/* Right end of @src needs merging */
225 	int marker;		/* End of the inserted runs */
226 
227 	if (!dst || !src) {
228 		ntfs_log_debug("Eeek. ntfs_rl_append() invoked with NULL "
229 				"pointer!\n");
230 		errno = EINVAL;
231 		return NULL;
232 	}
233 
234 	/* First, check if the right hand end needs merging. */
235 	if ((loc + 1) < dsize)
236 		right = ntfs_rl_are_mergeable(src + ssize - 1, dst + loc + 1);
237 
238 	/* Space required: @dst size + @src size, less one if we merged. */
239 	dst = ntfs_rl_realloc(dst, dsize, dsize + ssize - right);
240 	if (!dst)
241 		return NULL;
242 	/*
243 	 * We are guaranteed to succeed from here so can start modifying the
244 	 * original runlists.
245 	 */
246 
247 	/* First, merge the right hand end, if necessary. */
248 	if (right)
249 		__ntfs_rl_merge(src + ssize - 1, dst + loc + 1);
250 
251 	/* marker - First run after the @src runs that have been inserted */
252 	marker = loc + ssize + 1;
253 
254 	/* Move the tail of @dst out of the way, then copy in @src. */
255 	ntfs_rl_mm(dst, marker, loc + 1 + right, dsize - loc - 1 - right);
256 	ntfs_rl_mc(dst, loc + 1, src, 0, ssize);
257 
258 	/* Adjust the size of the preceding hole. */
259 	dst[loc].length = dst[loc + 1].vcn - dst[loc].vcn;
260 
261 	/* We may have changed the length of the file, so fix the end marker */
262 	if (dst[marker].lcn == LCN_ENOENT)
263 		dst[marker].vcn = dst[marker-1].vcn + dst[marker-1].length;
264 
265 	return dst;
266 }
267 
268 /**
269  * ntfs_rl_insert - insert a runlist into another
270  * @dst:	original runlist to be worked on
271  * @dsize:	number of elements in @dst (including end marker)
272  * @src:	new runlist to be inserted
273  * @ssize:	number of elements in @src (excluding end marker)
274  * @loc:	insert the new runlist @src before this element in @dst
275  *
276  * Insert the runlist @src before element @loc in the runlist @dst. Merge the
277  * left end of the new runlist, if necessary. Adjust the size of the hole
278  * after the inserted runlist.
279  *
280  * On success, return a pointer to the new, combined, runlist. Note, both
281  * runlists @dst and @src are deallocated before returning so you cannot use
282  * the pointers for anything any more. (Strictly speaking the returned runlist
283  * may be the same as @dst but this is irrelevant.)
284  *
285  * On error, return NULL, with errno set to the error code. Both runlists are
286  * left unmodified.
287  */
ntfs_rl_insert(runlist_element * dst,int dsize,runlist_element * src,int ssize,int loc)288 static runlist_element *ntfs_rl_insert(runlist_element *dst, int dsize,
289 				       runlist_element *src, int ssize, int loc)
290 {
291 	BOOL left = FALSE;	/* Left end of @src needs merging */
292 	BOOL disc = FALSE;	/* Discontinuity between @dst and @src */
293 	int marker;		/* End of the inserted runs */
294 
295 	if (!dst || !src) {
296 		ntfs_log_debug("Eeek. ntfs_rl_insert() invoked with NULL "
297 				"pointer!\n");
298 		errno = EINVAL;
299 		return NULL;
300 	}
301 
302 	/* disc => Discontinuity between the end of @dst and the start of @src.
303 	 *	   This means we might need to insert a "notmapped" run.
304 	 */
305 	if (loc == 0)
306 		disc = (src[0].vcn > 0);
307 	else {
308 		s64 merged_length;
309 
310 		left = ntfs_rl_are_mergeable(dst + loc - 1, src);
311 
312 		merged_length = dst[loc - 1].length;
313 		if (left)
314 			merged_length += src->length;
315 
316 		disc = (src[0].vcn > dst[loc - 1].vcn + merged_length);
317 	}
318 
319 	/* Space required: @dst size + @src size, less one if we merged, plus
320 	 * one if there was a discontinuity.
321 	 */
322 	dst = ntfs_rl_realloc(dst, dsize, dsize + ssize - left + disc);
323 	if (!dst)
324 		return NULL;
325 	/*
326 	 * We are guaranteed to succeed from here so can start modifying the
327 	 * original runlist.
328 	 */
329 
330 	if (left)
331 		__ntfs_rl_merge(dst + loc - 1, src);
332 
333 	/*
334 	 * marker - First run after the @src runs that have been inserted
335 	 * Nominally: marker = @loc + @ssize (location + number of runs in @src)
336 	 * If "left", then the first run in @src has been merged with one in @dst.
337 	 * If "disc", then @dst and @src don't meet and we need an extra run to fill the gap.
338 	 */
339 	marker = loc + ssize - left + disc;
340 
341 	/* Move the tail of @dst out of the way, then copy in @src. */
342 	ntfs_rl_mm(dst, marker, loc, dsize - loc);
343 	ntfs_rl_mc(dst, loc + disc, src, left, ssize - left);
344 
345 	/* Adjust the VCN of the first run after the insertion ... */
346 	dst[marker].vcn = dst[marker - 1].vcn + dst[marker - 1].length;
347 	/* ... and the length. */
348 	if (dst[marker].lcn == LCN_HOLE || dst[marker].lcn == LCN_RL_NOT_MAPPED)
349 		dst[marker].length = dst[marker + 1].vcn - dst[marker].vcn;
350 
351 	/* Writing beyond the end of the file and there's a discontinuity. */
352 	if (disc) {
353 		if (loc > 0) {
354 			dst[loc].vcn = dst[loc - 1].vcn + dst[loc - 1].length;
355 			dst[loc].length = dst[loc + 1].vcn - dst[loc].vcn;
356 		} else {
357 			dst[loc].vcn = 0;
358 			dst[loc].length = dst[loc + 1].vcn;
359 		}
360 		dst[loc].lcn = LCN_RL_NOT_MAPPED;
361 	}
362 	return dst;
363 }
364 
365 /**
366  * ntfs_rl_replace - overwrite a runlist element with another runlist
367  * @dst:	original runlist to be worked on
368  * @dsize:	number of elements in @dst (including end marker)
369  * @src:	new runlist to be inserted
370  * @ssize:	number of elements in @src (excluding end marker)
371  * @loc:	index in runlist @dst to overwrite with @src
372  *
373  * Replace the runlist element @dst at @loc with @src. Merge the left and
374  * right ends of the inserted runlist, if necessary.
375  *
376  * On success, return a pointer to the new, combined, runlist. Note, both
377  * runlists @dst and @src are deallocated before returning so you cannot use
378  * the pointers for anything any more. (Strictly speaking the returned runlist
379  * may be the same as @dst but this is irrelevant.)
380  *
381  * On error, return NULL, with errno set to the error code. Both runlists are
382  * left unmodified.
383  */
ntfs_rl_replace(runlist_element * dst,int dsize,runlist_element * src,int ssize,int loc)384 static runlist_element *ntfs_rl_replace(runlist_element *dst, int dsize,
385 					runlist_element *src, int ssize,
386 					int loc)
387 {
388 	signed delta;
389 	BOOL left  = FALSE;	/* Left end of @src needs merging */
390 	BOOL right = FALSE;	/* Right end of @src needs merging */
391 	int tail;		/* Start of tail of @dst */
392 	int marker;		/* End of the inserted runs */
393 
394 	if (!dst || !src) {
395 		ntfs_log_debug("Eeek. ntfs_rl_replace() invoked with NULL "
396 				"pointer!\n");
397 		errno = EINVAL;
398 		return NULL;
399 	}
400 
401 	/* First, see if the left and right ends need merging. */
402 	if ((loc + 1) < dsize)
403 		right = ntfs_rl_are_mergeable(src + ssize - 1, dst + loc + 1);
404 	if (loc > 0)
405 		left = ntfs_rl_are_mergeable(dst + loc - 1, src);
406 
407 	/* Allocate some space. We'll need less if the left, right, or both
408 	 * ends get merged.  The -1 accounts for the run being replaced.
409 	 */
410 	delta = ssize - 1 - left - right;
411 	if (delta > 0) {
412 		dst = ntfs_rl_realloc(dst, dsize, dsize + delta);
413 		if (!dst)
414 			return NULL;
415 	}
416 	/*
417 	 * We are guaranteed to succeed from here so can start modifying the
418 	 * original runlists.
419 	 */
420 
421 	/* First, merge the left and right ends, if necessary. */
422 	if (right)
423 		__ntfs_rl_merge(src + ssize - 1, dst + loc + 1);
424 	if (left)
425 		__ntfs_rl_merge(dst + loc - 1, src);
426 
427 	/*
428 	 * tail - Offset of the tail of @dst
429 	 * Nominally: @tail = @loc + 1 (location, skipping the replaced run)
430 	 * If "right", then one of @dst's runs is already merged into @src.
431 	 */
432 	tail = loc + right + 1;
433 
434 	/*
435 	 * marker - First run after the @src runs that have been inserted
436 	 * Nominally: @marker = @loc + @ssize (location + number of runs in @src)
437 	 * If "left", then the first run in @src has been merged with one in @dst.
438 	 */
439 	marker = loc + ssize - left;
440 
441 	/* Move the tail of @dst out of the way, then copy in @src. */
442 	ntfs_rl_mm(dst, marker, tail, dsize - tail);
443 	ntfs_rl_mc(dst, loc, src, left, ssize - left);
444 
445 	/* We may have changed the length of the file, so fix the end marker */
446 	if (((dsize - tail) > 0) && (dst[marker].lcn == LCN_ENOENT))
447 		dst[marker].vcn = dst[marker - 1].vcn + dst[marker - 1].length;
448 
449 	return dst;
450 }
451 
452 /**
453  * ntfs_rl_split - insert a runlist into the centre of a hole
454  * @dst:	original runlist to be worked on
455  * @dsize:	number of elements in @dst (including end marker)
456  * @src:	new runlist to be inserted
457  * @ssize:	number of elements in @src (excluding end marker)
458  * @loc:	index in runlist @dst at which to split and insert @src
459  *
460  * Split the runlist @dst at @loc into two and insert @new in between the two
461  * fragments. No merging of runlists is necessary. Adjust the size of the
462  * holes either side.
463  *
464  * On success, return a pointer to the new, combined, runlist. Note, both
465  * runlists @dst and @src are deallocated before returning so you cannot use
466  * the pointers for anything any more. (Strictly speaking the returned runlist
467  * may be the same as @dst but this is irrelevant.)
468  *
469  * On error, return NULL, with errno set to the error code. Both runlists are
470  * left unmodified.
471  */
ntfs_rl_split(runlist_element * dst,int dsize,runlist_element * src,int ssize,int loc)472 static runlist_element *ntfs_rl_split(runlist_element *dst, int dsize,
473 				      runlist_element *src, int ssize, int loc)
474 {
475 	if (!dst || !src) {
476 		ntfs_log_debug("Eeek. ntfs_rl_split() invoked with NULL pointer!\n");
477 		errno = EINVAL;
478 		return NULL;
479 	}
480 
481 	/* Space required: @dst size + @src size + one new hole. */
482 	dst = ntfs_rl_realloc(dst, dsize, dsize + ssize + 1);
483 	if (!dst)
484 		return dst;
485 	/*
486 	 * We are guaranteed to succeed from here so can start modifying the
487 	 * original runlists.
488 	 */
489 
490 	/* Move the tail of @dst out of the way, then copy in @src. */
491 	ntfs_rl_mm(dst, loc + 1 + ssize, loc, dsize - loc);
492 	ntfs_rl_mc(dst, loc + 1, src, 0, ssize);
493 
494 	/* Adjust the size of the holes either size of @src. */
495 	dst[loc].length		= dst[loc+1].vcn       - dst[loc].vcn;
496 	dst[loc+ssize+1].vcn	= dst[loc+ssize].vcn   + dst[loc+ssize].length;
497 	dst[loc+ssize+1].length	= dst[loc+ssize+2].vcn - dst[loc+ssize+1].vcn;
498 
499 	return dst;
500 }
501 
502 
503 /**
504  * ntfs_runlists_merge_i - see ntfs_runlists_merge
505  */
ntfs_runlists_merge_i(runlist_element * drl,runlist_element * srl)506 static runlist_element *ntfs_runlists_merge_i(runlist_element *drl,
507 					      runlist_element *srl)
508 {
509 	int di, si;		/* Current index into @[ds]rl. */
510 	int sstart;		/* First index with lcn > LCN_RL_NOT_MAPPED. */
511 	int dins;		/* Index into @drl at which to insert @srl. */
512 	int dend, send;		/* Last index into @[ds]rl. */
513 	int dfinal, sfinal;	/* The last index into @[ds]rl with
514 				   lcn >= LCN_HOLE. */
515 	int marker = 0;
516 	VCN marker_vcn = 0;
517 
518 	ntfs_log_debug("dst:\n");
519 	ntfs_debug_runlist_dump(drl);
520 	ntfs_log_debug("src:\n");
521 	ntfs_debug_runlist_dump(srl);
522 
523 	/* Check for silly calling... */
524 	if (!srl)
525 		return drl;
526 
527 	/* Check for the case where the first mapping is being done now. */
528 	if (!drl) {
529 		drl = srl;
530 		/* Complete the source runlist if necessary. */
531 		if (drl[0].vcn) {
532 			/* Scan to the end of the source runlist. */
533 			for (dend = 0; drl[dend].length; dend++)
534 				;
535 			dend++;
536 			drl = ntfs_rl_realloc(drl, dend, dend + 1);
537 			if (!drl)
538 				return drl;
539 			/* Insert start element at the front of the runlist. */
540 			ntfs_rl_mm(drl, 1, 0, dend);
541 			drl[0].vcn = 0;
542 			drl[0].lcn = LCN_RL_NOT_MAPPED;
543 			drl[0].length = drl[1].vcn;
544 		}
545 		goto finished;
546 	}
547 
548 	si = di = 0;
549 
550 	/* Skip any unmapped start element(s) in the source runlist. */
551 	while (srl[si].length && srl[si].lcn < (LCN)LCN_HOLE)
552 		si++;
553 
554 	/* Can't have an entirely unmapped source runlist. */
555 	if (!srl[si].length) {
556 		errno = EINVAL;
557 		ntfs_log_perror("%s: unmapped source runlist", __FUNCTION__);
558 		return NULL;
559 	}
560 
561 	/* Record the starting points. */
562 	sstart = si;
563 
564 	/*
565 	 * Skip forward in @drl until we reach the position where @srl needs to
566 	 * be inserted. If we reach the end of @drl, @srl just needs to be
567 	 * appended to @drl.
568 	 */
569 	for (; drl[di].length; di++) {
570 		if (drl[di].vcn + drl[di].length > srl[sstart].vcn)
571 			break;
572 	}
573 	dins = di;
574 
575 	/* Sanity check for illegal overlaps. */
576 	if ((drl[di].vcn == srl[si].vcn) && (drl[di].lcn >= 0) &&
577 			(srl[si].lcn >= 0)) {
578 		errno = ERANGE;
579 		ntfs_log_perror("Run lists overlap. Cannot merge");
580 		return NULL;
581 	}
582 
583 	/* Scan to the end of both runlists in order to know their sizes. */
584 	for (send = si; srl[send].length; send++)
585 		;
586 	for (dend = di; drl[dend].length; dend++)
587 		;
588 
589 	if (srl[send].lcn == (LCN)LCN_ENOENT)
590 		marker_vcn = srl[marker = send].vcn;
591 
592 	/* Scan to the last element with lcn >= LCN_HOLE. */
593 	for (sfinal = send; sfinal >= 0 && srl[sfinal].lcn < LCN_HOLE; sfinal--)
594 		;
595 	for (dfinal = dend; dfinal >= 0 && drl[dfinal].lcn < LCN_HOLE; dfinal--)
596 		;
597 
598 	{
599 	BOOL start;
600 	BOOL finish;
601 	int ds = dend + 1;		/* Number of elements in drl & srl */
602 	int ss = sfinal - sstart + 1;
603 
604 	start  = ((drl[dins].lcn <  LCN_RL_NOT_MAPPED) ||    /* End of file   */
605 		  (drl[dins].vcn == srl[sstart].vcn));	     /* Start of hole */
606 	finish = ((drl[dins].lcn >= LCN_RL_NOT_MAPPED) &&    /* End of file   */
607 		 ((drl[dins].vcn + drl[dins].length) <=      /* End of hole   */
608 		  (srl[send - 1].vcn + srl[send - 1].length)));
609 
610 	/* Or we'll lose an end marker */
611 	if (finish && !drl[dins].length)
612 		ss++;
613 	if (marker && (drl[dins].vcn + drl[dins].length > srl[send - 1].vcn))
614 		finish = FALSE;
615 
616 	ntfs_log_debug("dfinal = %i, dend = %i\n", dfinal, dend);
617 	ntfs_log_debug("sstart = %i, sfinal = %i, send = %i\n", sstart, sfinal, send);
618 	ntfs_log_debug("start = %i, finish = %i\n", start, finish);
619 	ntfs_log_debug("ds = %i, ss = %i, dins = %i\n", ds, ss, dins);
620 
621 	if (start) {
622 		if (finish)
623 			drl = ntfs_rl_replace(drl, ds, srl + sstart, ss, dins);
624 		else
625 			drl = ntfs_rl_insert(drl, ds, srl + sstart, ss, dins);
626 	} else {
627 		if (finish)
628 			drl = ntfs_rl_append(drl, ds, srl + sstart, ss, dins);
629 		else
630 			drl = ntfs_rl_split(drl, ds, srl + sstart, ss, dins);
631 	}
632 	if (!drl) {
633 		ntfs_log_perror("Merge failed");
634 		return drl;
635 	}
636 	free(srl);
637 	if (marker) {
638 		ntfs_log_debug("Triggering marker code.\n");
639 		for (ds = dend; drl[ds].length; ds++)
640 			;
641 		/* We only need to care if @srl ended after @drl. */
642 		if (drl[ds].vcn <= marker_vcn) {
643 			int slots = 0;
644 
645 			if (drl[ds].vcn == marker_vcn) {
646 				ntfs_log_debug("Old marker = %lli, replacing with "
647 						"LCN_ENOENT.\n",
648 						(long long)drl[ds].lcn);
649 				drl[ds].lcn = (LCN)LCN_ENOENT;
650 				goto finished;
651 			}
652 			/*
653 			 * We need to create an unmapped runlist element in
654 			 * @drl or extend an existing one before adding the
655 			 * ENOENT terminator.
656 			 */
657 			if (drl[ds].lcn == (LCN)LCN_ENOENT) {
658 				ds--;
659 				slots = 1;
660 			}
661 			if (drl[ds].lcn != (LCN)LCN_RL_NOT_MAPPED) {
662 				/* Add an unmapped runlist element. */
663 				if (!slots) {
664 					/* FIXME/TODO: We need to have the
665 					 * extra memory already! (AIA)
666 					 */
667 					drl = ntfs_rl_realloc(drl, ds, ds + 2);
668 					if (!drl)
669 						goto critical_error;
670 					slots = 2;
671 				}
672 				ds++;
673 				/* Need to set vcn if it isn't set already. */
674 				if (slots != 1)
675 					drl[ds].vcn = drl[ds - 1].vcn +
676 							drl[ds - 1].length;
677 				drl[ds].lcn = (LCN)LCN_RL_NOT_MAPPED;
678 				/* We now used up a slot. */
679 				slots--;
680 			}
681 			drl[ds].length = marker_vcn - drl[ds].vcn;
682 			/* Finally add the ENOENT terminator. */
683 			ds++;
684 			if (!slots) {
685 				/* FIXME/TODO: We need to have the extra
686 				 * memory already! (AIA)
687 				 */
688 				drl = ntfs_rl_realloc(drl, ds, ds + 1);
689 				if (!drl)
690 					goto critical_error;
691 			}
692 			drl[ds].vcn = marker_vcn;
693 			drl[ds].lcn = (LCN)LCN_ENOENT;
694 			drl[ds].length = (s64)0;
695 		}
696 	}
697 	}
698 
699 finished:
700 	/* The merge was completed successfully. */
701 	ntfs_log_debug("Merged runlist:\n");
702 	ntfs_debug_runlist_dump(drl);
703 	return drl;
704 
705 critical_error:
706 	/* Critical error! We cannot afford to fail here. */
707 	ntfs_log_perror("libntfs: Critical error");
708 	ntfs_log_debug("Forcing segmentation fault!\n");
709 	marker_vcn = ((runlist*)NULL)->lcn;
710 	return drl;
711 }
712 
713 /**
714  * ntfs_runlists_merge - merge two runlists into one
715  * @drl:	original runlist to be worked on
716  * @srl:	new runlist to be merged into @drl
717  *
718  * First we sanity check the two runlists @srl and @drl to make sure that they
719  * are sensible and can be merged. The runlist @srl must be either after the
720  * runlist @drl or completely within a hole (or unmapped region) in @drl.
721  *
722  * Merging of runlists is necessary in two cases:
723  *   1. When attribute lists are used and a further extent is being mapped.
724  *   2. When new clusters are allocated to fill a hole or extend a file.
725  *
726  * There are four possible ways @srl can be merged. It can:
727  *	- be inserted at the beginning of a hole,
728  *	- split the hole in two and be inserted between the two fragments,
729  *	- be appended at the end of a hole, or it can
730  *	- replace the whole hole.
731  * It can also be appended to the end of the runlist, which is just a variant
732  * of the insert case.
733  *
734  * On success, return a pointer to the new, combined, runlist. Note, both
735  * runlists @drl and @srl are deallocated before returning so you cannot use
736  * the pointers for anything any more. (Strictly speaking the returned runlist
737  * may be the same as @dst but this is irrelevant.)
738  *
739  * On error, return NULL, with errno set to the error code. Both runlists are
740  * left unmodified. The following error codes are defined:
741  *	ENOMEM		Not enough memory to allocate runlist array.
742  *	EINVAL		Invalid parameters were passed in.
743  *	ERANGE		The runlists overlap and cannot be merged.
744  */
ntfs_runlists_merge(runlist_element * drl,runlist_element * srl)745 runlist_element *ntfs_runlists_merge(runlist_element *drl,
746 		runlist_element *srl)
747 {
748 	runlist_element *rl;
749 
750 	ntfs_log_enter("Entering\n");
751 	rl = ntfs_runlists_merge_i(drl, srl);
752 	ntfs_log_leave("\n");
753 	return rl;
754 }
755 
756 /**
757  * ntfs_mapping_pairs_decompress - convert mapping pairs array to runlist
758  * @vol:	ntfs volume on which the attribute resides
759  * @attr:	attribute record whose mapping pairs array to decompress
760  * @old_rl:	optional runlist in which to insert @attr's runlist
761  *
762  * Decompress the attribute @attr's mapping pairs array into a runlist. On
763  * success, return the decompressed runlist.
764  *
765  * If @old_rl is not NULL, decompressed runlist is inserted into the
766  * appropriate place in @old_rl and the resultant, combined runlist is
767  * returned. The original @old_rl is deallocated.
768  *
769  * On error, return NULL with errno set to the error code. @old_rl is left
770  * unmodified in that case.
771  *
772  * The following error codes are defined:
773  *	ENOMEM		Not enough memory to allocate runlist array.
774  *	EIO		Corrupt runlist.
775  *	EINVAL		Invalid parameters were passed in.
776  *	ERANGE		The two runlists overlap.
777  *
778  * FIXME: For now we take the conceptionally simplest approach of creating the
779  * new runlist disregarding the already existing one and then splicing the
780  * two into one, if that is possible (we check for overlap and discard the new
781  * runlist if overlap present before returning NULL, with errno = ERANGE).
782  */
ntfs_mapping_pairs_decompress_i(const ntfs_volume * vol,const ATTR_RECORD * attr,runlist_element * old_rl)783 static runlist_element *ntfs_mapping_pairs_decompress_i(const ntfs_volume *vol,
784 		const ATTR_RECORD *attr, runlist_element *old_rl)
785 {
786 	VCN vcn;		/* Current vcn. */
787 	LCN lcn;		/* Current lcn. */
788 	s64 deltaxcn;		/* Change in [vl]cn. */
789 	runlist_element *rl;	/* The output runlist. */
790 	const u8 *buf;		/* Current position in mapping pairs array. */
791 	const u8 *attr_end;	/* End of attribute. */
792 	int err, rlsize;	/* Size of runlist buffer. */
793 	u16 rlpos;		/* Current runlist position in units of
794 				   runlist_elements. */
795 	u8 b;			/* Current byte offset in buf. */
796 
797 	ntfs_log_trace("Entering for attr 0x%x.\n",
798 			(unsigned)le32_to_cpu(attr->type));
799 	/* Make sure attr exists and is non-resident. */
800 	if (!attr || !attr->non_resident ||
801 			sle64_to_cpu(attr->lowest_vcn) < (VCN)0) {
802 		errno = EINVAL;
803 		return NULL;
804 	}
805 	/* Start at vcn = lowest_vcn and lcn 0. */
806 	vcn = sle64_to_cpu(attr->lowest_vcn);
807 	lcn = 0;
808 	/* Get start of the mapping pairs array. */
809 	buf = (const u8*)attr + le16_to_cpu(attr->mapping_pairs_offset);
810 	attr_end = (const u8*)attr + le32_to_cpu(attr->length);
811 	if (buf < (const u8*)attr || buf > attr_end) {
812 		ntfs_log_debug("Corrupt attribute.\n");
813 		errno = EIO;
814 		return NULL;
815 	}
816 	/* Current position in runlist array. */
817 	rlpos = 0;
818 	/* Allocate first 4kiB block and set current runlist size to 4kiB. */
819 	rlsize = 0x1000;
820 	rl = ntfs_malloc(rlsize);
821 	if (!rl)
822 		return NULL;
823 	/* Insert unmapped starting element if necessary. */
824 	if (vcn) {
825 		rl->vcn = (VCN)0;
826 		rl->lcn = (LCN)LCN_RL_NOT_MAPPED;
827 		rl->length = vcn;
828 		rlpos++;
829 	}
830 	while (buf < attr_end && *buf) {
831 		/*
832 		 * Allocate more memory if needed, including space for the
833 		 * not-mapped and terminator elements.
834 		 */
835 		if ((int)((rlpos + 3) * sizeof(*old_rl)) > rlsize) {
836 			runlist_element *rl2;
837 
838 			rlsize += 0x1000;
839 			rl2 = realloc(rl, rlsize);
840 			if (!rl2) {
841 				int eo = errno;
842 				free(rl);
843 				errno = eo;
844 				return NULL;
845 			}
846 			rl = rl2;
847 		}
848 		/* Enter the current vcn into the current runlist element. */
849 		rl[rlpos].vcn = vcn;
850 		/*
851 		 * Get the change in vcn, i.e. the run length in clusters.
852 		 * Doing it this way ensures that we signextend negative values.
853 		 * A negative run length doesn't make any sense, but hey, I
854 		 * didn't make up the NTFS specs and Windows NT4 treats the run
855 		 * length as a signed value so that's how it is...
856 		 */
857 		b = *buf & 0xf;
858 		if (b) {
859 			if (buf + b > attr_end)
860 				goto io_error;
861 			for (deltaxcn = (s8)buf[b--]; b; b--)
862 				deltaxcn = (deltaxcn << 8) + buf[b];
863 		} else { /* The length entry is compulsory. */
864 			ntfs_log_debug("Missing length entry in mapping pairs "
865 					"array.\n");
866 			deltaxcn = (s64)-1;
867 		}
868 		/*
869 		 * Assume a negative length to indicate data corruption and
870 		 * hence clean-up and return NULL.
871 		 */
872 		if (deltaxcn < 0) {
873 			ntfs_log_debug("Invalid length in mapping pairs array.\n");
874 			goto err_out;
875 		}
876 		/*
877 		 * Enter the current run length into the current runlist
878 		 * element.
879 		 */
880 		rl[rlpos].length = deltaxcn;
881 		/* Increment the current vcn by the current run length. */
882 		vcn += deltaxcn;
883 		/*
884 		 * There might be no lcn change at all, as is the case for
885 		 * sparse clusters on NTFS 3.0+, in which case we set the lcn
886 		 * to LCN_HOLE.
887 		 */
888 		if (!(*buf & 0xf0))
889 			rl[rlpos].lcn = (LCN)LCN_HOLE;
890 		else {
891 			/* Get the lcn change which really can be negative. */
892 			u8 b2 = *buf & 0xf;
893 			b = b2 + ((*buf >> 4) & 0xf);
894 			if (buf + b > attr_end)
895 				goto io_error;
896 			for (deltaxcn = (s8)buf[b--]; b > b2; b--)
897 				deltaxcn = (deltaxcn << 8) + buf[b];
898 			/* Change the current lcn to it's new value. */
899 			lcn += deltaxcn;
900 #ifdef DEBUG
901 			/*
902 			 * On NTFS 1.2-, apparently can have lcn == -1 to
903 			 * indicate a hole. But we haven't verified ourselves
904 			 * whether it is really the lcn or the deltaxcn that is
905 			 * -1. So if either is found give us a message so we
906 			 * can investigate it further!
907 			 */
908 			if (vol->major_ver < 3) {
909 				if (deltaxcn == (LCN)-1)
910 					ntfs_log_debug("lcn delta == -1\n");
911 				if (lcn == (LCN)-1)
912 					ntfs_log_debug("lcn == -1\n");
913 			}
914 #endif
915 			/* Check lcn is not below -1. */
916 			if (lcn < (LCN)-1) {
917 				ntfs_log_debug("Invalid LCN < -1 in mapping pairs "
918 						"array.\n");
919 				goto err_out;
920 			}
921 			/* chkdsk accepts zero-sized runs only for holes */
922 			if ((lcn != (LCN)-1) && !rl[rlpos].length) {
923 				ntfs_log_debug(
924 					"Invalid zero-sized data run.\n");
925 				goto err_out;
926 			}
927 			/* Enter the current lcn into the runlist element. */
928 			rl[rlpos].lcn = lcn;
929 		}
930 		/* Get to the next runlist element, skipping zero-sized holes */
931 		if (rl[rlpos].length)
932 			rlpos++;
933 		/* Increment the buffer position to the next mapping pair. */
934 		buf += (*buf & 0xf) + ((*buf >> 4) & 0xf) + 1;
935 	}
936 	if (buf >= attr_end)
937 		goto io_error;
938 	/*
939 	 * If there is a highest_vcn specified, it must be equal to the final
940 	 * vcn in the runlist - 1, or something has gone badly wrong.
941 	 */
942 	deltaxcn = sle64_to_cpu(attr->highest_vcn);
943 	if (deltaxcn && vcn - 1 != deltaxcn) {
944 mpa_err:
945 		ntfs_log_debug("Corrupt mapping pairs array in non-resident "
946 				"attribute.\n");
947 		goto err_out;
948 	}
949 
950 	/*
951 	 * If this is the base of runlist (if 'lowest_vcn' is 0), then
952 	 * 'allocated_size' is valid, and we can use it to compute the total
953 	 * number of clusters across all extents.  If the runlist covers all
954 	 * clusters, then it fits into a single extent and we can terminate
955 	 * the runlist with LCN_NOENT.  Otherwise, we must terminate the runlist
956 	 * with LCN_RL_NOT_MAPPED and let the caller look for more extents.
957 	 */
958 	if (!attr->lowest_vcn) {
959 		VCN num_clusters;
960 
961 		num_clusters = ((sle64_to_cpu(attr->allocated_size) +
962 				vol->cluster_size - 1) >>
963 				vol->cluster_size_bits);
964 
965 		if (num_clusters > vcn) {
966 			/*
967 			 * The runlist doesn't cover all the clusters, so there
968 			 * must be more extents.
969 			 */
970 			ntfs_log_debug("More extents to follow; vcn = 0x%llx, "
971 				       "num_clusters = 0x%llx\n",
972 					(long long)vcn,
973 					(long long)num_clusters);
974 			rl[rlpos].vcn = vcn;
975 			vcn += rl[rlpos].length = num_clusters - vcn;
976 			rl[rlpos].lcn = (LCN)LCN_RL_NOT_MAPPED;
977 			rlpos++;
978 		} else if (vcn > num_clusters) {
979 			/*
980 			 * There are more VCNs in the runlist than expected, so
981 			 * the runlist is corrupt.
982 			 */
983 			ntfs_log_error("Corrupt attribute. vcn = 0x%llx, "
984 				       "num_clusters = 0x%llx\n",
985 					(long long)vcn,
986 					(long long)num_clusters);
987 			goto mpa_err;
988 		}
989 		rl[rlpos].lcn = (LCN)LCN_ENOENT;
990 	} else /* Not the base extent. There may be more extents to follow. */
991 		rl[rlpos].lcn = (LCN)LCN_RL_NOT_MAPPED;
992 
993 	/* Setup terminating runlist element. */
994 	rl[rlpos].vcn = vcn;
995 	rl[rlpos].length = (s64)0;
996 	/* If no existing runlist was specified, we are done. */
997 	if (!old_rl || !old_rl[0].length) {
998 		ntfs_log_debug("Mapping pairs array successfully decompressed:\n");
999 		ntfs_debug_runlist_dump(rl);
1000 		if (old_rl)
1001 			free(old_rl);
1002 		return rl;
1003 	}
1004 	/* Now combine the new and old runlists checking for overlaps. */
1005 	if (rl[0].length)
1006 		old_rl = ntfs_runlists_merge(old_rl, rl);
1007 	else
1008 		free(rl);
1009 	if (old_rl)
1010 		return old_rl;
1011 	err = errno;
1012 	free(rl);
1013 	ntfs_log_debug("Failed to merge runlists.\n");
1014 	errno = err;
1015 	return NULL;
1016 io_error:
1017 	ntfs_log_debug("Corrupt attribute.\n");
1018 err_out:
1019 	free(rl);
1020 	errno = EIO;
1021 	return NULL;
1022 }
1023 
ntfs_mapping_pairs_decompress(const ntfs_volume * vol,const ATTR_RECORD * attr,runlist_element * old_rl)1024 runlist_element *ntfs_mapping_pairs_decompress(const ntfs_volume *vol,
1025 		const ATTR_RECORD *attr, runlist_element *old_rl)
1026 {
1027 	runlist_element *rle;
1028 
1029 	ntfs_log_enter("Entering\n");
1030 	rle = ntfs_mapping_pairs_decompress_i(vol, attr, old_rl);
1031 	ntfs_log_leave("\n");
1032 	return rle;
1033 }
1034 
1035 /**
1036  * ntfs_rl_vcn_to_lcn - convert a vcn into a lcn given a runlist
1037  * @rl:		runlist to use for conversion
1038  * @vcn:	vcn to convert
1039  *
1040  * Convert the virtual cluster number @vcn of an attribute into a logical
1041  * cluster number (lcn) of a device using the runlist @rl to map vcns to their
1042  * corresponding lcns.
1043  *
1044  * Since lcns must be >= 0, we use negative return values with special meaning:
1045  *
1046  * Return value			Meaning / Description
1047  * ==================================================
1048  *  -1 = LCN_HOLE		Hole / not allocated on disk.
1049  *  -2 = LCN_RL_NOT_MAPPED	This is part of the runlist which has not been
1050  *				inserted into the runlist yet.
1051  *  -3 = LCN_ENOENT		There is no such vcn in the attribute.
1052  *  -4 = LCN_EINVAL		Input parameter error.
1053  */
ntfs_rl_vcn_to_lcn(const runlist_element * rl,const VCN vcn)1054 LCN ntfs_rl_vcn_to_lcn(const runlist_element *rl, const VCN vcn)
1055 {
1056 	int i;
1057 
1058 	if (vcn < (VCN)0)
1059 		return (LCN)LCN_EINVAL;
1060 	/*
1061 	 * If rl is NULL, assume that we have found an unmapped runlist. The
1062 	 * caller can then attempt to map it and fail appropriately if
1063 	 * necessary.
1064 	 */
1065 	if (!rl)
1066 		return (LCN)LCN_RL_NOT_MAPPED;
1067 
1068 	/* Catch out of lower bounds vcn. */
1069 	if (vcn < rl[0].vcn)
1070 		return (LCN)LCN_ENOENT;
1071 
1072 	for (i = 0; rl[i].length; i++) {
1073 		if (vcn < rl[i+1].vcn) {
1074 			if (rl[i].lcn >= (LCN)0)
1075 				return rl[i].lcn + (vcn - rl[i].vcn);
1076 			return rl[i].lcn;
1077 		}
1078 	}
1079 	/*
1080 	 * The terminator element is setup to the correct value, i.e. one of
1081 	 * LCN_HOLE, LCN_RL_NOT_MAPPED, or LCN_ENOENT.
1082 	 */
1083 	if (rl[i].lcn < (LCN)0)
1084 		return rl[i].lcn;
1085 	/* Just in case... We could replace this with BUG() some day. */
1086 	return (LCN)LCN_ENOENT;
1087 }
1088 
1089 /**
1090  * ntfs_rl_pread - gather read from disk
1091  * @vol:	ntfs volume to read from
1092  * @rl:		runlist specifying where to read the data from
1093  * @pos:	byte position within runlist @rl at which to begin the read
1094  * @count:	number of bytes to read
1095  * @b:		data buffer into which to read from disk
1096  *
1097  * This function will read @count bytes from the volume @vol to the data buffer
1098  * @b gathering the data as specified by the runlist @rl. The read begins at
1099  * offset @pos into the runlist @rl.
1100  *
1101  * On success, return the number of successfully read bytes. If this number is
1102  * lower than @count this means that the read reached end of file or that an
1103  * error was encountered during the read so that the read is partial. 0 means
1104  * nothing was read (also return 0 when @count is 0).
1105  *
1106  * On error and nothing has been read, return -1 with errno set appropriately
1107  * to the return code of ntfs_pread(), or to EINVAL in case of invalid
1108  * arguments.
1109  *
1110  * NOTE: If we encounter EOF while reading we return EIO because we assume that
1111  * the run list must point to valid locations within the ntfs volume.
1112  */
ntfs_rl_pread(const ntfs_volume * vol,const runlist_element * rl,const s64 pos,s64 count,void * b)1113 s64 ntfs_rl_pread(const ntfs_volume *vol, const runlist_element *rl,
1114 		const s64 pos, s64 count, void *b)
1115 {
1116 	s64 bytes_read, to_read, ofs, total;
1117 	int err = EIO;
1118 
1119 	if (!vol || !rl || pos < 0 || count < 0) {
1120 		errno = EINVAL;
1121 		ntfs_log_perror("Failed to read runlist [vol: %p rl: %p "
1122 				"pos: %lld count: %lld]", vol, rl,
1123 				(long long)pos, (long long)count);
1124 		return -1;
1125 	}
1126 	if (!count)
1127 		return count;
1128 	/* Seek in @rl to the run containing @pos. */
1129 	for (ofs = 0; rl->length && (ofs + (rl->length <<
1130 			vol->cluster_size_bits) <= pos); rl++)
1131 		ofs += (rl->length << vol->cluster_size_bits);
1132 	/* Offset in the run at which to begin reading. */
1133 	ofs = pos - ofs;
1134 	for (total = 0LL; count; rl++, ofs = 0) {
1135 		if (!rl->length)
1136 			goto rl_err_out;
1137 		if (rl->lcn < (LCN)0) {
1138 			if (rl->lcn != (LCN)LCN_HOLE)
1139 				goto rl_err_out;
1140 			/* It is a hole. Just fill buffer @b with zeroes. */
1141 			to_read = min(count, (rl->length <<
1142 					vol->cluster_size_bits) - ofs);
1143 			memset(b, 0, to_read);
1144 			/* Update counters and proceed with next run. */
1145 			total += to_read;
1146 			count -= to_read;
1147 			b = (u8*)b + to_read;
1148 			continue;
1149 		}
1150 		/* It is a real lcn, read it from the volume. */
1151 		to_read = min(count, (rl->length << vol->cluster_size_bits) -
1152 				ofs);
1153 retry:
1154 		bytes_read = ntfs_pread(vol->dev, (rl->lcn <<
1155 				vol->cluster_size_bits) + ofs, to_read, b);
1156 		/* If everything ok, update progress counters and continue. */
1157 		if (bytes_read > 0) {
1158 			total += bytes_read;
1159 			count -= bytes_read;
1160 			b = (u8*)b + bytes_read;
1161 			continue;
1162 		}
1163 		/* If the syscall was interrupted, try again. */
1164 		if (bytes_read == (s64)-1 && errno == EINTR)
1165 			goto retry;
1166 		if (bytes_read == (s64)-1)
1167 			err = errno;
1168 		goto rl_err_out;
1169 	}
1170 	/* Finally, return the number of bytes read. */
1171 	return total;
1172 rl_err_out:
1173 	if (total)
1174 		return total;
1175 	errno = err;
1176 	return -1;
1177 }
1178 
1179 /**
1180  * ntfs_rl_pwrite - scatter write to disk
1181  * @vol:	ntfs volume to write to
1182  * @rl:		runlist entry specifying where to write the data to
1183  * @ofs:	offset in file for runlist element indicated in @rl
1184  * @pos:	byte position from runlist beginning at which to begin the write
1185  * @count:	number of bytes to write
1186  * @b:		data buffer to write to disk
1187  *
1188  * This function will write @count bytes from data buffer @b to the volume @vol
1189  * scattering the data as specified by the runlist @rl. The write begins at
1190  * offset @pos into the runlist @rl. If a run is sparse then the related buffer
1191  * data is ignored which means that the caller must ensure they are consistent.
1192  *
1193  * On success, return the number of successfully written bytes. If this number
1194  * is lower than @count this means that the write has been interrupted in
1195  * flight or that an error was encountered during the write so that the write
1196  * is partial. 0 means nothing was written (also return 0 when @count is 0).
1197  *
1198  * On error and nothing has been written, return -1 with errno set
1199  * appropriately to the return code of ntfs_pwrite(), or to to EINVAL in case
1200  * of invalid arguments.
1201  */
ntfs_rl_pwrite(const ntfs_volume * vol,const runlist_element * rl,s64 ofs,const s64 pos,s64 count,void * b)1202 s64 ntfs_rl_pwrite(const ntfs_volume *vol, const runlist_element *rl,
1203 		s64 ofs, const s64 pos, s64 count, void *b)
1204 {
1205 	s64 written, to_write, total = 0;
1206 	int err = EIO;
1207 
1208 	if (!vol || !rl || pos < 0 || count < 0) {
1209 		errno = EINVAL;
1210 		ntfs_log_perror("Failed to write runlist [vol: %p rl: %p "
1211 				"pos: %lld count: %lld]", vol, rl,
1212 				(long long)pos, (long long)count);
1213 		goto errno_set;
1214 	}
1215 	if (!count)
1216 		goto out;
1217 	/* Seek in @rl to the run containing @pos. */
1218 	while (rl->length && (ofs + (rl->length <<
1219 			vol->cluster_size_bits) <= pos)) {
1220 		ofs += (rl->length << vol->cluster_size_bits);
1221 		rl++;
1222 	}
1223 	/* Offset in the run at which to begin writing. */
1224 	ofs = pos - ofs;
1225 	for (total = 0LL; count; rl++, ofs = 0) {
1226 		if (!rl->length)
1227 			goto rl_err_out;
1228 		if (rl->lcn < (LCN)0) {
1229 
1230 			if (rl->lcn != (LCN)LCN_HOLE)
1231 				goto rl_err_out;
1232 
1233 			to_write = min(count, (rl->length <<
1234 					       vol->cluster_size_bits) - ofs);
1235 
1236 			total += to_write;
1237 			count -= to_write;
1238 			b = (u8*)b + to_write;
1239 			continue;
1240 		}
1241 		/* It is a real lcn, write it to the volume. */
1242 		to_write = min(count, (rl->length << vol->cluster_size_bits) -
1243 				ofs);
1244 retry:
1245 		if (!NVolReadOnly(vol))
1246 			written = ntfs_pwrite(vol->dev, (rl->lcn <<
1247 					vol->cluster_size_bits) + ofs,
1248 					to_write, b);
1249 		else
1250 			written = to_write;
1251 		/* If everything ok, update progress counters and continue. */
1252 		if (written > 0) {
1253 			total += written;
1254 			count -= written;
1255 			b = (u8*)b + written;
1256 			continue;
1257 		}
1258 		/* If the syscall was interrupted, try again. */
1259 		if (written == (s64)-1 && errno == EINTR)
1260 			goto retry;
1261 		if (written == (s64)-1)
1262 			err = errno;
1263 		goto rl_err_out;
1264 	}
1265 out:
1266 	return total;
1267 rl_err_out:
1268 	if (total)
1269 		goto out;
1270 	errno = err;
1271 errno_set:
1272 	total = -1;
1273 	goto out;
1274 }
1275 
1276 /**
1277  * ntfs_get_nr_significant_bytes - get number of bytes needed to store a number
1278  * @n:		number for which to get the number of bytes for
1279  *
1280  * Return the number of bytes required to store @n unambiguously as
1281  * a signed number.
1282  *
1283  * This is used in the context of the mapping pairs array to determine how
1284  * many bytes will be needed in the array to store a given logical cluster
1285  * number (lcn) or a specific run length.
1286  *
1287  * Return the number of bytes written. This function cannot fail.
1288  */
ntfs_get_nr_significant_bytes(const s64 n)1289 int ntfs_get_nr_significant_bytes(const s64 n)
1290 {
1291 	u64 l;
1292 	int i;
1293 
1294 	l = (n < 0 ? ~n : n);
1295 	i = 1;
1296 	if (l >= 128) {
1297 		l >>= 7;
1298 		do {
1299 			i++;
1300 			l >>= 8;
1301 		} while (l);
1302 	}
1303 	return i;
1304 }
1305 
1306 /**
1307  * ntfs_get_size_for_mapping_pairs - get bytes needed for mapping pairs array
1308  * @vol:	ntfs volume (needed for the ntfs version)
1309  * @rl:		runlist for which to determine the size of the mapping pairs
1310  * @start_vcn:	vcn at which to start the mapping pairs array
1311  *
1312  * Walk the runlist @rl and calculate the size in bytes of the mapping pairs
1313  * array corresponding to the runlist @rl, starting at vcn @start_vcn.  This
1314  * for example allows us to allocate a buffer of the right size when building
1315  * the mapping pairs array.
1316  *
1317  * If @rl is NULL, just return 1 (for the single terminator byte).
1318  *
1319  * Return the calculated size in bytes on success.  On error, return -1 with
1320  * errno set to the error code.  The following error codes are defined:
1321  *	EINVAL	- Run list contains unmapped elements. Make sure to only pass
1322  *		  fully mapped runlists to this function.
1323  *		- @start_vcn is invalid.
1324  *	EIO	- The runlist is corrupt.
1325  */
ntfs_get_size_for_mapping_pairs(const ntfs_volume * vol,const runlist_element * rl,const VCN start_vcn,int max_size)1326 int ntfs_get_size_for_mapping_pairs(const ntfs_volume *vol,
1327 		const runlist_element *rl, const VCN start_vcn, int max_size)
1328 {
1329 	LCN prev_lcn;
1330 	int rls;
1331 
1332 	if (start_vcn < 0) {
1333 		ntfs_log_trace("start_vcn %lld (should be >= 0)\n",
1334 				(long long) start_vcn);
1335 		errno = EINVAL;
1336 		goto errno_set;
1337 	}
1338 	if (!rl) {
1339 		if (start_vcn) {
1340 			ntfs_log_trace("rl NULL, start_vcn %lld (should be > 0)\n",
1341 					(long long) start_vcn);
1342 			errno = EINVAL;
1343 			goto errno_set;
1344 		}
1345 		rls = 1;
1346 		goto out;
1347 	}
1348 	/* Skip to runlist element containing @start_vcn. */
1349 	while (rl->length && start_vcn >= rl[1].vcn)
1350 		rl++;
1351 	if ((!rl->length && start_vcn > rl->vcn) || start_vcn < rl->vcn) {
1352 		errno = EINVAL;
1353 		goto errno_set;
1354 	}
1355 	prev_lcn = 0;
1356 	/* Always need the terminating zero byte. */
1357 	rls = 1;
1358 	/* Do the first partial run if present. */
1359 	if (start_vcn > rl->vcn) {
1360 		s64 delta;
1361 
1362 		/* We know rl->length != 0 already. */
1363 		if (rl->length < 0 || rl->lcn < LCN_HOLE)
1364 			goto err_out;
1365 		delta = start_vcn - rl->vcn;
1366 		/* Header byte + length. */
1367 		rls += 1 + ntfs_get_nr_significant_bytes(rl->length - delta);
1368 		/*
1369 		 * If the logical cluster number (lcn) denotes a hole and we
1370 		 * are on NTFS 3.0+, we don't store it at all, i.e. we need
1371 		 * zero space. On earlier NTFS versions we just store the lcn.
1372 		 * Note: this assumes that on NTFS 1.2-, holes are stored with
1373 		 * an lcn of -1 and not a delta_lcn of -1 (unless both are -1).
1374 		 */
1375 		if (rl->lcn >= 0 || vol->major_ver < 3) {
1376 			prev_lcn = rl->lcn;
1377 			if (rl->lcn >= 0)
1378 				prev_lcn += delta;
1379 			/* Change in lcn. */
1380 			rls += ntfs_get_nr_significant_bytes(prev_lcn);
1381 		}
1382 		/* Go to next runlist element. */
1383 		rl++;
1384 	}
1385 	/* Do the full runs. */
1386 	for (; rl->length && (rls <= max_size); rl++) {
1387 		if (rl->length < 0 || rl->lcn < LCN_HOLE)
1388 			goto err_out;
1389 		/* Header byte + length. */
1390 		rls += 1 + ntfs_get_nr_significant_bytes(rl->length);
1391 		/*
1392 		 * If the logical cluster number (lcn) denotes a hole and we
1393 		 * are on NTFS 3.0+, we don't store it at all, i.e. we need
1394 		 * zero space. On earlier NTFS versions we just store the lcn.
1395 		 * Note: this assumes that on NTFS 1.2-, holes are stored with
1396 		 * an lcn of -1 and not a delta_lcn of -1 (unless both are -1).
1397 		 */
1398 		if (rl->lcn >= 0 || vol->major_ver < 3) {
1399 			/* Change in lcn. */
1400 			rls += ntfs_get_nr_significant_bytes(rl->lcn -
1401 					prev_lcn);
1402 			prev_lcn = rl->lcn;
1403 		}
1404 	}
1405 out:
1406 	return rls;
1407 err_out:
1408 	if (rl->lcn == LCN_RL_NOT_MAPPED)
1409 		errno = EINVAL;
1410 	else
1411 		errno = EIO;
1412 errno_set:
1413 	rls = -1;
1414 	goto out;
1415 }
1416 
1417 /**
1418  * ntfs_write_significant_bytes - write the significant bytes of a number
1419  * @dst:	destination buffer to write to
1420  * @dst_max:	pointer to last byte of destination buffer for bounds checking
1421  * @n:		number whose significant bytes to write
1422  *
1423  * Store in @dst, the minimum bytes of the number @n which are required to
1424  * identify @n unambiguously as a signed number, taking care not to exceed
1425  * @dest_max, the maximum position within @dst to which we are allowed to
1426  * write.
1427  *
1428  * This is used when building the mapping pairs array of a runlist to compress
1429  * a given logical cluster number (lcn) or a specific run length to the minimum
1430  * size possible.
1431  *
1432  * Return the number of bytes written on success. On error, i.e. the
1433  * destination buffer @dst is too small, return -1 with errno set ENOSPC.
1434  */
ntfs_write_significant_bytes(u8 * dst,const u8 * dst_max,const s64 n)1435 int ntfs_write_significant_bytes(u8 *dst, const u8 *dst_max, const s64 n)
1436 {
1437 	s64 l = n;
1438 	int i;
1439 
1440 	i = 0;
1441 	if (dst > dst_max)
1442 		goto err_out;
1443 	*dst++ = l;
1444 	i++;
1445 	while ((l > 0x7f) || (l < -0x80)) {
1446 		if (dst > dst_max)
1447 			goto err_out;
1448 		l >>= 8;
1449 		*dst++ = l;
1450 		i++;
1451 	}
1452 	return i;
1453 err_out:
1454 	errno = ENOSPC;
1455 	return -1;
1456 }
1457 
1458 /**
1459  * ntfs_mapping_pairs_build - build the mapping pairs array from a runlist
1460  * @vol:	ntfs volume (needed for the ntfs version)
1461  * @dst:	destination buffer to which to write the mapping pairs array
1462  * @dst_len:	size of destination buffer @dst in bytes
1463  * @rl:		runlist for which to build the mapping pairs array
1464  * @start_vcn:	vcn at which to start the mapping pairs array
1465  * @stop_vcn:	first vcn outside destination buffer on success or ENOSPC error
1466  *
1467  * Create the mapping pairs array from the runlist @rl, starting at vcn
1468  * @start_vcn and save the array in @dst.  @dst_len is the size of @dst in
1469  * bytes and it should be at least equal to the value obtained by calling
1470  * ntfs_get_size_for_mapping_pairs().
1471  *
1472  * If @rl is NULL, just write a single terminator byte to @dst.
1473  *
1474  * On success or ENOSPC error, if @stop_vcn is not NULL, *@stop_vcn is set to
1475  * the first vcn outside the destination buffer. Note that on error @dst has
1476  * been filled with all the mapping pairs that will fit, thus it can be treated
1477  * as partial success, in that a new attribute extent needs to be created or the
1478  * next extent has to be used and the mapping pairs build has to be continued
1479  * with @start_vcn set to *@stop_vcn.
1480  *
1481  * Return 0 on success.  On error, return -1 with errno set to the error code.
1482  * The following error codes are defined:
1483  *	EINVAL	- Run list contains unmapped elements. Make sure to only pass
1484  *		  fully mapped runlists to this function.
1485  *		- @start_vcn is invalid.
1486  *	EIO	- The runlist is corrupt.
1487  *	ENOSPC	- The destination buffer is too small.
1488  */
ntfs_mapping_pairs_build(const ntfs_volume * vol,u8 * dst,const int dst_len,const runlist_element * rl,const VCN start_vcn,runlist_element const ** stop_rl)1489 int ntfs_mapping_pairs_build(const ntfs_volume *vol, u8 *dst,
1490 		const int dst_len, const runlist_element *rl,
1491 		const VCN start_vcn, runlist_element const **stop_rl)
1492 {
1493 	LCN prev_lcn;
1494 	u8 *dst_max, *dst_next;
1495 	s8 len_len, lcn_len;
1496 	int ret = 0;
1497 
1498 	if (start_vcn < 0)
1499 		goto val_err;
1500 	if (!rl) {
1501 		if (start_vcn)
1502 			goto val_err;
1503 		if (stop_rl)
1504 			*stop_rl = rl;
1505 		if (dst_len < 1)
1506 			goto nospc_err;
1507 		goto ok;
1508 	}
1509 	/* Skip to runlist element containing @start_vcn. */
1510 	while (rl->length && start_vcn >= rl[1].vcn)
1511 		rl++;
1512 	if ((!rl->length && start_vcn > rl->vcn) || start_vcn < rl->vcn)
1513 		goto val_err;
1514 	/*
1515 	 * @dst_max is used for bounds checking in
1516 	 * ntfs_write_significant_bytes().
1517 	 */
1518 	dst_max = dst + dst_len - 1;
1519 	prev_lcn = 0;
1520 	/* Do the first partial run if present. */
1521 	if (start_vcn > rl->vcn) {
1522 		s64 delta;
1523 
1524 		/* We know rl->length != 0 already. */
1525 		if (rl->length < 0 || rl->lcn < LCN_HOLE)
1526 			goto err_out;
1527 		delta = start_vcn - rl->vcn;
1528 		/* Write length. */
1529 		len_len = ntfs_write_significant_bytes(dst + 1, dst_max,
1530 				rl->length - delta);
1531 		if (len_len < 0)
1532 			goto size_err;
1533 		/*
1534 		 * If the logical cluster number (lcn) denotes a hole and we
1535 		 * are on NTFS 3.0+, we don't store it at all, i.e. we need
1536 		 * zero space. On earlier NTFS versions we just write the lcn
1537 		 * change.  FIXME: Do we need to write the lcn change or just
1538 		 * the lcn in that case?  Not sure as I have never seen this
1539 		 * case on NT4. - We assume that we just need to write the lcn
1540 		 * change until someone tells us otherwise... (AIA)
1541 		 */
1542 		if (rl->lcn >= 0 || vol->major_ver < 3) {
1543 			prev_lcn = rl->lcn;
1544 			if (rl->lcn >= 0)
1545 				prev_lcn += delta;
1546 			/* Write change in lcn. */
1547 			lcn_len = ntfs_write_significant_bytes(dst + 1 +
1548 					len_len, dst_max, prev_lcn);
1549 			if (lcn_len < 0)
1550 				goto size_err;
1551 		} else
1552 			lcn_len = 0;
1553 		dst_next = dst + len_len + lcn_len + 1;
1554 		if (dst_next > dst_max)
1555 			goto size_err;
1556 		/* Update header byte. */
1557 		*dst = lcn_len << 4 | len_len;
1558 		/* Position at next mapping pairs array element. */
1559 		dst = dst_next;
1560 		/* Go to next runlist element. */
1561 		rl++;
1562 	}
1563 	/* Do the full runs. */
1564 	for (; rl->length; rl++) {
1565 		if (rl->length < 0 || rl->lcn < LCN_HOLE)
1566 			goto err_out;
1567 		/* Write length. */
1568 		len_len = ntfs_write_significant_bytes(dst + 1, dst_max,
1569 				rl->length);
1570 		if (len_len < 0)
1571 			goto size_err;
1572 		/*
1573 		 * If the logical cluster number (lcn) denotes a hole and we
1574 		 * are on NTFS 3.0+, we don't store it at all, i.e. we need
1575 		 * zero space. On earlier NTFS versions we just write the lcn
1576 		 * change. FIXME: Do we need to write the lcn change or just
1577 		 * the lcn in that case? Not sure as I have never seen this
1578 		 * case on NT4. - We assume that we just need to write the lcn
1579 		 * change until someone tells us otherwise... (AIA)
1580 		 */
1581 		if (rl->lcn >= 0 || vol->major_ver < 3) {
1582 			/* Write change in lcn. */
1583 			lcn_len = ntfs_write_significant_bytes(dst + 1 +
1584 					len_len, dst_max, rl->lcn - prev_lcn);
1585 			if (lcn_len < 0)
1586 				goto size_err;
1587 			prev_lcn = rl->lcn;
1588 		} else
1589 			lcn_len = 0;
1590 		dst_next = dst + len_len + lcn_len + 1;
1591 		if (dst_next > dst_max)
1592 			goto size_err;
1593 		/* Update header byte. */
1594 		*dst = lcn_len << 4 | len_len;
1595 		/* Position at next mapping pairs array element. */
1596 		dst += 1 + len_len + lcn_len;
1597 	}
1598 	/* Set stop vcn. */
1599 	if (stop_rl)
1600 		*stop_rl = rl;
1601 ok:
1602 	/* Add terminator byte. */
1603 	*dst = 0;
1604 out:
1605 	return ret;
1606 size_err:
1607 	/* Set stop vcn. */
1608 	if (stop_rl)
1609 		*stop_rl = rl;
1610 	/* Add terminator byte. */
1611 	*dst = 0;
1612 nospc_err:
1613 	errno = ENOSPC;
1614 	goto errno_set;
1615 val_err:
1616 	errno = EINVAL;
1617 	goto errno_set;
1618 err_out:
1619 	if (rl->lcn == LCN_RL_NOT_MAPPED)
1620 		errno = EINVAL;
1621 	else
1622 		errno = EIO;
1623 errno_set:
1624 	ret = -1;
1625 	goto out;
1626 }
1627 
1628 /**
1629  * ntfs_rl_truncate - truncate a runlist starting at a specified vcn
1630  * @arl:	address of runlist to truncate
1631  * @start_vcn:	first vcn which should be cut off
1632  *
1633  * Truncate the runlist *@arl starting at vcn @start_vcn as well as the memory
1634  * buffer holding the runlist.
1635  *
1636  * Return 0 on success and -1 on error with errno set to the error code.
1637  *
1638  * NOTE: @arl is the address of the runlist. We need the address so we can
1639  * modify the pointer to the runlist with the new, reallocated memory buffer.
1640  */
ntfs_rl_truncate(runlist ** arl,const VCN start_vcn)1641 int ntfs_rl_truncate(runlist **arl, const VCN start_vcn)
1642 {
1643 	runlist *rl;
1644 	/* BOOL is_end = FALSE; */
1645 
1646 	if (!arl || !*arl) {
1647 		errno = EINVAL;
1648 		if (!arl)
1649 			ntfs_log_perror("rl_truncate error: arl: %p", arl);
1650 		else
1651 			ntfs_log_perror("rl_truncate error:"
1652 				" arl: %p *arl: %p", arl, *arl);
1653 		return -1;
1654 	}
1655 
1656 	rl = *arl;
1657 
1658 	if (start_vcn < rl->vcn) {
1659 		errno = EINVAL;
1660 		ntfs_log_perror("Start_vcn lies outside front of runlist");
1661 		return -1;
1662 	}
1663 
1664 	/* Find the starting vcn in the run list. */
1665 	while (rl->length) {
1666 		if (start_vcn < rl[1].vcn)
1667 			break;
1668 		rl++;
1669 	}
1670 
1671 	if (!rl->length) {
1672 		errno = EIO;
1673 		ntfs_log_trace("Truncating already truncated runlist?\n");
1674 		return -1;
1675 	}
1676 
1677 	/* Truncate the run. */
1678 	rl->length = start_vcn - rl->vcn;
1679 
1680 	/*
1681 	 * If a run was partially truncated, make the following runlist
1682 	 * element a terminator instead of the truncated runlist
1683 	 * element itself.
1684 	 */
1685 	if (rl->length) {
1686 		++rl;
1687 /*
1688 		if (!rl->length)
1689 			is_end = TRUE;
1690 */
1691 		rl->vcn = start_vcn;
1692 		rl->length = 0;
1693 	}
1694 	rl->lcn = (LCN)LCN_ENOENT;
1695 	/**
1696 	 * Reallocate memory if necessary.
1697 	 * FIXME: Below code is broken, because runlist allocations must be
1698 	 * a multiple of 4096. The code caused crashes and corruptions.
1699 	 */
1700 /*
1701 	 if (!is_end) {
1702 		size_t new_size = (rl - *arl + 1) * sizeof(runlist_element);
1703 		rl = realloc(*arl, new_size);
1704 		if (rl)
1705 			*arl = rl;
1706 	}
1707 */
1708 	return 0;
1709 }
1710 
1711 /**
1712  * ntfs_rl_sparse - check whether runlist have sparse regions or not.
1713  * @rl:		runlist to check
1714  *
1715  * Return 1 if have, 0 if not, -1 on error with errno set to the error code.
1716  */
ntfs_rl_sparse(runlist * rl)1717 int ntfs_rl_sparse(runlist *rl)
1718 {
1719 	runlist *rlc;
1720 
1721 	if (!rl) {
1722 		errno = EINVAL;
1723 		ntfs_log_perror("%s: ", __FUNCTION__);
1724 		return -1;
1725 	}
1726 
1727 	for (rlc = rl; rlc->length; rlc++)
1728 		if (rlc->lcn < 0) {
1729 			if (rlc->lcn != LCN_HOLE) {
1730 				errno = EINVAL;
1731 				ntfs_log_perror("%s: bad runlist", __FUNCTION__);
1732 				return -1;
1733 			}
1734 			return 1;
1735 		}
1736 	return 0;
1737 }
1738 
1739 /**
1740  * ntfs_rl_get_compressed_size - calculate length of non sparse regions
1741  * @vol:	ntfs volume (need for cluster size)
1742  * @rl:		runlist to calculate for
1743  *
1744  * Return compressed size or -1 on error with errno set to the error code.
1745  */
ntfs_rl_get_compressed_size(ntfs_volume * vol,runlist * rl)1746 s64 ntfs_rl_get_compressed_size(ntfs_volume *vol, runlist *rl)
1747 {
1748 	runlist *rlc;
1749 	s64 ret = 0;
1750 
1751 	if (!rl) {
1752 		errno = EINVAL;
1753 		ntfs_log_perror("%s: ", __FUNCTION__);
1754 		return -1;
1755 	}
1756 
1757 	for (rlc = rl; rlc->length; rlc++) {
1758 		if (rlc->lcn < 0) {
1759 			if (rlc->lcn != LCN_HOLE) {
1760 				errno = EINVAL;
1761 				ntfs_log_perror("%s: bad runlist", __FUNCTION__);
1762 				return -1;
1763 			}
1764 		} else
1765 			ret += rlc->length;
1766 	}
1767 	return ret << vol->cluster_size_bits;
1768 }
1769 
1770 
1771 #ifdef NTFS_TEST
1772 /**
1773  * test_rl_helper
1774  */
1775 #define MKRL(R,V,L,S)				\
1776 	(R)->vcn = V;				\
1777 	(R)->lcn = L;				\
1778 	(R)->length = S;
1779 /*
1780 }
1781 */
1782 /**
1783  * test_rl_dump_runlist - Runlist test: Display the contents of a runlist
1784  * @rl:
1785  *
1786  * Description...
1787  *
1788  * Returns:
1789  */
test_rl_dump_runlist(const runlist_element * rl)1790 static void test_rl_dump_runlist(const runlist_element *rl)
1791 {
1792 	int abbr = 0;	/* abbreviate long lists */
1793 	int len = 0;
1794 	int i;
1795 	const char *lcn_str[5] = { "HOLE", "NOTMAP", "ENOENT", "XXXX" };
1796 
1797 	if (!rl) {
1798 		printf("    Run list not present.\n");
1799 		return;
1800 	}
1801 
1802 	if (abbr)
1803 		for (len = 0; rl[len].length; len++) ;
1804 
1805 	printf("     VCN      LCN      len\n");
1806 	for (i = 0; ; i++, rl++) {
1807 		LCN lcn = rl->lcn;
1808 
1809 		if ((abbr) && (len > 20)) {
1810 			if (i == 4)
1811 				printf("     ...\n");
1812 			if ((i > 3) && (i < (len - 3)))
1813 				continue;
1814 		}
1815 
1816 		if (lcn < (LCN)0) {
1817 			int ind = -lcn - 1;
1818 
1819 			if (ind > -LCN_ENOENT - 1)
1820 				ind = 3;
1821 			printf("%8lld %8s %8lld\n",
1822 				rl->vcn, lcn_str[ind], rl->length);
1823 		} else
1824 			printf("%8lld %8lld %8lld\n",
1825 				rl->vcn, rl->lcn, rl->length);
1826 		if (!rl->length)
1827 			break;
1828 	}
1829 	if ((abbr) && (len > 20))
1830 		printf("    (%d entries)\n", len+1);
1831 	printf("\n");
1832 }
1833 
1834 /**
1835  * test_rl_runlists_merge - Runlist test: Merge two runlists
1836  * @drl:
1837  * @srl:
1838  *
1839  * Description...
1840  *
1841  * Returns:
1842  */
test_rl_runlists_merge(runlist_element * drl,runlist_element * srl)1843 static runlist_element * test_rl_runlists_merge(runlist_element *drl, runlist_element *srl)
1844 {
1845 	runlist_element *res = NULL;
1846 
1847 	printf("dst:\n");
1848 	test_rl_dump_runlist(drl);
1849 	printf("src:\n");
1850 	test_rl_dump_runlist(srl);
1851 
1852 	res = ntfs_runlists_merge(drl, srl);
1853 
1854 	printf("res:\n");
1855 	test_rl_dump_runlist(res);
1856 
1857 	return res;
1858 }
1859 
1860 /**
1861  * test_rl_read_buffer - Runlist test: Read a file containing a runlist
1862  * @file:
1863  * @buf:
1864  * @bufsize:
1865  *
1866  * Description...
1867  *
1868  * Returns:
1869  */
test_rl_read_buffer(const char * file,u8 * buf,int bufsize)1870 static int test_rl_read_buffer(const char *file, u8 *buf, int bufsize)
1871 {
1872 	FILE *fptr;
1873 
1874 	fptr = fopen(file, "r");
1875 	if (!fptr) {
1876 		printf("open %s\n", file);
1877 		return 0;
1878 	}
1879 
1880 	if (fread(buf, bufsize, 1, fptr) == 99) {
1881 		printf("read %s\n", file);
1882 		return 0;
1883 	}
1884 
1885 	fclose(fptr);
1886 	return 1;
1887 }
1888 
1889 /**
1890  * test_rl_pure_src - Runlist test: Complicate the simple tests a little
1891  * @contig:
1892  * @multi:
1893  * @vcn:
1894  * @len:
1895  *
1896  * Description...
1897  *
1898  * Returns:
1899  */
test_rl_pure_src(BOOL contig,BOOL multi,int vcn,int len)1900 static runlist_element * test_rl_pure_src(BOOL contig, BOOL multi, int vcn, int len)
1901 {
1902 	runlist_element *result;
1903 	int fudge;
1904 
1905 	if (contig)
1906 		fudge = 0;
1907 	else
1908 		fudge = 999;
1909 
1910 	result = ntfs_malloc(4096);
1911 	if (!result)
1912 		return NULL;
1913 
1914 	if (multi) {
1915 		MKRL(result+0, vcn + (0*len/4), fudge + vcn + 1000 + (0*len/4), len / 4)
1916 		MKRL(result+1, vcn + (1*len/4), fudge + vcn + 1000 + (1*len/4), len / 4)
1917 		MKRL(result+2, vcn + (2*len/4), fudge + vcn + 1000 + (2*len/4), len / 4)
1918 		MKRL(result+3, vcn + (3*len/4), fudge + vcn + 1000 + (3*len/4), len / 4)
1919 		MKRL(result+4, vcn + (4*len/4), LCN_RL_NOT_MAPPED,              0)
1920 	} else {
1921 		MKRL(result+0, vcn,       fudge + vcn + 1000, len)
1922 		MKRL(result+1, vcn + len, LCN_RL_NOT_MAPPED,  0)
1923 	}
1924 	return result;
1925 }
1926 
1927 /**
1928  * test_rl_pure_test - Runlist test: Perform tests using simple runlists
1929  * @test:
1930  * @contig:
1931  * @multi:
1932  * @vcn:
1933  * @len:
1934  * @file:
1935  * @size:
1936  *
1937  * Description...
1938  *
1939  * Returns:
1940  */
test_rl_pure_test(int test,BOOL contig,BOOL multi,int vcn,int len,runlist_element * file,int size)1941 static void test_rl_pure_test(int test, BOOL contig, BOOL multi, int vcn, int len, runlist_element *file, int size)
1942 {
1943 	runlist_element *src;
1944 	runlist_element *dst;
1945 	runlist_element *res;
1946 
1947 	src = test_rl_pure_src(contig, multi, vcn, len);
1948 	dst = ntfs_malloc(4096);
1949 	if (!src || !dst) {
1950 		printf("Test %2d ---------- FAILED! (no free memory?)\n", test);
1951 		return;
1952 	}
1953 
1954 	memcpy(dst, file, size);
1955 
1956 	printf("Test %2d ----------\n", test);
1957 	res = test_rl_runlists_merge(dst, src);
1958 
1959 	free(res);
1960 }
1961 
1962 /**
1963  * test_rl_pure - Runlist test: Create tests using simple runlists
1964  * @contig:
1965  * @multi:
1966  *
1967  * Description...
1968  *
1969  * Returns:
1970  */
test_rl_pure(char * contig,char * multi)1971 static void test_rl_pure(char *contig, char *multi)
1972 {
1973 		/* VCN,  LCN, len */
1974 	static runlist_element file1[] = {
1975 		{    0,   -1, 100 },	/* HOLE */
1976 		{  100, 1100, 100 },	/* DATA */
1977 		{  200,   -1, 100 },	/* HOLE */
1978 		{  300, 1300, 100 },	/* DATA */
1979 		{  400,   -1, 100 },	/* HOLE */
1980 		{  500,   -3,   0 }	/* NOENT */
1981 	};
1982 	static runlist_element file2[] = {
1983 		{    0, 1000, 100 },	/* DATA */
1984 		{  100,   -1, 100 },	/* HOLE */
1985 		{  200,   -3,   0 }	/* NOENT */
1986 	};
1987 	static runlist_element file3[] = {
1988 		{    0, 1000, 100 },	/* DATA */
1989 		{  100,   -3,   0 }	/* NOENT */
1990 	};
1991 	static runlist_element file4[] = {
1992 		{    0,   -3,   0 }	/* NOENT */
1993 	};
1994 	static runlist_element file5[] = {
1995 		{    0,   -2, 100 },	/* NOTMAP */
1996 		{  100, 1100, 100 },	/* DATA */
1997 		{  200,   -2, 100 },	/* NOTMAP */
1998 		{  300, 1300, 100 },	/* DATA */
1999 		{  400,   -2, 100 },	/* NOTMAP */
2000 		{  500,   -3,   0 }	/* NOENT */
2001 	};
2002 	static runlist_element file6[] = {
2003 		{    0, 1000, 100 },	/* DATA */
2004 		{  100,   -2, 100 },	/* NOTMAP */
2005 		{  200,   -3,   0 }	/* NOENT */
2006 	};
2007 	BOOL c, m;
2008 
2009 	if (strcmp(contig, "contig") == 0)
2010 		c = TRUE;
2011 	else if (strcmp(contig, "noncontig") == 0)
2012 		c = FALSE;
2013 	else {
2014 		printf("rl pure [contig|noncontig] [single|multi]\n");
2015 		return;
2016 	}
2017 	if (strcmp(multi, "multi") == 0)
2018 		m = TRUE;
2019 	else if (strcmp(multi, "single") == 0)
2020 		m = FALSE;
2021 	else {
2022 		printf("rl pure [contig|noncontig] [single|multi]\n");
2023 		return;
2024 	}
2025 
2026 	test_rl_pure_test(1,  c, m,   0,  40, file1, sizeof(file1));
2027 	test_rl_pure_test(2,  c, m,  40,  40, file1, sizeof(file1));
2028 	test_rl_pure_test(3,  c, m,  60,  40, file1, sizeof(file1));
2029 	test_rl_pure_test(4,  c, m,   0, 100, file1, sizeof(file1));
2030 	test_rl_pure_test(5,  c, m, 200,  40, file1, sizeof(file1));
2031 	test_rl_pure_test(6,  c, m, 240,  40, file1, sizeof(file1));
2032 	test_rl_pure_test(7,  c, m, 260,  40, file1, sizeof(file1));
2033 	test_rl_pure_test(8,  c, m, 200, 100, file1, sizeof(file1));
2034 	test_rl_pure_test(9,  c, m, 400,  40, file1, sizeof(file1));
2035 	test_rl_pure_test(10, c, m, 440,  40, file1, sizeof(file1));
2036 	test_rl_pure_test(11, c, m, 460,  40, file1, sizeof(file1));
2037 	test_rl_pure_test(12, c, m, 400, 100, file1, sizeof(file1));
2038 	test_rl_pure_test(13, c, m, 160, 100, file2, sizeof(file2));
2039 	test_rl_pure_test(14, c, m, 100, 140, file2, sizeof(file2));
2040 	test_rl_pure_test(15, c, m, 200,  40, file2, sizeof(file2));
2041 	test_rl_pure_test(16, c, m, 240,  40, file2, sizeof(file2));
2042 	test_rl_pure_test(17, c, m, 100,  40, file3, sizeof(file3));
2043 	test_rl_pure_test(18, c, m, 140,  40, file3, sizeof(file3));
2044 	test_rl_pure_test(19, c, m,   0,  40, file4, sizeof(file4));
2045 	test_rl_pure_test(20, c, m,  40,  40, file4, sizeof(file4));
2046 	test_rl_pure_test(21, c, m,   0,  40, file5, sizeof(file5));
2047 	test_rl_pure_test(22, c, m,  40,  40, file5, sizeof(file5));
2048 	test_rl_pure_test(23, c, m,  60,  40, file5, sizeof(file5));
2049 	test_rl_pure_test(24, c, m,   0, 100, file5, sizeof(file5));
2050 	test_rl_pure_test(25, c, m, 200,  40, file5, sizeof(file5));
2051 	test_rl_pure_test(26, c, m, 240,  40, file5, sizeof(file5));
2052 	test_rl_pure_test(27, c, m, 260,  40, file5, sizeof(file5));
2053 	test_rl_pure_test(28, c, m, 200, 100, file5, sizeof(file5));
2054 	test_rl_pure_test(29, c, m, 400,  40, file5, sizeof(file5));
2055 	test_rl_pure_test(30, c, m, 440,  40, file5, sizeof(file5));
2056 	test_rl_pure_test(31, c, m, 460,  40, file5, sizeof(file5));
2057 	test_rl_pure_test(32, c, m, 400, 100, file5, sizeof(file5));
2058 	test_rl_pure_test(33, c, m, 160, 100, file6, sizeof(file6));
2059 	test_rl_pure_test(34, c, m, 100, 140, file6, sizeof(file6));
2060 }
2061 
2062 /**
2063  * test_rl_zero - Runlist test: Merge a zero-length runlist
2064  *
2065  * Description...
2066  *
2067  * Returns:
2068  */
test_rl_zero(void)2069 static void test_rl_zero(void)
2070 {
2071 	runlist_element *jim = NULL;
2072 	runlist_element *bob = NULL;
2073 
2074 	bob = calloc(3, sizeof(runlist_element));
2075 	if (!bob)
2076 		return;
2077 
2078 	MKRL(bob+0, 10, 99, 5)
2079 	MKRL(bob+1, 15, LCN_RL_NOT_MAPPED, 0)
2080 
2081 	jim = test_rl_runlists_merge(jim, bob);
2082 	if (!jim)
2083 		return;
2084 
2085 	free(jim);
2086 }
2087 
2088 /**
2089  * test_rl_frag_combine - Runlist test: Perform tests using fragmented files
2090  * @vol:
2091  * @attr1:
2092  * @attr2:
2093  * @attr3:
2094  *
2095  * Description...
2096  *
2097  * Returns:
2098  */
test_rl_frag_combine(ntfs_volume * vol,ATTR_RECORD * attr1,ATTR_RECORD * attr2,ATTR_RECORD * attr3)2099 static void test_rl_frag_combine(ntfs_volume *vol, ATTR_RECORD *attr1, ATTR_RECORD *attr2, ATTR_RECORD *attr3)
2100 {
2101 	runlist_element *run1;
2102 	runlist_element *run2;
2103 	runlist_element *run3;
2104 
2105 	run1 = ntfs_mapping_pairs_decompress(vol, attr1, NULL);
2106 	if (!run1)
2107 		return;
2108 
2109 	run2 = ntfs_mapping_pairs_decompress(vol, attr2, NULL);
2110 	if (!run2)
2111 		return;
2112 
2113 	run1 = test_rl_runlists_merge(run1, run2);
2114 
2115 	run3 = ntfs_mapping_pairs_decompress(vol, attr3, NULL);
2116 	if (!run3)
2117 		return;
2118 
2119 	run1 = test_rl_runlists_merge(run1, run3);
2120 
2121 	free(run1);
2122 }
2123 
2124 /**
2125  * test_rl_frag - Runlist test: Create tests using very fragmented files
2126  * @test:
2127  *
2128  * Description...
2129  *
2130  * Returns:
2131  */
test_rl_frag(char * test)2132 static void test_rl_frag(char *test)
2133 {
2134 	ntfs_volume vol;
2135 	ATTR_RECORD *attr1 = ntfs_malloc(1024);
2136 	ATTR_RECORD *attr2 = ntfs_malloc(1024);
2137 	ATTR_RECORD *attr3 = ntfs_malloc(1024);
2138 
2139 	if (!attr1 || !attr2 || !attr3)
2140 		goto out;
2141 
2142 	vol.sb = NULL;
2143 	vol.sector_size_bits = 9;
2144 	vol.cluster_size = 2048;
2145 	vol.cluster_size_bits = 11;
2146 	vol.major_ver = 3;
2147 
2148 	if (!test_rl_read_buffer("runlist-data/attr1.bin", (u8*) attr1, 1024))
2149 		goto out;
2150 	if (!test_rl_read_buffer("runlist-data/attr2.bin", (u8*) attr2, 1024))
2151 		goto out;
2152 	if (!test_rl_read_buffer("runlist-data/attr3.bin", (u8*) attr3, 1024))
2153 		goto out;
2154 
2155 	if      (strcmp(test, "123") == 0)  test_rl_frag_combine(&vol, attr1, attr2, attr3);
2156 	else if (strcmp(test, "132") == 0)  test_rl_frag_combine(&vol, attr1, attr3, attr2);
2157 	else if (strcmp(test, "213") == 0)  test_rl_frag_combine(&vol, attr2, attr1, attr3);
2158 	else if (strcmp(test, "231") == 0)  test_rl_frag_combine(&vol, attr2, attr3, attr1);
2159 	else if (strcmp(test, "312") == 0)  test_rl_frag_combine(&vol, attr3, attr1, attr2);
2160 	else if (strcmp(test, "321") == 0)  test_rl_frag_combine(&vol, attr3, attr2, attr1);
2161 	else
2162 		printf("Frag: No such test '%s'\n", test);
2163 
2164 out:
2165 	free(attr1);
2166 	free(attr2);
2167 	free(attr3);
2168 }
2169 
2170 /**
2171  * test_rl_main - Runlist test: Program start (main)
2172  * @argc:
2173  * @argv:
2174  *
2175  * Description...
2176  *
2177  * Returns:
2178  */
test_rl_main(int argc,char * argv[])2179 int test_rl_main(int argc, char *argv[])
2180 {
2181 	if      ((argc == 2) && (strcmp(argv[1], "zero") == 0)) test_rl_zero();
2182 	else if ((argc == 3) && (strcmp(argv[1], "frag") == 0)) test_rl_frag(argv[2]);
2183 	else if ((argc == 4) && (strcmp(argv[1], "pure") == 0)) test_rl_pure(argv[2], argv[3]);
2184 	else
2185 		printf("rl [zero|frag|pure] {args}\n");
2186 
2187 	return 0;
2188 }
2189 
2190 #endif
2191 
2192