commit_graph.c 33.8 KB
Newer Older
1 2 3 4 5 6 7 8 9
/*
 * Copyright (C) the libgit2 contributors. All rights reserved.
 *
 * This file is part of libgit2, distributed under the GNU GPL v2 with
 * a Linking Exception. For full terms see the included COPYING file.
 */

#include "commit_graph.h"

10
#include "array.h"
11
#include "buf.h"
12
#include "filebuf.h"
13 14
#include "futils.h"
#include "hash.h"
15 16
#include "oidarray.h"
#include "oidmap.h"
17
#include "pack.h"
18 19
#include "repository.h"
#include "revwalk.h"
20 21

#define GIT_COMMIT_GRAPH_MISSING_PARENT 0x70000000
22 23
#define GIT_COMMIT_GRAPH_GENERATION_NUMBER_MAX 0x3FFFFFFF
#define GIT_COMMIT_GRAPH_GENERATION_NUMBER_INFINITY 0xFFFFFFFF
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

#define COMMIT_GRAPH_SIGNATURE 0x43475048 /* "CGPH" */
#define COMMIT_GRAPH_VERSION 1
#define COMMIT_GRAPH_OBJECT_ID_VERSION 1
struct git_commit_graph_header {
	uint32_t signature;
	uint8_t version;
	uint8_t object_id_version;
	uint8_t chunks;
	uint8_t base_graph_files;
};

#define COMMIT_GRAPH_OID_FANOUT_ID 0x4f494446	      /* "OIDF" */
#define COMMIT_GRAPH_OID_LOOKUP_ID 0x4f49444c	      /* "OIDL" */
#define COMMIT_GRAPH_COMMIT_DATA_ID 0x43444154	      /* "CDAT" */
#define COMMIT_GRAPH_EXTRA_EDGE_LIST_ID 0x45444745    /* "EDGE" */
#define COMMIT_GRAPH_BLOOM_FILTER_INDEX_ID 0x42494458 /* "BIDX" */
#define COMMIT_GRAPH_BLOOM_FILTER_DATA_ID 0x42444154  /* "BDAT" */

struct git_commit_graph_chunk {
	off64_t offset;
	size_t length;
};

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
typedef git_array_t(size_t) parent_index_array_t;

struct packed_commit {
	size_t index;
	git_oid sha1;
	git_oid tree_oid;
	uint32_t generation;
	git_time_t commit_time;
	git_array_oid_t parents;
	parent_index_array_t parent_indices;
};

static void packed_commit_free(struct packed_commit *p)
{
	if (!p)
		return;

	git_array_clear(p->parents);
	git_array_clear(p->parent_indices);
	git__free(p);
}

static struct packed_commit *packed_commit_new(git_commit *commit)
{
	unsigned int i, parentcount = git_commit_parentcount(commit);
lhchavez committed
73
	struct packed_commit *p = git__calloc(1, sizeof(struct packed_commit));
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
	if (!p)
		goto cleanup;

	git_array_init_to_size(p->parents, parentcount);
	if (parentcount && !p->parents.ptr)
		goto cleanup;

	if (git_oid_cpy(&p->sha1, git_commit_id(commit)) < 0)
		goto cleanup;
	if (git_oid_cpy(&p->tree_oid, git_commit_tree_id(commit)) < 0)
		goto cleanup;
	p->commit_time = git_commit_time(commit);

	for (i = 0; i < parentcount; ++i) {
		git_oid *parent_id = git_array_alloc(p->parents);
		if (!parent_id)
			goto cleanup;
		if (git_oid_cpy(parent_id, git_commit_parent_id(commit, i)) < 0)
			goto cleanup;
	}

	return p;

cleanup:
	packed_commit_free(p);
	return NULL;
}

typedef int (*commit_graph_write_cb)(const char *buf, size_t size, void *cb_data);

104 105 106 107 108 109 110
static int commit_graph_error(const char *message)
{
	git_error_set(GIT_ERROR_ODB, "invalid commit-graph file - %s", message);
	return -1;
}

static int commit_graph_parse_oid_fanout(
111
		git_commit_graph_file *file,
112 113 114 115 116 117 118 119 120 121 122
		const unsigned char *data,
		struct git_commit_graph_chunk *chunk_oid_fanout)
{
	uint32_t i, nr;
	if (chunk_oid_fanout->offset == 0)
		return commit_graph_error("missing OID Fanout chunk");
	if (chunk_oid_fanout->length == 0)
		return commit_graph_error("empty OID Fanout chunk");
	if (chunk_oid_fanout->length != 256 * 4)
		return commit_graph_error("OID Fanout chunk has wrong length");

123
	file->oid_fanout = (const uint32_t *)(data + chunk_oid_fanout->offset);
124 125
	nr = 0;
	for (i = 0; i < 256; ++i) {
126
		uint32_t n = ntohl(file->oid_fanout[i]);
127 128 129 130
		if (n < nr)
			return commit_graph_error("index is non-monotonic");
		nr = n;
	}
131
	file->num_commits = nr;
132 133 134 135
	return 0;
}

static int commit_graph_parse_oid_lookup(
136
		git_commit_graph_file *file,
137 138 139 140
		const unsigned char *data,
		struct git_commit_graph_chunk *chunk_oid_lookup)
{
	uint32_t i;
141
	unsigned char *oid, *prev_oid, zero_oid[GIT_OID_SHA1_SIZE] = {0};
142 143 144 145 146

	if (chunk_oid_lookup->offset == 0)
		return commit_graph_error("missing OID Lookup chunk");
	if (chunk_oid_lookup->length == 0)
		return commit_graph_error("empty OID Lookup chunk");
147
	if (chunk_oid_lookup->length != file->num_commits * GIT_OID_SHA1_SIZE)
148 149
		return commit_graph_error("OID Lookup chunk has wrong length");

150 151
	file->oid_lookup = oid = (unsigned char *)(data + chunk_oid_lookup->offset);
	prev_oid = zero_oid;
152
	for (i = 0; i < file->num_commits; ++i, oid += GIT_OID_SHA1_SIZE) {
Edward Thomson committed
153
		if (git_oid_raw_cmp(prev_oid, oid, GIT_OID_SHA1_SIZE) >= 0)
154 155 156 157 158 159 160 161
			return commit_graph_error("OID Lookup index is non-monotonic");
		prev_oid = oid;
	}

	return 0;
}

static int commit_graph_parse_commit_data(
162
		git_commit_graph_file *file,
163 164 165 166 167 168 169
		const unsigned char *data,
		struct git_commit_graph_chunk *chunk_commit_data)
{
	if (chunk_commit_data->offset == 0)
		return commit_graph_error("missing Commit Data chunk");
	if (chunk_commit_data->length == 0)
		return commit_graph_error("empty Commit Data chunk");
170
	if (chunk_commit_data->length != file->num_commits * (GIT_OID_SHA1_SIZE + 16))
171 172
		return commit_graph_error("Commit Data chunk has wrong length");

173
	file->commit_data = data + chunk_commit_data->offset;
174 175 176 177 178

	return 0;
}

static int commit_graph_parse_extra_edge_list(
179
		git_commit_graph_file *file,
180 181 182 183 184 185 186 187
		const unsigned char *data,
		struct git_commit_graph_chunk *chunk_extra_edge_list)
{
	if (chunk_extra_edge_list->length == 0)
		return 0;
	if (chunk_extra_edge_list->length % 4 != 0)
		return commit_graph_error("malformed Extra Edge List chunk");

188 189
	file->extra_edge_list = data + chunk_extra_edge_list->offset;
	file->num_extra_edge_list = chunk_extra_edge_list->length / 4;
190 191 192 193

	return 0;
}

194 195 196 197
int git_commit_graph_file_parse(
		git_commit_graph_file *file,
		const unsigned char *data,
		size_t size)
198 199 200 201 202
{
	struct git_commit_graph_header *hdr;
	const unsigned char *chunk_hdr;
	struct git_commit_graph_chunk *last_chunk;
	uint32_t i;
203
	uint64_t last_chunk_offset, chunk_offset, trailer_offset;
204
	size_t checksum_size;
205 206 207 208 209
	int error;
	struct git_commit_graph_chunk chunk_oid_fanout = {0}, chunk_oid_lookup = {0},
				      chunk_commit_data = {0}, chunk_extra_edge_list = {0},
				      chunk_unsupported = {0};

210
	GIT_ASSERT_ARG(file);
211

212
	if (size < sizeof(struct git_commit_graph_header) + GIT_OID_SHA1_SIZE)
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
		return commit_graph_error("commit-graph is too short");

	hdr = ((struct git_commit_graph_header *)data);

	if (hdr->signature != htonl(COMMIT_GRAPH_SIGNATURE) || hdr->version != COMMIT_GRAPH_VERSION
	    || hdr->object_id_version != COMMIT_GRAPH_OBJECT_ID_VERSION) {
		return commit_graph_error("unsupported commit-graph version");
	}
	if (hdr->chunks == 0)
		return commit_graph_error("no chunks in commit-graph");

	/*
	 * The very first chunk's offset should be after the header, all the chunk
	 * headers, and a special zero chunk.
	 */
	last_chunk_offset = sizeof(struct git_commit_graph_header) + (1 + hdr->chunks) * 12;
229
	trailer_offset = size - GIT_OID_SHA1_SIZE;
230 231
	checksum_size = GIT_HASH_SHA1_SIZE;

232 233
	if (trailer_offset < last_chunk_offset)
		return commit_graph_error("wrong commit-graph size");
234
	memcpy(file->checksum, (data + trailer_offset), checksum_size);
235 236 237 238

	chunk_hdr = data + sizeof(struct git_commit_graph_header);
	last_chunk = NULL;
	for (i = 0; i < hdr->chunks; ++i, chunk_hdr += 12) {
239 240
		chunk_offset = ((uint64_t)ntohl(*((uint32_t *)(chunk_hdr + 4)))) << 32
				| ((uint64_t)ntohl(*((uint32_t *)(chunk_hdr + 8))));
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
		if (chunk_offset < last_chunk_offset)
			return commit_graph_error("chunks are non-monotonic");
		if (chunk_offset >= trailer_offset)
			return commit_graph_error("chunks extend beyond the trailer");
		if (last_chunk != NULL)
			last_chunk->length = (size_t)(chunk_offset - last_chunk_offset);
		last_chunk_offset = chunk_offset;

		switch (ntohl(*((uint32_t *)(chunk_hdr + 0)))) {
		case COMMIT_GRAPH_OID_FANOUT_ID:
			chunk_oid_fanout.offset = last_chunk_offset;
			last_chunk = &chunk_oid_fanout;
			break;

		case COMMIT_GRAPH_OID_LOOKUP_ID:
			chunk_oid_lookup.offset = last_chunk_offset;
			last_chunk = &chunk_oid_lookup;
			break;

		case COMMIT_GRAPH_COMMIT_DATA_ID:
			chunk_commit_data.offset = last_chunk_offset;
			last_chunk = &chunk_commit_data;
			break;

		case COMMIT_GRAPH_EXTRA_EDGE_LIST_ID:
			chunk_extra_edge_list.offset = last_chunk_offset;
			last_chunk = &chunk_extra_edge_list;
			break;

		case COMMIT_GRAPH_BLOOM_FILTER_INDEX_ID:
		case COMMIT_GRAPH_BLOOM_FILTER_DATA_ID:
			chunk_unsupported.offset = last_chunk_offset;
			last_chunk = &chunk_unsupported;
			break;

		default:
			return commit_graph_error("unrecognized chunk ID");
		}
	}
	last_chunk->length = (size_t)(trailer_offset - last_chunk_offset);

282
	error = commit_graph_parse_oid_fanout(file, data, &chunk_oid_fanout);
283 284
	if (error < 0)
		return error;
285
	error = commit_graph_parse_oid_lookup(file, data, &chunk_oid_lookup);
286 287
	if (error < 0)
		return error;
288
	error = commit_graph_parse_commit_data(file, data, &chunk_commit_data);
289 290
	if (error < 0)
		return error;
291
	error = commit_graph_parse_extra_edge_list(file, data, &chunk_extra_edge_list);
292 293 294 295 296 297
	if (error < 0)
		return error;

	return 0;
}

298
int git_commit_graph_new(git_commit_graph **cgraph_out, const char *objects_dir, bool open_file)
299
{
300 301 302 303 304 305 306 307 308
	git_commit_graph *cgraph = NULL;
	int error = 0;

	GIT_ASSERT_ARG(cgraph_out);
	GIT_ASSERT_ARG(objects_dir);

	cgraph = git__calloc(1, sizeof(git_commit_graph));
	GIT_ERROR_CHECK_ALLOC(cgraph);

309
	error = git_str_joinpath(&cgraph->filename, objects_dir, "info/commit-graph");
310 311 312 313
	if (error < 0)
		goto error;

	if (open_file) {
314
		error = git_commit_graph_file_open(&cgraph->file, git_str_cstr(&cgraph->filename));
315 316 317 318 319 320 321 322 323 324 325 326 327
		if (error < 0)
			goto error;
		cgraph->checked = 1;
	}

	*cgraph_out = cgraph;
	return 0;

error:
	git_commit_graph_free(cgraph);
	return error;
}

328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
int git_commit_graph_validate(git_commit_graph *cgraph) {
	unsigned char checksum[GIT_HASH_SHA1_SIZE];
	size_t checksum_size = GIT_HASH_SHA1_SIZE;
	size_t trailer_offset = cgraph->file->graph_map.len - checksum_size;

	if (cgraph->file->graph_map.len < checksum_size)
		return commit_graph_error("map length too small");

	if (git_hash_buf(checksum, cgraph->file->graph_map.data, trailer_offset, GIT_HASH_ALGORITHM_SHA1) < 0)
		return commit_graph_error("could not calculate signature");
	if (memcmp(checksum, cgraph->file->checksum, checksum_size) != 0)
		return commit_graph_error("index signature mismatch");

	return 0;
}

344 345
int git_commit_graph_open(git_commit_graph **cgraph_out, const char *objects_dir)
{
346 347 348 349 350
	int error = git_commit_graph_new(cgraph_out, objects_dir, true);
	if (!error) {
		return git_commit_graph_validate(*cgraph_out);
	}
	return error;
351 352 353 354 355
}

int git_commit_graph_file_open(git_commit_graph_file **file_out, const char *path)
{
	git_commit_graph_file *file;
356 357 358 359 360 361 362 363 364 365 366 367
	git_file fd = -1;
	size_t cgraph_size;
	struct stat st;
	int error;

	/* TODO: properly open the file without access time using O_NOATIME */
	fd = git_futils_open_ro(path);
	if (fd < 0)
		return fd;

	if (p_fstat(fd, &st) < 0) {
		p_close(fd);
368 369
		git_error_set(GIT_ERROR_ODB, "commit-graph file not found - '%s'", path);
		return GIT_ENOTFOUND;
370 371 372 373 374
	}

	if (!S_ISREG(st.st_mode) || !git__is_sizet(st.st_size)) {
		p_close(fd);
		git_error_set(GIT_ERROR_ODB, "invalid pack index '%s'", path);
375
		return GIT_ENOTFOUND;
376 377 378
	}
	cgraph_size = (size_t)st.st_size;

379 380
	file = git__calloc(1, sizeof(git_commit_graph_file));
	GIT_ERROR_CHECK_ALLOC(file);
381

382
	error = git_futils_mmap_ro(&file->graph_map, fd, 0, cgraph_size);
383 384
	p_close(fd);
	if (error < 0) {
385
		git_commit_graph_file_free(file);
386 387 388
		return error;
	}

389 390
	if ((error = git_commit_graph_file_parse(file, file->graph_map.data, cgraph_size)) < 0) {
		git_commit_graph_file_free(file);
391 392 393
		return error;
	}

394
	*file_out = file;
395 396 397
	return 0;
}

398 399 400 401 402 403 404 405 406 407
int git_commit_graph_get_file(git_commit_graph_file **file_out, git_commit_graph *cgraph)
{
	if (!cgraph->checked) {
		int error = 0;
		git_commit_graph_file *result = NULL;

		/* We only check once, no matter the result. */
		cgraph->checked = 1;

		/* Best effort */
408
		error = git_commit_graph_file_open(&result, git_str_cstr(&cgraph->filename));
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427

		if (error < 0)
			return error;

		cgraph->file = result;
	}
	if (!cgraph->file)
		return GIT_ENOTFOUND;

	*file_out = cgraph->file;
	return 0;
}

void git_commit_graph_refresh(git_commit_graph *cgraph)
{
	if (!cgraph->checked)
		return;

	if (cgraph->file
428
	    && git_commit_graph_file_needs_refresh(cgraph->file, git_str_cstr(&cgraph->filename))) {
429 430 431 432 433 434 435 436 437
		/* We just free the commit graph. The next time it is requested, it will be
		 * re-loaded. */
		git_commit_graph_file_free(cgraph->file);
		cgraph->file = NULL;
	}
	/* Force a lazy re-check next time it is needed. */
	cgraph->checked = 0;
}

438 439
static int git_commit_graph_entry_get_byindex(
		git_commit_graph_entry *e,
440
		const git_commit_graph_file *file,
441 442 443 444 445
		size_t pos)
{
	const unsigned char *commit_data;

	GIT_ASSERT_ARG(e);
446
	GIT_ASSERT_ARG(file);
447

448
	if (pos >= file->num_commits) {
449 450 451 452
		git_error_set(GIT_ERROR_INVALID, "commit index %zu does not exist", pos);
		return GIT_ENOTFOUND;
	}

453
	commit_data = file->commit_data + pos * (GIT_OID_SHA1_SIZE + 4 * sizeof(uint32_t));
454
	git_oid__fromraw(&e->tree_oid, commit_data, GIT_OID_SHA1);
455
	e->parent_indices[0] = ntohl(*((uint32_t *)(commit_data + GIT_OID_SHA1_SIZE)));
lhchavez committed
456
	e->parent_indices[1] = ntohl(
457
			*((uint32_t *)(commit_data + GIT_OID_SHA1_SIZE + sizeof(uint32_t))));
458 459
	e->parent_count = (e->parent_indices[0] != GIT_COMMIT_GRAPH_MISSING_PARENT)
			+ (e->parent_indices[1] != GIT_COMMIT_GRAPH_MISSING_PARENT);
460 461
	e->generation = ntohl(*((uint32_t *)(commit_data + GIT_OID_SHA1_SIZE + 2 * sizeof(uint32_t))));
	e->commit_time = ntohl(*((uint32_t *)(commit_data + GIT_OID_SHA1_SIZE + 3 * sizeof(uint32_t))));
462

463
	e->commit_time |= (e->generation & UINT64_C(0x3)) << UINT64_C(32);
464 465 466 467 468
	e->generation >>= 2u;
	if (e->parent_indices[1] & 0x80000000u) {
		uint32_t extra_edge_list_pos = e->parent_indices[1] & 0x7fffffff;

		/* Make sure we're not being sent out of bounds */
469
		if (extra_edge_list_pos >= file->num_extra_edge_list) {
470 471 472 473 474 475 476
			git_error_set(GIT_ERROR_INVALID,
				      "commit %u does not exist",
				      extra_edge_list_pos);
			return GIT_ENOTFOUND;
		}

		e->extra_parents_index = extra_edge_list_pos;
477
		while (extra_edge_list_pos < file->num_extra_edge_list
478
		       && (ntohl(*(
479
					   (uint32_t *)(file->extra_edge_list
480 481 482 483 484 485 486
							+ extra_edge_list_pos * sizeof(uint32_t))))
			   & 0x80000000u)
				       == 0) {
			extra_edge_list_pos++;
			e->parent_count++;
		}
	}
487

488
	git_oid__fromraw(&e->sha1, &file->oid_lookup[pos * GIT_OID_SHA1_SIZE], GIT_OID_SHA1);
489 490 491
	return 0;
}

492
bool git_commit_graph_file_needs_refresh(const git_commit_graph_file *file, const char *path)
493 494 495 496
{
	git_file fd = -1;
	struct stat st;
	ssize_t bytes_read;
497 498
	unsigned char checksum[GIT_HASH_SHA1_SIZE];
	size_t checksum_size = GIT_HASH_SHA1_SIZE;
499 500 501 502 503 504 505 506 507 508 509 510

	/* TODO: properly open the file without access time using O_NOATIME */
	fd = git_futils_open_ro(path);
	if (fd < 0)
		return true;

	if (p_fstat(fd, &st) < 0) {
		p_close(fd);
		return true;
	}

	if (!S_ISREG(st.st_mode) || !git__is_sizet(st.st_size)
511
	    || (size_t)st.st_size != file->graph_map.len) {
512 513 514 515
		p_close(fd);
		return true;
	}

516
	bytes_read = p_pread(fd, checksum, checksum_size, st.st_size - checksum_size);
517
	p_close(fd);
518
	if (bytes_read != (ssize_t)checksum_size)
519 520
		return true;

521
	return (memcmp(checksum, file->checksum, checksum_size) != 0);
522 523
}

524 525
int git_commit_graph_entry_find(
		git_commit_graph_entry *e,
526
		const git_commit_graph_file *file,
527 528 529 530 531
		const git_oid *short_oid,
		size_t len)
{
	int pos, found = 0;
	uint32_t hi, lo;
532
	const unsigned char *current = NULL;
533 534

	GIT_ASSERT_ARG(e);
535
	GIT_ASSERT_ARG(file);
536 537
	GIT_ASSERT_ARG(short_oid);

538 539
	hi = ntohl(file->oid_fanout[(int)short_oid->id[0]]);
	lo = ((short_oid->id[0] == 0x0) ? 0 : ntohl(file->oid_fanout[(int)short_oid->id[0] - 1]));
540

541
	pos = git_pack__lookup_id(file->oid_lookup, GIT_OID_SHA1_SIZE, lo, hi, short_oid->id, GIT_OID_SHA1);
542 543 544 545

	if (pos >= 0) {
		/* An object matching exactly the oid was found */
		found = 1;
546
		current = file->oid_lookup + (pos * GIT_OID_SHA1_SIZE);
547 548 549 550
	} else {
		/* No object was found */
		/* pos refers to the object with the "closest" oid to short_oid */
		pos = -1 - pos;
551
		if (pos < (int)file->num_commits) {
552
			current = file->oid_lookup + (pos * GIT_OID_SHA1_SIZE);
553

554
			if (!git_oid_raw_ncmp(short_oid->id, current, len))
555 556 557 558
				found = 1;
		}
	}

559
	if (found && len != GIT_OID_SHA1_HEXSIZE && pos + 1 < (int)file->num_commits) {
560
		/* Check for ambiguousity */
561
		const unsigned char *next = current + GIT_OID_SHA1_SIZE;
562

563
		if (!git_oid_raw_ncmp(short_oid->id, next, len))
564 565 566 567 568
			found = 2;
	}

	if (!found)
		return git_odb__error_notfound(
569
				"failed to find offset for commit-graph index entry", short_oid, len);
570 571
	if (found > 1)
		return git_odb__error_ambiguous(
572
				"found multiple offsets for commit-graph index entry");
573

574
	return git_commit_graph_entry_get_byindex(e, file, pos);
575 576 577 578
}

int git_commit_graph_entry_parent(
		git_commit_graph_entry *parent,
579
		const git_commit_graph_file *file,
580 581 582 583
		const git_commit_graph_entry *entry,
		size_t n)
{
	GIT_ASSERT_ARG(parent);
584
	GIT_ASSERT_ARG(file);
585 586 587 588 589 590 591

	if (n >= entry->parent_count) {
		git_error_set(GIT_ERROR_INVALID, "parent index %zu does not exist", n);
		return GIT_ENOTFOUND;
	}

	if (n == 0 || (n == 1 && entry->parent_count == 2))
592
		return git_commit_graph_entry_get_byindex(parent, file, entry->parent_indices[n]);
593 594 595

	return git_commit_graph_entry_get_byindex(
			parent,
596
			file,
597
			ntohl(
598
					*(uint32_t *)(file->extra_edge_list
599 600 601 602 603
						      + (entry->extra_parents_index + n - 1)
								      * sizeof(uint32_t)))
					& 0x7fffffff);
}

604
int git_commit_graph_file_close(git_commit_graph_file *file)
605
{
606
	GIT_ASSERT_ARG(file);
607

608 609
	if (file->graph_map.data)
		git_futils_mmap_free(&file->graph_map);
610 611 612 613

	return 0;
}

614
void git_commit_graph_free(git_commit_graph *cgraph)
615 616 617 618
{
	if (!cgraph)
		return;

619
	git_str_dispose(&cgraph->filename);
620
	git_commit_graph_file_free(cgraph->file);
621 622
	git__free(cgraph);
}
623 624 625 626 627 628 629 630 631

void git_commit_graph_file_free(git_commit_graph_file *file)
{
	if (!file)
		return;

	git_commit_graph_file_close(file);
	git__free(file);
}
632 633 634 635 636 637 638 639 640 641 642 643 644

static int packed_commit__cmp(const void *a_, const void *b_)
{
	const struct packed_commit *a = a_;
	const struct packed_commit *b = b_;
	return git_oid_cmp(&a->sha1, &b->sha1);
}

int git_commit_graph_writer_new(git_commit_graph_writer **out, const char *objects_info_dir)
{
	git_commit_graph_writer *w = git__calloc(1, sizeof(git_commit_graph_writer));
	GIT_ERROR_CHECK_ALLOC(w);

645
	if (git_str_sets(&w->objects_info_dir, objects_info_dir) < 0) {
646 647 648 649 650
		git__free(w);
		return -1;
	}

	if (git_vector_init(&w->commits, 0, packed_commit__cmp) < 0) {
651
		git_str_dispose(&w->objects_info_dir);
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
		git__free(w);
		return -1;
	}

	*out = w;
	return 0;
}

void git_commit_graph_writer_free(git_commit_graph_writer *w)
{
	struct packed_commit *packed_commit;
	size_t i;

	if (!w)
		return;

	git_vector_foreach (&w->commits, i, packed_commit)
		packed_commit_free(packed_commit);
	git_vector_free(&w->commits);
671
	git_str_dispose(&w->objects_info_dir);
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
	git__free(w);
}

struct object_entry_cb_state {
	git_repository *repo;
	git_odb *db;
	git_vector *commits;
};

static int object_entry__cb(const git_oid *id, void *data)
{
	struct object_entry_cb_state *state = (struct object_entry_cb_state *)data;
	git_commit *commit = NULL;
	struct packed_commit *packed_commit = NULL;
	size_t header_len;
	git_object_t header_type;
	int error = 0;

	error = git_odb_read_header(&header_len, &header_type, state->db, id);
	if (error < 0)
		return error;

	if (header_type != GIT_OBJECT_COMMIT)
		return 0;

	error = git_commit_lookup(&commit, state->repo, id);
	if (error < 0)
		return error;

	packed_commit = packed_commit_new(commit);
	git_commit_free(commit);
	GIT_ERROR_CHECK_ALLOC(packed_commit);

	error = git_vector_insert(state->commits, packed_commit);
	if (error < 0) {
		packed_commit_free(packed_commit);
		return error;
	}

	return 0;
}

int git_commit_graph_writer_add_index_file(
		git_commit_graph_writer *w,
		git_repository *repo,
		const char *idx_path)
{
	int error;
	struct git_pack_file *p = NULL;
lhchavez committed
721 722 723
	struct object_entry_cb_state state = {0};
	state.repo = repo;
	state.commits = &w->commits;
724 725 726 727 728

	error = git_repository_odb(&state.db, repo);
	if (error < 0)
		goto cleanup;

729 730
	/* TODO: SHA256 */
	error = git_mwindow_get_pack(&p, idx_path, 0);
731 732 733 734 735 736 737 738
	if (error < 0)
		goto cleanup;

	error = git_pack_foreach_entry(p, object_entry__cb, &state);
	if (error < 0)
		goto cleanup;

cleanup:
739 740
	if (p)
		git_mwindow_put_pack(p);
741 742 743 744 745 746 747 748 749 750
	git_odb_free(state.db);
	return error;
}

int git_commit_graph_writer_add_revwalk(git_commit_graph_writer *w, git_revwalk *walk)
{
	int error;
	git_oid id;
	git_repository *repo = git_revwalk_repository(walk);
	git_commit *commit;
751
	struct packed_commit *packed_commit;
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775

	while ((git_revwalk_next(&id, walk)) == 0) {
		error = git_commit_lookup(&commit, repo, &id);
		if (error < 0)
			return error;

		packed_commit = packed_commit_new(commit);
		git_commit_free(commit);
		GIT_ERROR_CHECK_ALLOC(packed_commit);

		error = git_vector_insert(&w->commits, packed_commit);
		if (error < 0) {
			packed_commit_free(packed_commit);
			return error;
		}
	}

	return 0;
}

enum generation_number_commit_state {
	GENERATION_NUMBER_COMMIT_STATE_UNVISITED = 0,
	GENERATION_NUMBER_COMMIT_STATE_ADDED = 1,
	GENERATION_NUMBER_COMMIT_STATE_EXPANDED = 2,
776
	GENERATION_NUMBER_COMMIT_STATE_VISITED = 3
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
};

static int compute_generation_numbers(git_vector *commits)
{
	git_array_t(size_t) index_stack = GIT_ARRAY_INIT;
	size_t i, j;
	size_t *parent_idx;
	enum generation_number_commit_state *commit_states = NULL;
	struct packed_commit *child_packed_commit;
	git_oidmap *packed_commit_map = NULL;
	int error = 0;

	/* First populate the parent indices fields */
	error = git_oidmap_new(&packed_commit_map);
	if (error < 0)
		goto cleanup;
	git_vector_foreach (commits, i, child_packed_commit) {
		child_packed_commit->index = i;
		error = git_oidmap_set(
				packed_commit_map, &child_packed_commit->sha1, child_packed_commit);
		if (error < 0)
			goto cleanup;
	}

	git_vector_foreach (commits, i, child_packed_commit) {
		size_t parent_i, *parent_idx_ptr;
		struct packed_commit *parent_packed_commit;
		git_oid *parent_id;
		git_array_init_to_size(
				child_packed_commit->parent_indices,
				git_array_size(child_packed_commit->parents));
		if (git_array_size(child_packed_commit->parents)
		    && !child_packed_commit->parent_indices.ptr) {
			error = -1;
			goto cleanup;
		}
		git_array_foreach (child_packed_commit->parents, parent_i, parent_id) {
			parent_packed_commit = git_oidmap_get(packed_commit_map, parent_id);
			if (!parent_packed_commit) {
				git_error_set(GIT_ERROR_ODB,
					      "parent commit %s not found in commit graph",
					      git_oid_tostr_s(parent_id));
				error = GIT_ENOTFOUND;
				goto cleanup;
			}
			parent_idx_ptr = git_array_alloc(child_packed_commit->parent_indices);
			if (!parent_idx_ptr) {
				error = -1;
				goto cleanup;
			}
			*parent_idx_ptr = parent_packed_commit->index;
		}
	}

	/*
	 * We copy all the commits to the stack and then during visitation,
	 * each node can be added up to two times to the stack.
	 */
	git_array_init_to_size(index_stack, 3 * git_vector_length(commits));
	if (!index_stack.ptr) {
		error = -1;
		goto cleanup;
	}

	commit_states = (enum generation_number_commit_state *)git__calloc(
			git_vector_length(commits), sizeof(enum generation_number_commit_state));
	if (!commit_states) {
		error = -1;
		goto cleanup;
	}

	/*
	 * Perform a Post-Order traversal so that all parent nodes are fully
	 * visited before the child node.
	 */
	git_vector_foreach (commits, i, child_packed_commit)
		*(size_t *)git_array_alloc(index_stack) = i;

	while (git_array_size(index_stack)) {
856 857
		size_t *index_ptr = git_array_pop(index_stack);
		i = *index_ptr;
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
		child_packed_commit = git_vector_get(commits, i);

		if (commit_states[i] == GENERATION_NUMBER_COMMIT_STATE_VISITED) {
			/* This commit has already been fully visited. */
			continue;
		}
		if (commit_states[i] == GENERATION_NUMBER_COMMIT_STATE_EXPANDED) {
			/* All of the commits parents have been visited. */
			child_packed_commit->generation = 0;
			git_array_foreach (child_packed_commit->parent_indices, j, parent_idx) {
				struct packed_commit *parent = git_vector_get(commits, *parent_idx);
				if (child_packed_commit->generation < parent->generation)
					child_packed_commit->generation = parent->generation;
			}
			if (child_packed_commit->generation
			    < GIT_COMMIT_GRAPH_GENERATION_NUMBER_MAX) {
				++child_packed_commit->generation;
			}
			commit_states[i] = GENERATION_NUMBER_COMMIT_STATE_VISITED;
			continue;
		}

		/*
		 * This is the first time we see this commit. We need
		 * to visit all its parents before we can fully visit
		 * it.
		 */
		if (git_array_size(child_packed_commit->parent_indices) == 0) {
			/*
			 * Special case: if the commit has no parents, there's
			 * no need to add it to the stack just to immediately
			 * remove it.
			 */
			commit_states[i] = GENERATION_NUMBER_COMMIT_STATE_VISITED;
			child_packed_commit->generation = 1;
			continue;
		}

		/*
		 * Add this current commit again so that it is visited
		 * again once all its children have been visited.
		 */
		*(size_t *)git_array_alloc(index_stack) = i;
		git_array_foreach (child_packed_commit->parent_indices, j, parent_idx) {
			if (commit_states[*parent_idx]
			    != GENERATION_NUMBER_COMMIT_STATE_UNVISITED) {
				/* This commit has already been considered. */
				continue;
			}

			commit_states[*parent_idx] = GENERATION_NUMBER_COMMIT_STATE_ADDED;
			*(size_t *)git_array_alloc(index_stack) = *parent_idx;
		}
		commit_states[i] = GENERATION_NUMBER_COMMIT_STATE_EXPANDED;
	}

cleanup:
	git_oidmap_free(packed_commit_map);
	git__free(commit_states);
	git_array_clear(index_stack);

	return error;
}

static int write_offset(off64_t offset, commit_graph_write_cb write_cb, void *cb_data)
{
	int error;
	uint32_t word;

	word = htonl((uint32_t)((offset >> 32) & 0xffffffffu));
	error = write_cb((const char *)&word, sizeof(word), cb_data);
	if (error < 0)
		return error;
	word = htonl((uint32_t)((offset >> 0) & 0xffffffffu));
	error = write_cb((const char *)&word, sizeof(word), cb_data);
	if (error < 0)
		return error;

	return 0;
}

939 940 941 942 943
static int write_chunk_header(
		int chunk_id,
		off64_t offset,
		commit_graph_write_cb write_cb,
		void *cb_data)
944 945 946 947 948 949 950 951 952 953
{
	uint32_t word = htonl(chunk_id);
	int error = write_cb((const char *)&word, sizeof(word), cb_data);
	if (error < 0)
		return error;
	return write_offset(offset, write_cb, cb_data);
}

static int commit_graph_write_buf(const char *buf, size_t size, void *data)
{
954 955
	git_str *b = (git_str *)data;
	return git_str_put(b, buf, size);
956 957 958 959 960 961 962 963 964 965
}

struct commit_graph_write_hash_context {
	commit_graph_write_cb write_cb;
	void *cb_data;
	git_hash_ctx *ctx;
};

static int commit_graph_write_hash(const char *buf, size_t size, void *data)
{
lhchavez committed
966
	struct commit_graph_write_hash_context *ctx = data;
967 968 969 970 971 972 973 974 975 976 977 978 979 980
	int error;

	error = git_hash_update(ctx->ctx, buf, size);
	if (error < 0)
		return error;

	return ctx->write_cb(buf, size, ctx->cb_data);
}

static void packed_commit_free_dup(void *packed_commit)
{
	packed_commit_free(packed_commit);
}

981 982 983 984
static int commit_graph_write(
		git_commit_graph_writer *w,
		commit_graph_write_cb write_cb,
		void *cb_data)
985 986 987 988
{
	int error = 0;
	size_t i;
	struct packed_commit *packed_commit;
lhchavez committed
989
	struct git_commit_graph_header hdr = {0};
990 991 992 993
	uint32_t oid_fanout_count;
	uint32_t extra_edge_list_count;
	uint32_t oid_fanout[256];
	off64_t offset;
994 995
	git_str oid_lookup = GIT_STR_INIT, commit_data = GIT_STR_INIT,
		extra_edge_list = GIT_STR_INIT;
996 997
	unsigned char checksum[GIT_HASH_SHA1_SIZE];
	size_t checksum_size;
998
	git_hash_ctx ctx;
lhchavez committed
999 1000 1001 1002 1003 1004 1005 1006 1007 1008
	struct commit_graph_write_hash_context hash_cb_data = {0};

	hdr.signature = htonl(COMMIT_GRAPH_SIGNATURE);
	hdr.version = COMMIT_GRAPH_VERSION;
	hdr.object_id_version = COMMIT_GRAPH_OBJECT_ID_VERSION;
	hdr.chunks = 0;
	hdr.base_graph_files = 0;
	hash_cb_data.write_cb = write_cb;
	hash_cb_data.cb_data = cb_data;
	hash_cb_data.ctx = &ctx;
1009

1010
	checksum_size = GIT_HASH_SHA1_SIZE;
1011
	error = git_hash_ctx_init(&ctx, GIT_HASH_ALGORITHM_SHA1);
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
	if (error < 0)
		return error;
	cb_data = &hash_cb_data;
	write_cb = commit_graph_write_hash;

	/* Sort the commits. */
	git_vector_sort(&w->commits);
	git_vector_uniq(&w->commits, packed_commit_free_dup);
	error = compute_generation_numbers(&w->commits);
	if (error < 0)
		goto cleanup;

	/* Fill the OID Fanout table. */
	oid_fanout_count = 0;
	for (i = 0; i < 256; i++) {
1027 1028 1029
		while (oid_fanout_count < git_vector_length(&w->commits) &&
		       (packed_commit = (struct packed_commit *)git_vector_get(&w->commits, oid_fanout_count)) &&
		       packed_commit->sha1.id[0] <= i)
1030 1031 1032 1033 1034 1035
			++oid_fanout_count;
		oid_fanout[i] = htonl(oid_fanout_count);
	}

	/* Fill the OID Lookup table. */
	git_vector_foreach (&w->commits, i, packed_commit) {
1036
		error = git_str_put(&oid_lookup,
1037
			(const char *)&packed_commit->sha1.id,
1038
			GIT_OID_SHA1_SIZE);
1039

1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
		if (error < 0)
			goto cleanup;
	}

	/* Fill the Commit Data and Extra Edge List tables. */
	extra_edge_list_count = 0;
	git_vector_foreach (&w->commits, i, packed_commit) {
		uint64_t commit_time;
		uint32_t generation;
		uint32_t word;
1050
		size_t *packed_index;
1051 1052
		unsigned int parentcount = (unsigned int)git_array_size(packed_commit->parents);

1053
		error = git_str_put(&commit_data,
1054
			(const char *)&packed_commit->tree_oid.id,
1055
			GIT_OID_SHA1_SIZE);
1056

1057 1058 1059
		if (error < 0)
			goto cleanup;

1060
		if (parentcount == 0) {
1061
			word = htonl(GIT_COMMIT_GRAPH_MISSING_PARENT);
1062 1063 1064 1065
		} else {
			packed_index = git_array_get(packed_commit->parent_indices, 0);
			word = htonl((uint32_t)*packed_index);
		}
1066
		error = git_str_put(&commit_data, (const char *)&word, sizeof(word));
1067 1068 1069
		if (error < 0)
			goto cleanup;

1070
		if (parentcount < 2) {
1071
			word = htonl(GIT_COMMIT_GRAPH_MISSING_PARENT);
1072 1073 1074 1075
		} else if (parentcount == 2) {
			packed_index = git_array_get(packed_commit->parent_indices, 1);
			word = htonl((uint32_t)*packed_index);
		} else {
1076
			word = htonl(0x80000000u | extra_edge_list_count);
1077
		}
1078
		error = git_str_put(&commit_data, (const char *)&word, sizeof(word));
1079 1080 1081 1082 1083 1084
		if (error < 0)
			goto cleanup;

		if (parentcount > 2) {
			unsigned int parent_i;
			for (parent_i = 1; parent_i < parentcount; ++parent_i) {
1085
				packed_index = git_array_get(
1086 1087 1088
					packed_commit->parent_indices, parent_i);
				word = htonl((uint32_t)(*packed_index | (parent_i + 1 == parentcount ? 0x80000000u : 0)));

1089
				error = git_str_put(&extra_edge_list,
lhchavez committed
1090 1091
						(const char *)&word,
						sizeof(word));
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
				if (error < 0)
					goto cleanup;
			}
			extra_edge_list_count += parentcount - 1;
		}

		generation = packed_commit->generation;
		commit_time = (uint64_t)packed_commit->commit_time;
		if (generation > GIT_COMMIT_GRAPH_GENERATION_NUMBER_MAX)
			generation = GIT_COMMIT_GRAPH_GENERATION_NUMBER_MAX;
1102
		word = ntohl((uint32_t)((generation << 2) | (((uint32_t)(commit_time >> 32)) & 0x3) ));
1103
		error = git_str_put(&commit_data, (const char *)&word, sizeof(word));
1104 1105
		if (error < 0)
			goto cleanup;
1106
		word = ntohl((uint32_t)(commit_time & 0xfffffffful));
1107
		error = git_str_put(&commit_data, (const char *)&word, sizeof(word));
1108 1109 1110 1111 1112 1113
		if (error < 0)
			goto cleanup;
	}

	/* Write the header. */
	hdr.chunks = 3;
1114
	if (git_str_len(&extra_edge_list) > 0)
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
		hdr.chunks++;
	error = write_cb((const char *)&hdr, sizeof(hdr), cb_data);
	if (error < 0)
		goto cleanup;

	/* Write the chunk headers. */
	offset = sizeof(hdr) + (hdr.chunks + 1) * 12;
	error = write_chunk_header(COMMIT_GRAPH_OID_FANOUT_ID, offset, write_cb, cb_data);
	if (error < 0)
		goto cleanup;
	offset += sizeof(oid_fanout);
	error = write_chunk_header(COMMIT_GRAPH_OID_LOOKUP_ID, offset, write_cb, cb_data);
	if (error < 0)
		goto cleanup;
1129
	offset += git_str_len(&oid_lookup);
1130 1131 1132
	error = write_chunk_header(COMMIT_GRAPH_COMMIT_DATA_ID, offset, write_cb, cb_data);
	if (error < 0)
		goto cleanup;
1133 1134
	offset += git_str_len(&commit_data);
	if (git_str_len(&extra_edge_list) > 0) {
1135 1136 1137 1138
		error = write_chunk_header(
				COMMIT_GRAPH_EXTRA_EDGE_LIST_ID, offset, write_cb, cb_data);
		if (error < 0)
			goto cleanup;
1139
		offset += git_str_len(&extra_edge_list);
1140 1141 1142 1143 1144 1145 1146 1147 1148
	}
	error = write_chunk_header(0, offset, write_cb, cb_data);
	if (error < 0)
		goto cleanup;

	/* Write all the chunks. */
	error = write_cb((const char *)oid_fanout, sizeof(oid_fanout), cb_data);
	if (error < 0)
		goto cleanup;
1149
	error = write_cb(git_str_cstr(&oid_lookup), git_str_len(&oid_lookup), cb_data);
1150 1151
	if (error < 0)
		goto cleanup;
1152
	error = write_cb(git_str_cstr(&commit_data), git_str_len(&commit_data), cb_data);
1153 1154
	if (error < 0)
		goto cleanup;
1155
	error = write_cb(git_str_cstr(&extra_edge_list), git_str_len(&extra_edge_list), cb_data);
1156 1157 1158 1159
	if (error < 0)
		goto cleanup;

	/* Finalize the checksum and write the trailer. */
1160
	error = git_hash_final(checksum, &ctx);
1161 1162
	if (error < 0)
		goto cleanup;
1163
	error = write_cb((char *)checksum, checksum_size, cb_data);
1164 1165 1166 1167
	if (error < 0)
		goto cleanup;

cleanup:
1168 1169 1170
	git_str_dispose(&oid_lookup);
	git_str_dispose(&commit_data);
	git_str_dispose(&extra_edge_list);
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
	git_hash_ctx_cleanup(&ctx);
	return error;
}

static int commit_graph_write_filebuf(const char *buf, size_t size, void *data)
{
	git_filebuf *f = (git_filebuf *)data;
	return git_filebuf_write(f, buf, size);
}

1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
int git_commit_graph_writer_options_init(
	git_commit_graph_writer_options *opts,
	unsigned int version)
{
	GIT_INIT_STRUCTURE_FROM_TEMPLATE(
			opts,
			version,
			git_commit_graph_writer_options,
			GIT_COMMIT_GRAPH_WRITER_OPTIONS_INIT);
	return 0;
}

1193 1194 1195 1196 1197 1198
int git_commit_graph_writer_commit(
		git_commit_graph_writer *w,
		git_commit_graph_writer_options *opts)
{
	int error;
	int filebuf_flags = GIT_FILEBUF_DO_NOT_BUFFER;
1199
	git_str commit_graph_path = GIT_STR_INIT;
1200 1201
	git_filebuf output = GIT_FILEBUF_INIT;

1202
	/* TODO: support options and fill in defaults. */
1203 1204
	GIT_UNUSED(opts);

1205 1206
	error = git_str_joinpath(
			&commit_graph_path, git_str_cstr(&w->objects_info_dir), "commit-graph");
1207 1208 1209 1210 1211
	if (error < 0)
		return error;

	if (git_repository__fsync_gitdir)
		filebuf_flags |= GIT_FILEBUF_FSYNC;
1212 1213
	error = git_filebuf_open(&output, git_str_cstr(&commit_graph_path), filebuf_flags, 0644);
	git_str_dispose(&commit_graph_path);
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
	if (error < 0)
		return error;

	error = commit_graph_write(w, commit_graph_write_filebuf, &output);
	if (error < 0) {
		git_filebuf_cleanup(&output);
		return error;
	}

	return git_filebuf_commit(&output);
}

int git_commit_graph_writer_dump(
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
	git_buf *cgraph,
	git_commit_graph_writer *w,
	git_commit_graph_writer_options *opts)
{
	GIT_BUF_WRAP_PRIVATE(cgraph, git_commit_graph__writer_dump, w, opts);
}

int git_commit_graph__writer_dump(
	git_str *cgraph,
	git_commit_graph_writer *w,
	git_commit_graph_writer_options *opts)
1238
{
lhchavez committed
1239
	/* TODO: support options. */
1240 1241 1242
	GIT_UNUSED(opts);
	return commit_graph_write(w, commit_graph_write_buf, cgraph);
}