summaryrefslogtreecommitdiff
path: root/com32/lib/syslinux/movebits.c
blob: c925339661df972267241c8bddb94705fb3f9a8e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
/* ----------------------------------------------------------------------- *
 *
 *   Copyright 2007-2008 H. Peter Anvin - All Rights Reserved
 *
 *   Permission is hereby granted, free of charge, to any person
 *   obtaining a copy of this software and associated documentation
 *   files (the "Software"), to deal in the Software without
 *   restriction, including without limitation the rights to use,
 *   copy, modify, merge, publish, distribute, sublicense, and/or
 *   sell copies of the Software, and to permit persons to whom
 *   the Software is furnished to do so, subject to the following
 *   conditions:
 *
 *   The above copyright notice and this permission notice shall
 *   be included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 *   OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 *   HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 *   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 *
 * ----------------------------------------------------------------------- */

/*
 * movebits.c
 *
 * Utility function to take a list of memory areas to shuffle and
 * convert it to a set of shuffle operations.
 *
 * Note: a lot of the functions in this file deal with "parent pointers",
 * which are pointers to a pointer to a list, or part of the list.
 * They can be pointers to a variable holding the list root pointer,
 * or pointers to a next field of a previous entry.
 */

#include <assert.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <inttypes.h>
#include <setjmp.h>

#include <syslinux/movebits.h>

#ifndef DEBUG
# ifdef TEST
#  define DEBUG 1
# else
#  define DEBUG 0
# endif
#endif

#if DEBUG
# include <stdio.h>
# define dprintf printf
#else
# define dprintf(...) ((void)0)
#endif

#define min(x,y) ((x) < (y) ? (x) : (y))
#define max(x,y) ((x) > (y) ? (x) : (y))

static jmp_buf new_movelist_bail;

static struct syslinux_movelist *
new_movelist(addr_t dst, addr_t src, addr_t len)
{
  struct syslinux_movelist *ml = malloc(sizeof(struct syslinux_movelist));

  if ( !ml )
    longjmp(new_movelist_bail, 1);

  ml->dst = dst;
  ml->src = src;
  ml->len = len;
  ml->next = NULL;

  return ml;
}

static struct syslinux_movelist *
dup_movelist(struct syslinux_movelist *src)
{
  struct syslinux_movelist *dst = NULL, **dstp = &dst, *ml;

  while (src) {
    ml = new_movelist(src->dst, src->src, src->len);
    *dstp = ml;
    dstp = &ml->next;
    src = src->next;
  }

  return dst;
}

/*
 * Take a chunk, entirely confined in **parentptr, and split it off so that
 * it has its own structure.
 */
static struct syslinux_movelist **
split_movelist(addr_t start, addr_t len, struct syslinux_movelist **parentptr)
{
  struct syslinux_movelist *m, *ml = *parentptr;

  assert(start >= ml->src);
  assert(start < ml->src+ml->len);

  /* Split off the beginning */
  if ( start > ml->src ) {
    addr_t l = start - ml->src;

    m = new_movelist(ml->dst+l, start, ml->len-l);
    m->next = ml->next;
    ml->len = l;
    ml->next = m;

    parentptr = &ml->next;
    ml = m;			/* Continue processing the new node */
  }

  /* Split off the end */
  if ( ml->len > len ) {
    addr_t l = ml->len - len;

    m = new_movelist(ml->dst+len, ml->src+len, l);
    m->next = ml->next;
    ml->len = len;
    ml->next = m;
  }

  return parentptr;
}

static void
delete_movelist(struct syslinux_movelist **parentptr)
{
  struct syslinux_movelist *o = *parentptr;
  *parentptr = o->next;
  free(o);
}

static void
free_movelist(struct syslinux_movelist **parentptr)
{
  while (*parentptr)
    delete_movelist(parentptr);
}

/*
 * Scan the freelist looking for a particular chunk of memory
 */
static struct syslinux_movelist **
is_free_zone(addr_t start, addr_t len, struct syslinux_movelist **space)
{
  struct syslinux_movelist *s;

  while ( (s = *space) ) {
    if ( s->src <= start && s->src+s->len >= start+len )
      return space;
    space = &s->next;
  }

  return NULL;
}

/*
 * Scan the freelist looking for the smallest chunk of memory which
 * can fit X bytes
 */
static struct syslinux_movelist **
free_area(addr_t len, struct syslinux_movelist **space)
{
  struct syslinux_movelist **best = NULL;
  struct syslinux_movelist *s;

  while ( (s = *space) ) {
    if ( s->len >= len ) {
      if ( !best || (*best)->len > s->len )
	best = space;
    }
    space = &s->next;
  }

  return best;
}


/*
 * Scan the freelist looking for the largest chunk of memory,
 * returns parent ptr
 */
static struct syslinux_movelist **
free_area_max(struct syslinux_movelist **space)
{
  struct syslinux_movelist **best = NULL;
  struct syslinux_movelist *s;

  while ( (s = *space) ) {
    if ( !best || s->len > (*best)->len )
      best = space;
    space = &s->next;
  }

  return best;
}

/*
 * Remove a chunk from the freelist
 */
static void
allocate_from(addr_t start, addr_t len, struct syslinux_movelist **parentptr)
{
  struct syslinux_movelist *c = *parentptr;

  assert(c->src <= start);
  assert(c->src+c->len >= start+len);

  if ( c->src != start || c->len != len ) {
    parentptr = split_movelist(start, len, parentptr);
    c = *parentptr;
  }

  *parentptr = c->next;
  free(c);
}

#if 0
/*
 * Remove any chunk from the freelist which is already
 * claimed by source data.  This somewhat frivolously
 * assumes that the fragments are either completely
 * covered by a free zone or not covered at all.
 */
static void
tidy_freelist(struct syslinux_movelist **frags,
	      struct syslinux_movelist **space)
{
  struct syslinux_movelist **sep;
  struct syslinux_movelist *f;

  while ( (f = *frags) ) {
    if ( (sep = is_free_zone(f->src, f->len, space)) )
      allocate_from(f->src, f->len, sep);
    frags = &f->next;
  }
}
#endif

/*
 * moves is computed from "frags" and "freemem".  "space" lists
 * free memory areas at our disposal, and is (src, cnt) only.
 */

int
syslinux_compute_movelist(struct syslinux_movelist **moves,
			  struct syslinux_movelist *ifrags,
			  struct syslinux_memmap *memmap)
{
  struct syslinux_memmap *mmap = NULL, *mm;
  struct syslinux_movelist *frags = NULL;
  struct syslinux_movelist *mv, *space;
  struct syslinux_movelist *f, **fp, **ep;
  struct syslinux_movelist *o, **op;
  addr_t needbase, needlen, copysrc, copydst, copylen;
  addr_t freebase, freelen;
  addr_t mstart, avail;
  addr_t cbyte;
  int m_ok;
  int rv = -1;
  int reverse;
  int again;

  dprintf("entering syslinux_compute_movelist()...\n");

  if (setjmp(new_movelist_bail)) {
    dprintf("Out of working memory!\n");
    goto bail;
  }

  *moves = NULL;

  /* Mark any memory that's in use by source material busy in the memory map */
  mmap = syslinux_dup_memmap(memmap);
  if (!mmap)
    goto bail;

  frags = dup_movelist(ifrags);

#if DEBUG
  dprintf("Initial memory map:\n");
  syslinux_dump_memmap(stdout, mmap);
#endif

  for (f = frags; f; f = f->next) {
    if (syslinux_add_memmap(&mmap, f->src, f->len, SMT_ALLOC)) {
      dprintf("Cannot generate free map\n");
      goto bail;
    }
  }

#if DEBUG
  dprintf("Adjusted memory map:\n");
  syslinux_dump_memmap(stdout, mmap);
#endif

  /* Compute the freelist in movelist format. */
  space = NULL;
  ep = &space;
  mstart = -1;
  m_ok = 0;

  /* Yes, we really do want to run through the loop on SMT_END */
  for (mm = mmap; mm; mm = mm->next) {
    /* We can safely use to-be-zeroed memory as a scratch area. */
    if (mmap->type == SMT_FREE || mmap->type == SMT_ZERO) {
      if (!m_ok) {
	m_ok = 1;
	mstart = mmap->start;
      }
    } else {
      if (m_ok) {
	f = new_movelist(0, mstart, mmap->start - mstart);
	*ep = f;
	ep = &f->next;
	m_ok = 0;
      }
    }

    mmap = mmap->next;
  }

  do {
    again = 0;

#if DEBUG
    dprintf("Current free list:\n");
    syslinux_dump_movelist(stdout, space);
    dprintf("Current frag list:\n");
    syslinux_dump_movelist(stdout, frags);
#endif

    fp = &frags;
    while ( (f = *fp) ) {
      dprintf("@: 0x%08x bytes at 0x%08x -> 0x%08x\n",
	      f->len, f->src, f->dst);

      if ( f->src == f->dst ) {
	delete_movelist(fp);
	continue;
      }

      /* See if we can move this chunk into place by claiming
	 the destination, or in the case of partial overlap, the
	 missing portion. */

      needbase = f->dst;
      needlen  = f->len;

      dprintf("need: base = 0x%08x, len = 0x%08x\n", needbase, needlen);

      reverse = 0;
      cbyte = f->dst;		/* "Critical byte" */
      if ( f->src < f->dst && (f->dst - f->src) < f->len ) {
	/* "Shift up" type overlap */
	needlen  = f->dst - f->src;
	needbase = f->dst + (f->len - needlen);
	cbyte = f->dst + f->len - 1;
	reverse = 1;
      } else if ( f->src > f->dst && (f->src - f->dst) < f->len ) {
	/* "Shift down" type overlap */
	needbase = f->dst;
	needlen  = f->src - f->dst;
      }

      dprintf("need: base = 0x%08x, len = 0x%08x, "
	      "reverse = %d, cbyte = 0x%08x\n",
	      needbase, needlen, reverse, cbyte);

      ep = is_free_zone(cbyte, 1, &space);
      if (ep) {
	if (reverse)
	  avail = needbase+needlen - (*ep)->src;
	else
	  avail = (*ep)->len - (needbase - (*ep)->src);
      } else {
	avail = 0;
      }

      if (avail) {
	/* We can move at least part of this chunk into place without
	   further ado */
	dprintf("space: start 0x%08x, len 0x%08x, free 0x%08x\n",
		(*ep)->src, (*ep)->len, avail);
	copylen = min(needlen, avail);

	if (reverse)
	  allocate_from(needbase+needlen-copylen, copylen, ep);
	else
	  allocate_from(needbase, copylen, ep);

	goto move_chunk;
      }

      /* At this point, we need to evict something out of our space.
	 Find the object occupying the critical byte of our target space,
	 and move it out (the whole object if we can, otherwise a subset.)
	 Then move a chunk of ourselves into place. */
      for ( op = &f->next, o = *op ; o ; op = &o->next, o = *op ) {

	dprintf("O: 0x%08x bytes at 0x%08x -> 0x%08x\n",
		o->len, o->src, o->dst);

	if ( !(o->src <= cbyte && o->src+o->len > cbyte) )
	  continue;		/* Not what we're looking for... */

	/* Find somewhere to put it... */

	if ( (ep = is_free_zone(o->dst, o->len, &space)) ) {
	  /* Score!  We can move it into place directly... */
	  copydst = o->dst;
	  copylen = o->len;
	} else if ( (ep = free_area(o->len, &space)) ) {
	  /* We can move the whole chunk */
	  copydst = (*ep)->src;
	  copylen = o->len;
	} else {
	  /* Well, copy as much as we can... */
	  ep = free_area_max(&space);
	  if ( !ep ) {
	    dprintf("No free memory at all!\n");
	    goto bail;		/* Stuck! */
	  }

	  /* Make sure we include the critical byte */
	  copydst = (*ep)->src;
	  if (reverse) {
	    copysrc = max(o->src, cbyte+1 - (*ep)->len);
	    copylen = cbyte+1 - copysrc;
	  } else {
	    copysrc = cbyte;
	    copylen = min((*ep)->len, o->len - (cbyte-o->src));
	  }
	}
	allocate_from(copydst, copylen, ep);

	if ( copylen < o->len ) {
	  op = split_movelist(copysrc, copylen, op);
	  o = *op;
	}

	mv = new_movelist(copydst, copysrc, copylen);
	dprintf("C: 0x%08x bytes at 0x%08x -> 0x%08x\n",
		mv->len, mv->src, mv->dst);
	*moves = mv;
	moves = &mv->next;

	o->src = copydst;

	if ( copylen > needlen ) {
	  /* We don't need all the memory we freed up.  Mark it free. */
	  if ( copysrc < needbase ) {
	    mv = new_movelist(0, copysrc, needbase-copysrc);
	    mv->next = space;
	    space = mv;
	    copylen -= (needbase-copysrc);
	  }
	  if ( copylen > needlen ) {
	    mv = new_movelist(0, copysrc+needlen, copylen-needlen);
	    mv->next = space;
	    space = mv;
	    copylen = needlen;
	  }
	}
	reverse = 0;
	goto move_chunk;
      }
      dprintf("Cannot find the chunk containing the critical byte\n");
      goto bail;			/* Stuck! */

    move_chunk:
      /* We're allowed to move the chunk into place now. */

      copydst = f->dst;
      copysrc = f->src;

      dprintf("Q: copylen = 0x%08x, needlen = 0x%08x\n", copylen, needlen);

      if ( copylen < needlen ) {
	if (reverse) {
	  copydst += (f->len-copylen);
	  copysrc += (f->len-copylen);
	}
      
	dprintf("X: 0x%08x bytes at 0x%08x -> 0x%08x\n",
		copylen, copysrc, copydst);

	/* Didn't get all we wanted, so we have to split the chunk */
	fp = split_movelist(copysrc, copylen, fp); /* Is this right? */
	f = *fp;
      }

      mv = new_movelist(f->dst, f->src, f->len);
      dprintf("A: 0x%08x bytes at 0x%08x -> 0x%08x\n",
	      mv->len, mv->src, mv->dst);
      *moves = mv;
      moves = &mv->next;

      /* Figure out what memory we just freed up */
      if ( f->dst > f->src ) {
	freebase = f->src;
	freelen  = min(f->len, f->dst-f->src);
      } else if ( f->src >= f->dst+f->len ) {
	freebase = f->src;
	freelen  = f->len;
      } else {
	freelen  = f->src-f->dst;
	freebase = f->dst+f->len;
      }

      dprintf("F: 0x%08x bytes at 0x%08x\n", freelen, freebase);

      mv = new_movelist(0, freebase, freelen);
      mv->next = space;
      space = mv;
      
      delete_movelist(fp);
      again = 1;		/* At least one chunk was moved */
    }
  } while (again);

  rv = 0;
 bail:
  if (mmap)
    syslinux_free_memmap(mmap);
  if (frags)
    free_movelist(&frags);
  return rv;
}

#ifdef TEST

#include <stdio.h>

int main(int argc, char *argv[])
{
  FILE *f;
  unsigned long d, s, l;
  struct syslinux_movelist *frags;
  struct syslinux_movelist **fep = &frags;
  struct syslinux_movelist *space;
  struct syslinux_movelist **sep = &space;
  struct syslinux_movelist *mv, *moves;

  f = fopen(argv[1], "r");
  while ( fscanf(f, "%lx %lx %lx", &d, &s, &l) == 3 ) {
    if ( d ) {
      mv = new_movelist(d, s, l);
      *fep = mv;
      fep = &mv->next;
    } else {
      mv = new_movelist(0, s, l);
      *sep = mv;
      sep = &mv->next;
    }
  }
  fclose(f);

  if ( syslinux_compute_movelist(&moves, frags, space) ) {
    printf("Failed to compute a move sequence\n");
    return 1;
  } else {
    for ( mv = moves ; mv ; mv = mv->next ) {
      printf("0x%08x bytes at 0x%08x -> 0x%08x\n",
	     mv->len, mv->src, mv->dst);
    }
    return 0;
  }
 }

#endif /* TEST */