##// END OF EJS Templates
parsers: fix parse_dirstate to check len before unpacking header (issue4979)
Yuya Nishihara -
r27226:f5e8cb81 stable
parent child Browse files
Show More
@@ -1,2843 +1,2848 b''
1 1 /*
2 2 parsers.c - efficient content parsing
3 3
4 4 Copyright 2008 Matt Mackall <mpm@selenic.com> and others
5 5
6 6 This software may be used and distributed according to the terms of
7 7 the GNU General Public License, incorporated herein by reference.
8 8 */
9 9
10 10 #include <Python.h>
11 11 #include <ctype.h>
12 12 #include <stddef.h>
13 13 #include <string.h>
14 14
15 15 #include "util.h"
16 16
17 17 static char *versionerrortext = "Python minor version mismatch";
18 18
19 19 static int8_t hextable[256] = {
20 20 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
21 21 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
22 22 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
23 23 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, /* 0-9 */
24 24 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* A-F */
25 25 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
26 26 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* a-f */
27 27 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
28 28 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
29 29 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
30 30 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
31 31 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
32 32 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
33 33 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
34 34 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
35 35 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
36 36 };
37 37
38 38 static char lowertable[128] = {
39 39 '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
40 40 '\x08', '\x09', '\x0a', '\x0b', '\x0c', '\x0d', '\x0e', '\x0f',
41 41 '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17',
42 42 '\x18', '\x19', '\x1a', '\x1b', '\x1c', '\x1d', '\x1e', '\x1f',
43 43 '\x20', '\x21', '\x22', '\x23', '\x24', '\x25', '\x26', '\x27',
44 44 '\x28', '\x29', '\x2a', '\x2b', '\x2c', '\x2d', '\x2e', '\x2f',
45 45 '\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37',
46 46 '\x38', '\x39', '\x3a', '\x3b', '\x3c', '\x3d', '\x3e', '\x3f',
47 47 '\x40',
48 48 '\x61', '\x62', '\x63', '\x64', '\x65', '\x66', '\x67', /* A-G */
49 49 '\x68', '\x69', '\x6a', '\x6b', '\x6c', '\x6d', '\x6e', '\x6f', /* H-O */
50 50 '\x70', '\x71', '\x72', '\x73', '\x74', '\x75', '\x76', '\x77', /* P-W */
51 51 '\x78', '\x79', '\x7a', /* X-Z */
52 52 '\x5b', '\x5c', '\x5d', '\x5e', '\x5f',
53 53 '\x60', '\x61', '\x62', '\x63', '\x64', '\x65', '\x66', '\x67',
54 54 '\x68', '\x69', '\x6a', '\x6b', '\x6c', '\x6d', '\x6e', '\x6f',
55 55 '\x70', '\x71', '\x72', '\x73', '\x74', '\x75', '\x76', '\x77',
56 56 '\x78', '\x79', '\x7a', '\x7b', '\x7c', '\x7d', '\x7e', '\x7f'
57 57 };
58 58
59 59 static char uppertable[128] = {
60 60 '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
61 61 '\x08', '\x09', '\x0a', '\x0b', '\x0c', '\x0d', '\x0e', '\x0f',
62 62 '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17',
63 63 '\x18', '\x19', '\x1a', '\x1b', '\x1c', '\x1d', '\x1e', '\x1f',
64 64 '\x20', '\x21', '\x22', '\x23', '\x24', '\x25', '\x26', '\x27',
65 65 '\x28', '\x29', '\x2a', '\x2b', '\x2c', '\x2d', '\x2e', '\x2f',
66 66 '\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37',
67 67 '\x38', '\x39', '\x3a', '\x3b', '\x3c', '\x3d', '\x3e', '\x3f',
68 68 '\x40', '\x41', '\x42', '\x43', '\x44', '\x45', '\x46', '\x47',
69 69 '\x48', '\x49', '\x4a', '\x4b', '\x4c', '\x4d', '\x4e', '\x4f',
70 70 '\x50', '\x51', '\x52', '\x53', '\x54', '\x55', '\x56', '\x57',
71 71 '\x58', '\x59', '\x5a', '\x5b', '\x5c', '\x5d', '\x5e', '\x5f',
72 72 '\x60',
73 73 '\x41', '\x42', '\x43', '\x44', '\x45', '\x46', '\x47', /* a-g */
74 74 '\x48', '\x49', '\x4a', '\x4b', '\x4c', '\x4d', '\x4e', '\x4f', /* h-o */
75 75 '\x50', '\x51', '\x52', '\x53', '\x54', '\x55', '\x56', '\x57', /* p-w */
76 76 '\x58', '\x59', '\x5a', /* x-z */
77 77 '\x7b', '\x7c', '\x7d', '\x7e', '\x7f'
78 78 };
79 79
80 80 static inline int hexdigit(const char *p, Py_ssize_t off)
81 81 {
82 82 int8_t val = hextable[(unsigned char)p[off]];
83 83
84 84 if (val >= 0) {
85 85 return val;
86 86 }
87 87
88 88 PyErr_SetString(PyExc_ValueError, "input contains non-hex character");
89 89 return 0;
90 90 }
91 91
92 92 /*
93 93 * Turn a hex-encoded string into binary.
94 94 */
95 95 PyObject *unhexlify(const char *str, int len)
96 96 {
97 97 PyObject *ret;
98 98 char *d;
99 99 int i;
100 100
101 101 ret = PyBytes_FromStringAndSize(NULL, len / 2);
102 102
103 103 if (!ret)
104 104 return NULL;
105 105
106 106 d = PyBytes_AsString(ret);
107 107
108 108 for (i = 0; i < len;) {
109 109 int hi = hexdigit(str, i++);
110 110 int lo = hexdigit(str, i++);
111 111 *d++ = (hi << 4) | lo;
112 112 }
113 113
114 114 return ret;
115 115 }
116 116
117 117 static inline PyObject *_asciitransform(PyObject *str_obj,
118 118 const char table[128],
119 119 PyObject *fallback_fn)
120 120 {
121 121 char *str, *newstr;
122 122 Py_ssize_t i, len;
123 123 PyObject *newobj = NULL;
124 124 PyObject *ret = NULL;
125 125
126 126 str = PyBytes_AS_STRING(str_obj);
127 127 len = PyBytes_GET_SIZE(str_obj);
128 128
129 129 newobj = PyBytes_FromStringAndSize(NULL, len);
130 130 if (!newobj)
131 131 goto quit;
132 132
133 133 newstr = PyBytes_AS_STRING(newobj);
134 134
135 135 for (i = 0; i < len; i++) {
136 136 char c = str[i];
137 137 if (c & 0x80) {
138 138 if (fallback_fn != NULL) {
139 139 ret = PyObject_CallFunctionObjArgs(fallback_fn,
140 140 str_obj, NULL);
141 141 } else {
142 142 PyObject *err = PyUnicodeDecodeError_Create(
143 143 "ascii", str, len, i, (i + 1),
144 144 "unexpected code byte");
145 145 PyErr_SetObject(PyExc_UnicodeDecodeError, err);
146 146 Py_XDECREF(err);
147 147 }
148 148 goto quit;
149 149 }
150 150 newstr[i] = table[(unsigned char)c];
151 151 }
152 152
153 153 ret = newobj;
154 154 Py_INCREF(ret);
155 155 quit:
156 156 Py_XDECREF(newobj);
157 157 return ret;
158 158 }
159 159
160 160 static PyObject *asciilower(PyObject *self, PyObject *args)
161 161 {
162 162 PyObject *str_obj;
163 163 if (!PyArg_ParseTuple(args, "O!:asciilower", &PyBytes_Type, &str_obj))
164 164 return NULL;
165 165 return _asciitransform(str_obj, lowertable, NULL);
166 166 }
167 167
168 168 static PyObject *asciiupper(PyObject *self, PyObject *args)
169 169 {
170 170 PyObject *str_obj;
171 171 if (!PyArg_ParseTuple(args, "O!:asciiupper", &PyBytes_Type, &str_obj))
172 172 return NULL;
173 173 return _asciitransform(str_obj, uppertable, NULL);
174 174 }
175 175
176 176 static inline PyObject *_dict_new_presized(Py_ssize_t expected_size)
177 177 {
178 178 /* _PyDict_NewPresized expects a minused parameter, but it actually
179 179 creates a dictionary that's the nearest power of two bigger than the
180 180 parameter. For example, with the initial minused = 1000, the
181 181 dictionary created has size 1024. Of course in a lot of cases that
182 182 can be greater than the maximum load factor Python's dict object
183 183 expects (= 2/3), so as soon as we cross the threshold we'll resize
184 184 anyway. So create a dictionary that's at least 3/2 the size. */
185 185 return _PyDict_NewPresized(((1 + expected_size) / 2) * 3);
186 186 }
187 187
188 188 static PyObject *dict_new_presized(PyObject *self, PyObject *args)
189 189 {
190 190 Py_ssize_t expected_size;
191 191
192 192 if (!PyArg_ParseTuple(args, "n:make_presized_dict", &expected_size))
193 193 return NULL;
194 194
195 195 return _dict_new_presized(expected_size);
196 196 }
197 197
198 198 static PyObject *make_file_foldmap(PyObject *self, PyObject *args)
199 199 {
200 200 PyObject *dmap, *spec_obj, *normcase_fallback;
201 201 PyObject *file_foldmap = NULL;
202 202 enum normcase_spec spec;
203 203 PyObject *k, *v;
204 204 dirstateTupleObject *tuple;
205 205 Py_ssize_t pos = 0;
206 206 const char *table;
207 207
208 208 if (!PyArg_ParseTuple(args, "O!O!O!:make_file_foldmap",
209 209 &PyDict_Type, &dmap,
210 210 &PyInt_Type, &spec_obj,
211 211 &PyFunction_Type, &normcase_fallback))
212 212 goto quit;
213 213
214 214 spec = (int)PyInt_AS_LONG(spec_obj);
215 215 switch (spec) {
216 216 case NORMCASE_LOWER:
217 217 table = lowertable;
218 218 break;
219 219 case NORMCASE_UPPER:
220 220 table = uppertable;
221 221 break;
222 222 case NORMCASE_OTHER:
223 223 table = NULL;
224 224 break;
225 225 default:
226 226 PyErr_SetString(PyExc_TypeError, "invalid normcasespec");
227 227 goto quit;
228 228 }
229 229
230 230 /* Add some more entries to deal with additions outside this
231 231 function. */
232 232 file_foldmap = _dict_new_presized((PyDict_Size(dmap) / 10) * 11);
233 233 if (file_foldmap == NULL)
234 234 goto quit;
235 235
236 236 while (PyDict_Next(dmap, &pos, &k, &v)) {
237 237 if (!dirstate_tuple_check(v)) {
238 238 PyErr_SetString(PyExc_TypeError,
239 239 "expected a dirstate tuple");
240 240 goto quit;
241 241 }
242 242
243 243 tuple = (dirstateTupleObject *)v;
244 244 if (tuple->state != 'r') {
245 245 PyObject *normed;
246 246 if (table != NULL) {
247 247 normed = _asciitransform(k, table,
248 248 normcase_fallback);
249 249 } else {
250 250 normed = PyObject_CallFunctionObjArgs(
251 251 normcase_fallback, k, NULL);
252 252 }
253 253
254 254 if (normed == NULL)
255 255 goto quit;
256 256 if (PyDict_SetItem(file_foldmap, normed, k) == -1) {
257 257 Py_DECREF(normed);
258 258 goto quit;
259 259 }
260 260 Py_DECREF(normed);
261 261 }
262 262 }
263 263 return file_foldmap;
264 264 quit:
265 265 Py_XDECREF(file_foldmap);
266 266 return NULL;
267 267 }
268 268
269 269 /*
270 270 * This code assumes that a manifest is stitched together with newline
271 271 * ('\n') characters.
272 272 */
273 273 static PyObject *parse_manifest(PyObject *self, PyObject *args)
274 274 {
275 275 PyObject *mfdict, *fdict;
276 276 char *str, *start, *end;
277 277 int len;
278 278
279 279 if (!PyArg_ParseTuple(args, "O!O!s#:parse_manifest",
280 280 &PyDict_Type, &mfdict,
281 281 &PyDict_Type, &fdict,
282 282 &str, &len))
283 283 goto quit;
284 284
285 285 start = str;
286 286 end = str + len;
287 287 while (start < end) {
288 288 PyObject *file = NULL, *node = NULL;
289 289 PyObject *flags = NULL;
290 290 char *zero = NULL, *newline = NULL;
291 291 ptrdiff_t nlen;
292 292
293 293 zero = memchr(start, '\0', end - start);
294 294 if (!zero) {
295 295 PyErr_SetString(PyExc_ValueError,
296 296 "manifest entry has no separator");
297 297 goto quit;
298 298 }
299 299
300 300 newline = memchr(zero + 1, '\n', end - (zero + 1));
301 301 if (!newline) {
302 302 PyErr_SetString(PyExc_ValueError,
303 303 "manifest contains trailing garbage");
304 304 goto quit;
305 305 }
306 306
307 307 file = PyBytes_FromStringAndSize(start, zero - start);
308 308
309 309 if (!file)
310 310 goto bail;
311 311
312 312 nlen = newline - zero - 1;
313 313
314 314 node = unhexlify(zero + 1, nlen > 40 ? 40 : (int)nlen);
315 315 if (!node)
316 316 goto bail;
317 317
318 318 if (nlen > 40) {
319 319 flags = PyBytes_FromStringAndSize(zero + 41,
320 320 nlen - 40);
321 321 if (!flags)
322 322 goto bail;
323 323
324 324 if (PyDict_SetItem(fdict, file, flags) == -1)
325 325 goto bail;
326 326 }
327 327
328 328 if (PyDict_SetItem(mfdict, file, node) == -1)
329 329 goto bail;
330 330
331 331 start = newline + 1;
332 332
333 333 Py_XDECREF(flags);
334 334 Py_XDECREF(node);
335 335 Py_XDECREF(file);
336 336 continue;
337 337 bail:
338 338 Py_XDECREF(flags);
339 339 Py_XDECREF(node);
340 340 Py_XDECREF(file);
341 341 goto quit;
342 342 }
343 343
344 344 Py_INCREF(Py_None);
345 345 return Py_None;
346 346 quit:
347 347 return NULL;
348 348 }
349 349
350 350 static inline dirstateTupleObject *make_dirstate_tuple(char state, int mode,
351 351 int size, int mtime)
352 352 {
353 353 dirstateTupleObject *t = PyObject_New(dirstateTupleObject,
354 354 &dirstateTupleType);
355 355 if (!t)
356 356 return NULL;
357 357 t->state = state;
358 358 t->mode = mode;
359 359 t->size = size;
360 360 t->mtime = mtime;
361 361 return t;
362 362 }
363 363
364 364 static PyObject *dirstate_tuple_new(PyTypeObject *subtype, PyObject *args,
365 365 PyObject *kwds)
366 366 {
367 367 /* We do all the initialization here and not a tp_init function because
368 368 * dirstate_tuple is immutable. */
369 369 dirstateTupleObject *t;
370 370 char state;
371 371 int size, mode, mtime;
372 372 if (!PyArg_ParseTuple(args, "ciii", &state, &mode, &size, &mtime))
373 373 return NULL;
374 374
375 375 t = (dirstateTupleObject *)subtype->tp_alloc(subtype, 1);
376 376 if (!t)
377 377 return NULL;
378 378 t->state = state;
379 379 t->mode = mode;
380 380 t->size = size;
381 381 t->mtime = mtime;
382 382
383 383 return (PyObject *)t;
384 384 }
385 385
386 386 static void dirstate_tuple_dealloc(PyObject *o)
387 387 {
388 388 PyObject_Del(o);
389 389 }
390 390
391 391 static Py_ssize_t dirstate_tuple_length(PyObject *o)
392 392 {
393 393 return 4;
394 394 }
395 395
396 396 static PyObject *dirstate_tuple_item(PyObject *o, Py_ssize_t i)
397 397 {
398 398 dirstateTupleObject *t = (dirstateTupleObject *)o;
399 399 switch (i) {
400 400 case 0:
401 401 return PyBytes_FromStringAndSize(&t->state, 1);
402 402 case 1:
403 403 return PyInt_FromLong(t->mode);
404 404 case 2:
405 405 return PyInt_FromLong(t->size);
406 406 case 3:
407 407 return PyInt_FromLong(t->mtime);
408 408 default:
409 409 PyErr_SetString(PyExc_IndexError, "index out of range");
410 410 return NULL;
411 411 }
412 412 }
413 413
414 414 static PySequenceMethods dirstate_tuple_sq = {
415 415 dirstate_tuple_length, /* sq_length */
416 416 0, /* sq_concat */
417 417 0, /* sq_repeat */
418 418 dirstate_tuple_item, /* sq_item */
419 419 0, /* sq_ass_item */
420 420 0, /* sq_contains */
421 421 0, /* sq_inplace_concat */
422 422 0 /* sq_inplace_repeat */
423 423 };
424 424
425 425 PyTypeObject dirstateTupleType = {
426 426 PyVarObject_HEAD_INIT(NULL, 0)
427 427 "dirstate_tuple", /* tp_name */
428 428 sizeof(dirstateTupleObject),/* tp_basicsize */
429 429 0, /* tp_itemsize */
430 430 (destructor)dirstate_tuple_dealloc, /* tp_dealloc */
431 431 0, /* tp_print */
432 432 0, /* tp_getattr */
433 433 0, /* tp_setattr */
434 434 0, /* tp_compare */
435 435 0, /* tp_repr */
436 436 0, /* tp_as_number */
437 437 &dirstate_tuple_sq, /* tp_as_sequence */
438 438 0, /* tp_as_mapping */
439 439 0, /* tp_hash */
440 440 0, /* tp_call */
441 441 0, /* tp_str */
442 442 0, /* tp_getattro */
443 443 0, /* tp_setattro */
444 444 0, /* tp_as_buffer */
445 445 Py_TPFLAGS_DEFAULT, /* tp_flags */
446 446 "dirstate tuple", /* tp_doc */
447 447 0, /* tp_traverse */
448 448 0, /* tp_clear */
449 449 0, /* tp_richcompare */
450 450 0, /* tp_weaklistoffset */
451 451 0, /* tp_iter */
452 452 0, /* tp_iternext */
453 453 0, /* tp_methods */
454 454 0, /* tp_members */
455 455 0, /* tp_getset */
456 456 0, /* tp_base */
457 457 0, /* tp_dict */
458 458 0, /* tp_descr_get */
459 459 0, /* tp_descr_set */
460 460 0, /* tp_dictoffset */
461 461 0, /* tp_init */
462 462 0, /* tp_alloc */
463 463 dirstate_tuple_new, /* tp_new */
464 464 };
465 465
466 466 static PyObject *parse_dirstate(PyObject *self, PyObject *args)
467 467 {
468 468 PyObject *dmap, *cmap, *parents = NULL, *ret = NULL;
469 469 PyObject *fname = NULL, *cname = NULL, *entry = NULL;
470 470 char state, *cur, *str, *cpos;
471 471 int mode, size, mtime;
472 472 unsigned int flen, len, pos = 40;
473 473 int readlen;
474 474
475 475 if (!PyArg_ParseTuple(args, "O!O!s#:parse_dirstate",
476 476 &PyDict_Type, &dmap,
477 477 &PyDict_Type, &cmap,
478 478 &str, &readlen))
479 479 goto quit;
480 480
481 481 len = readlen;
482 482
483 483 /* read parents */
484 484 if (len < 40) {
485 485 PyErr_SetString(
486 486 PyExc_ValueError, "too little data for parents");
487 487 goto quit;
488 488 }
489 489
490 490 parents = Py_BuildValue("s#s#", str, 20, str + 20, 20);
491 491 if (!parents)
492 492 goto quit;
493 493
494 494 /* read filenames */
495 495 while (pos >= 40 && pos < len) {
496 if (pos + 17 > len) {
497 PyErr_SetString(PyExc_ValueError,
498 "overflow in dirstate");
499 goto quit;
500 }
496 501 cur = str + pos;
497 502 /* unpack header */
498 503 state = *cur;
499 504 mode = getbe32(cur + 1);
500 505 size = getbe32(cur + 5);
501 506 mtime = getbe32(cur + 9);
502 507 flen = getbe32(cur + 13);
503 508 pos += 17;
504 509 cur += 17;
505 510 if (flen > len - pos) {
506 511 PyErr_SetString(PyExc_ValueError, "overflow in dirstate");
507 512 goto quit;
508 513 }
509 514
510 515 entry = (PyObject *)make_dirstate_tuple(state, mode, size,
511 516 mtime);
512 517 cpos = memchr(cur, 0, flen);
513 518 if (cpos) {
514 519 fname = PyBytes_FromStringAndSize(cur, cpos - cur);
515 520 cname = PyBytes_FromStringAndSize(cpos + 1,
516 521 flen - (cpos - cur) - 1);
517 522 if (!fname || !cname ||
518 523 PyDict_SetItem(cmap, fname, cname) == -1 ||
519 524 PyDict_SetItem(dmap, fname, entry) == -1)
520 525 goto quit;
521 526 Py_DECREF(cname);
522 527 } else {
523 528 fname = PyBytes_FromStringAndSize(cur, flen);
524 529 if (!fname ||
525 530 PyDict_SetItem(dmap, fname, entry) == -1)
526 531 goto quit;
527 532 }
528 533 Py_DECREF(fname);
529 534 Py_DECREF(entry);
530 535 fname = cname = entry = NULL;
531 536 pos += flen;
532 537 }
533 538
534 539 ret = parents;
535 540 Py_INCREF(ret);
536 541 quit:
537 542 Py_XDECREF(fname);
538 543 Py_XDECREF(cname);
539 544 Py_XDECREF(entry);
540 545 Py_XDECREF(parents);
541 546 return ret;
542 547 }
543 548
544 549 /*
545 550 * Efficiently pack a dirstate object into its on-disk format.
546 551 */
547 552 static PyObject *pack_dirstate(PyObject *self, PyObject *args)
548 553 {
549 554 PyObject *packobj = NULL;
550 555 PyObject *map, *copymap, *pl, *mtime_unset = NULL;
551 556 Py_ssize_t nbytes, pos, l;
552 557 PyObject *k, *v = NULL, *pn;
553 558 char *p, *s;
554 559 int now;
555 560
556 561 if (!PyArg_ParseTuple(args, "O!O!Oi:pack_dirstate",
557 562 &PyDict_Type, &map, &PyDict_Type, &copymap,
558 563 &pl, &now))
559 564 return NULL;
560 565
561 566 if (!PySequence_Check(pl) || PySequence_Size(pl) != 2) {
562 567 PyErr_SetString(PyExc_TypeError, "expected 2-element sequence");
563 568 return NULL;
564 569 }
565 570
566 571 /* Figure out how much we need to allocate. */
567 572 for (nbytes = 40, pos = 0; PyDict_Next(map, &pos, &k, &v);) {
568 573 PyObject *c;
569 574 if (!PyString_Check(k)) {
570 575 PyErr_SetString(PyExc_TypeError, "expected string key");
571 576 goto bail;
572 577 }
573 578 nbytes += PyString_GET_SIZE(k) + 17;
574 579 c = PyDict_GetItem(copymap, k);
575 580 if (c) {
576 581 if (!PyString_Check(c)) {
577 582 PyErr_SetString(PyExc_TypeError,
578 583 "expected string key");
579 584 goto bail;
580 585 }
581 586 nbytes += PyString_GET_SIZE(c) + 1;
582 587 }
583 588 }
584 589
585 590 packobj = PyString_FromStringAndSize(NULL, nbytes);
586 591 if (packobj == NULL)
587 592 goto bail;
588 593
589 594 p = PyString_AS_STRING(packobj);
590 595
591 596 pn = PySequence_ITEM(pl, 0);
592 597 if (PyString_AsStringAndSize(pn, &s, &l) == -1 || l != 20) {
593 598 PyErr_SetString(PyExc_TypeError, "expected a 20-byte hash");
594 599 goto bail;
595 600 }
596 601 memcpy(p, s, l);
597 602 p += 20;
598 603 pn = PySequence_ITEM(pl, 1);
599 604 if (PyString_AsStringAndSize(pn, &s, &l) == -1 || l != 20) {
600 605 PyErr_SetString(PyExc_TypeError, "expected a 20-byte hash");
601 606 goto bail;
602 607 }
603 608 memcpy(p, s, l);
604 609 p += 20;
605 610
606 611 for (pos = 0; PyDict_Next(map, &pos, &k, &v); ) {
607 612 dirstateTupleObject *tuple;
608 613 char state;
609 614 int mode, size, mtime;
610 615 Py_ssize_t len, l;
611 616 PyObject *o;
612 617 char *t;
613 618
614 619 if (!dirstate_tuple_check(v)) {
615 620 PyErr_SetString(PyExc_TypeError,
616 621 "expected a dirstate tuple");
617 622 goto bail;
618 623 }
619 624 tuple = (dirstateTupleObject *)v;
620 625
621 626 state = tuple->state;
622 627 mode = tuple->mode;
623 628 size = tuple->size;
624 629 mtime = tuple->mtime;
625 630 if (state == 'n' && mtime == now) {
626 631 /* See pure/parsers.py:pack_dirstate for why we do
627 632 * this. */
628 633 mtime = -1;
629 634 mtime_unset = (PyObject *)make_dirstate_tuple(
630 635 state, mode, size, mtime);
631 636 if (!mtime_unset)
632 637 goto bail;
633 638 if (PyDict_SetItem(map, k, mtime_unset) == -1)
634 639 goto bail;
635 640 Py_DECREF(mtime_unset);
636 641 mtime_unset = NULL;
637 642 }
638 643 *p++ = state;
639 644 putbe32((uint32_t)mode, p);
640 645 putbe32((uint32_t)size, p + 4);
641 646 putbe32((uint32_t)mtime, p + 8);
642 647 t = p + 12;
643 648 p += 16;
644 649 len = PyString_GET_SIZE(k);
645 650 memcpy(p, PyString_AS_STRING(k), len);
646 651 p += len;
647 652 o = PyDict_GetItem(copymap, k);
648 653 if (o) {
649 654 *p++ = '\0';
650 655 l = PyString_GET_SIZE(o);
651 656 memcpy(p, PyString_AS_STRING(o), l);
652 657 p += l;
653 658 len += l + 1;
654 659 }
655 660 putbe32((uint32_t)len, t);
656 661 }
657 662
658 663 pos = p - PyString_AS_STRING(packobj);
659 664 if (pos != nbytes) {
660 665 PyErr_Format(PyExc_SystemError, "bad dirstate size: %ld != %ld",
661 666 (long)pos, (long)nbytes);
662 667 goto bail;
663 668 }
664 669
665 670 return packobj;
666 671 bail:
667 672 Py_XDECREF(mtime_unset);
668 673 Py_XDECREF(packobj);
669 674 Py_XDECREF(v);
670 675 return NULL;
671 676 }
672 677
673 678 /*
674 679 * A base-16 trie for fast node->rev mapping.
675 680 *
676 681 * Positive value is index of the next node in the trie
677 682 * Negative value is a leaf: -(rev + 1)
678 683 * Zero is empty
679 684 */
680 685 typedef struct {
681 686 int children[16];
682 687 } nodetree;
683 688
684 689 /*
685 690 * This class has two behaviors.
686 691 *
687 692 * When used in a list-like way (with integer keys), we decode an
688 693 * entry in a RevlogNG index file on demand. Our last entry is a
689 694 * sentinel, always a nullid. We have limited support for
690 695 * integer-keyed insert and delete, only at elements right before the
691 696 * sentinel.
692 697 *
693 698 * With string keys, we lazily perform a reverse mapping from node to
694 699 * rev, using a base-16 trie.
695 700 */
696 701 typedef struct {
697 702 PyObject_HEAD
698 703 /* Type-specific fields go here. */
699 704 PyObject *data; /* raw bytes of index */
700 705 PyObject **cache; /* cached tuples */
701 706 const char **offsets; /* populated on demand */
702 707 Py_ssize_t raw_length; /* original number of elements */
703 708 Py_ssize_t length; /* current number of elements */
704 709 PyObject *added; /* populated on demand */
705 710 PyObject *headrevs; /* cache, invalidated on changes */
706 711 PyObject *filteredrevs;/* filtered revs set */
707 712 nodetree *nt; /* base-16 trie */
708 713 unsigned ntlength; /* # nodes in use */
709 714 unsigned ntcapacity; /* # nodes allocated */
710 715 int ntdepth; /* maximum depth of tree */
711 716 int ntsplits; /* # splits performed */
712 717 int ntrev; /* last rev scanned */
713 718 int ntlookups; /* # lookups */
714 719 int ntmisses; /* # lookups that miss the cache */
715 720 int inlined;
716 721 } indexObject;
717 722
718 723 static Py_ssize_t index_length(const indexObject *self)
719 724 {
720 725 if (self->added == NULL)
721 726 return self->length;
722 727 return self->length + PyList_GET_SIZE(self->added);
723 728 }
724 729
725 730 static PyObject *nullentry;
726 731 static const char nullid[20];
727 732
728 733 static Py_ssize_t inline_scan(indexObject *self, const char **offsets);
729 734
730 735 #if LONG_MAX == 0x7fffffffL
731 736 static char *tuple_format = "Kiiiiiis#";
732 737 #else
733 738 static char *tuple_format = "kiiiiiis#";
734 739 #endif
735 740
736 741 /* A RevlogNG v1 index entry is 64 bytes long. */
737 742 static const long v1_hdrsize = 64;
738 743
739 744 /*
740 745 * Return a pointer to the beginning of a RevlogNG record.
741 746 */
742 747 static const char *index_deref(indexObject *self, Py_ssize_t pos)
743 748 {
744 749 if (self->inlined && pos > 0) {
745 750 if (self->offsets == NULL) {
746 751 self->offsets = malloc(self->raw_length *
747 752 sizeof(*self->offsets));
748 753 if (self->offsets == NULL)
749 754 return (const char *)PyErr_NoMemory();
750 755 inline_scan(self, self->offsets);
751 756 }
752 757 return self->offsets[pos];
753 758 }
754 759
755 760 return PyString_AS_STRING(self->data) + pos * v1_hdrsize;
756 761 }
757 762
758 763 static inline int index_get_parents(indexObject *self, Py_ssize_t rev,
759 764 int *ps, int maxrev)
760 765 {
761 766 if (rev >= self->length - 1) {
762 767 PyObject *tuple = PyList_GET_ITEM(self->added,
763 768 rev - self->length + 1);
764 769 ps[0] = (int)PyInt_AS_LONG(PyTuple_GET_ITEM(tuple, 5));
765 770 ps[1] = (int)PyInt_AS_LONG(PyTuple_GET_ITEM(tuple, 6));
766 771 } else {
767 772 const char *data = index_deref(self, rev);
768 773 ps[0] = getbe32(data + 24);
769 774 ps[1] = getbe32(data + 28);
770 775 }
771 776 /* If index file is corrupted, ps[] may point to invalid revisions. So
772 777 * there is a risk of buffer overflow to trust them unconditionally. */
773 778 if (ps[0] > maxrev || ps[1] > maxrev) {
774 779 PyErr_SetString(PyExc_ValueError, "parent out of range");
775 780 return -1;
776 781 }
777 782 return 0;
778 783 }
779 784
780 785
781 786 /*
782 787 * RevlogNG format (all in big endian, data may be inlined):
783 788 * 6 bytes: offset
784 789 * 2 bytes: flags
785 790 * 4 bytes: compressed length
786 791 * 4 bytes: uncompressed length
787 792 * 4 bytes: base revision
788 793 * 4 bytes: link revision
789 794 * 4 bytes: parent 1 revision
790 795 * 4 bytes: parent 2 revision
791 796 * 32 bytes: nodeid (only 20 bytes used)
792 797 */
793 798 static PyObject *index_get(indexObject *self, Py_ssize_t pos)
794 799 {
795 800 uint64_t offset_flags;
796 801 int comp_len, uncomp_len, base_rev, link_rev, parent_1, parent_2;
797 802 const char *c_node_id;
798 803 const char *data;
799 804 Py_ssize_t length = index_length(self);
800 805 PyObject *entry;
801 806
802 807 if (pos < 0)
803 808 pos += length;
804 809
805 810 if (pos < 0 || pos >= length) {
806 811 PyErr_SetString(PyExc_IndexError, "revlog index out of range");
807 812 return NULL;
808 813 }
809 814
810 815 if (pos == length - 1) {
811 816 Py_INCREF(nullentry);
812 817 return nullentry;
813 818 }
814 819
815 820 if (pos >= self->length - 1) {
816 821 PyObject *obj;
817 822 obj = PyList_GET_ITEM(self->added, pos - self->length + 1);
818 823 Py_INCREF(obj);
819 824 return obj;
820 825 }
821 826
822 827 if (self->cache) {
823 828 if (self->cache[pos]) {
824 829 Py_INCREF(self->cache[pos]);
825 830 return self->cache[pos];
826 831 }
827 832 } else {
828 833 self->cache = calloc(self->raw_length, sizeof(PyObject *));
829 834 if (self->cache == NULL)
830 835 return PyErr_NoMemory();
831 836 }
832 837
833 838 data = index_deref(self, pos);
834 839 if (data == NULL)
835 840 return NULL;
836 841
837 842 offset_flags = getbe32(data + 4);
838 843 if (pos == 0) /* mask out version number for the first entry */
839 844 offset_flags &= 0xFFFF;
840 845 else {
841 846 uint32_t offset_high = getbe32(data);
842 847 offset_flags |= ((uint64_t)offset_high) << 32;
843 848 }
844 849
845 850 comp_len = getbe32(data + 8);
846 851 uncomp_len = getbe32(data + 12);
847 852 base_rev = getbe32(data + 16);
848 853 link_rev = getbe32(data + 20);
849 854 parent_1 = getbe32(data + 24);
850 855 parent_2 = getbe32(data + 28);
851 856 c_node_id = data + 32;
852 857
853 858 entry = Py_BuildValue(tuple_format, offset_flags, comp_len,
854 859 uncomp_len, base_rev, link_rev,
855 860 parent_1, parent_2, c_node_id, 20);
856 861
857 862 if (entry) {
858 863 PyObject_GC_UnTrack(entry);
859 864 Py_INCREF(entry);
860 865 }
861 866
862 867 self->cache[pos] = entry;
863 868
864 869 return entry;
865 870 }
866 871
867 872 /*
868 873 * Return the 20-byte SHA of the node corresponding to the given rev.
869 874 */
870 875 static const char *index_node(indexObject *self, Py_ssize_t pos)
871 876 {
872 877 Py_ssize_t length = index_length(self);
873 878 const char *data;
874 879
875 880 if (pos == length - 1 || pos == INT_MAX)
876 881 return nullid;
877 882
878 883 if (pos >= length)
879 884 return NULL;
880 885
881 886 if (pos >= self->length - 1) {
882 887 PyObject *tuple, *str;
883 888 tuple = PyList_GET_ITEM(self->added, pos - self->length + 1);
884 889 str = PyTuple_GetItem(tuple, 7);
885 890 return str ? PyString_AS_STRING(str) : NULL;
886 891 }
887 892
888 893 data = index_deref(self, pos);
889 894 return data ? data + 32 : NULL;
890 895 }
891 896
892 897 static int nt_insert(indexObject *self, const char *node, int rev);
893 898
894 899 static int node_check(PyObject *obj, char **node, Py_ssize_t *nodelen)
895 900 {
896 901 if (PyString_AsStringAndSize(obj, node, nodelen) == -1)
897 902 return -1;
898 903 if (*nodelen == 20)
899 904 return 0;
900 905 PyErr_SetString(PyExc_ValueError, "20-byte hash required");
901 906 return -1;
902 907 }
903 908
904 909 static PyObject *index_insert(indexObject *self, PyObject *args)
905 910 {
906 911 PyObject *obj;
907 912 char *node;
908 913 int index;
909 914 Py_ssize_t len, nodelen;
910 915
911 916 if (!PyArg_ParseTuple(args, "iO", &index, &obj))
912 917 return NULL;
913 918
914 919 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 8) {
915 920 PyErr_SetString(PyExc_TypeError, "8-tuple required");
916 921 return NULL;
917 922 }
918 923
919 924 if (node_check(PyTuple_GET_ITEM(obj, 7), &node, &nodelen) == -1)
920 925 return NULL;
921 926
922 927 len = index_length(self);
923 928
924 929 if (index < 0)
925 930 index += len;
926 931
927 932 if (index != len - 1) {
928 933 PyErr_SetString(PyExc_IndexError,
929 934 "insert only supported at index -1");
930 935 return NULL;
931 936 }
932 937
933 938 if (self->added == NULL) {
934 939 self->added = PyList_New(0);
935 940 if (self->added == NULL)
936 941 return NULL;
937 942 }
938 943
939 944 if (PyList_Append(self->added, obj) == -1)
940 945 return NULL;
941 946
942 947 if (self->nt)
943 948 nt_insert(self, node, index);
944 949
945 950 Py_CLEAR(self->headrevs);
946 951 Py_RETURN_NONE;
947 952 }
948 953
949 954 static void _index_clearcaches(indexObject *self)
950 955 {
951 956 if (self->cache) {
952 957 Py_ssize_t i;
953 958
954 959 for (i = 0; i < self->raw_length; i++)
955 960 Py_CLEAR(self->cache[i]);
956 961 free(self->cache);
957 962 self->cache = NULL;
958 963 }
959 964 if (self->offsets) {
960 965 free(self->offsets);
961 966 self->offsets = NULL;
962 967 }
963 968 if (self->nt) {
964 969 free(self->nt);
965 970 self->nt = NULL;
966 971 }
967 972 Py_CLEAR(self->headrevs);
968 973 }
969 974
970 975 static PyObject *index_clearcaches(indexObject *self)
971 976 {
972 977 _index_clearcaches(self);
973 978 self->ntlength = self->ntcapacity = 0;
974 979 self->ntdepth = self->ntsplits = 0;
975 980 self->ntrev = -1;
976 981 self->ntlookups = self->ntmisses = 0;
977 982 Py_RETURN_NONE;
978 983 }
979 984
980 985 static PyObject *index_stats(indexObject *self)
981 986 {
982 987 PyObject *obj = PyDict_New();
983 988 PyObject *t = NULL;
984 989
985 990 if (obj == NULL)
986 991 return NULL;
987 992
988 993 #define istat(__n, __d) \
989 994 t = PyInt_FromSsize_t(self->__n); \
990 995 if (!t) \
991 996 goto bail; \
992 997 if (PyDict_SetItemString(obj, __d, t) == -1) \
993 998 goto bail; \
994 999 Py_DECREF(t);
995 1000
996 1001 if (self->added) {
997 1002 Py_ssize_t len = PyList_GET_SIZE(self->added);
998 1003 t = PyInt_FromSsize_t(len);
999 1004 if (!t)
1000 1005 goto bail;
1001 1006 if (PyDict_SetItemString(obj, "index entries added", t) == -1)
1002 1007 goto bail;
1003 1008 Py_DECREF(t);
1004 1009 }
1005 1010
1006 1011 if (self->raw_length != self->length - 1)
1007 1012 istat(raw_length, "revs on disk");
1008 1013 istat(length, "revs in memory");
1009 1014 istat(ntcapacity, "node trie capacity");
1010 1015 istat(ntdepth, "node trie depth");
1011 1016 istat(ntlength, "node trie count");
1012 1017 istat(ntlookups, "node trie lookups");
1013 1018 istat(ntmisses, "node trie misses");
1014 1019 istat(ntrev, "node trie last rev scanned");
1015 1020 istat(ntsplits, "node trie splits");
1016 1021
1017 1022 #undef istat
1018 1023
1019 1024 return obj;
1020 1025
1021 1026 bail:
1022 1027 Py_XDECREF(obj);
1023 1028 Py_XDECREF(t);
1024 1029 return NULL;
1025 1030 }
1026 1031
1027 1032 /*
1028 1033 * When we cache a list, we want to be sure the caller can't mutate
1029 1034 * the cached copy.
1030 1035 */
1031 1036 static PyObject *list_copy(PyObject *list)
1032 1037 {
1033 1038 Py_ssize_t len = PyList_GET_SIZE(list);
1034 1039 PyObject *newlist = PyList_New(len);
1035 1040 Py_ssize_t i;
1036 1041
1037 1042 if (newlist == NULL)
1038 1043 return NULL;
1039 1044
1040 1045 for (i = 0; i < len; i++) {
1041 1046 PyObject *obj = PyList_GET_ITEM(list, i);
1042 1047 Py_INCREF(obj);
1043 1048 PyList_SET_ITEM(newlist, i, obj);
1044 1049 }
1045 1050
1046 1051 return newlist;
1047 1052 }
1048 1053
1049 1054 static int check_filter(PyObject *filter, Py_ssize_t arg) {
1050 1055 if (filter) {
1051 1056 PyObject *arglist, *result;
1052 1057 int isfiltered;
1053 1058
1054 1059 arglist = Py_BuildValue("(n)", arg);
1055 1060 if (!arglist) {
1056 1061 return -1;
1057 1062 }
1058 1063
1059 1064 result = PyEval_CallObject(filter, arglist);
1060 1065 Py_DECREF(arglist);
1061 1066 if (!result) {
1062 1067 return -1;
1063 1068 }
1064 1069
1065 1070 /* PyObject_IsTrue returns 1 if true, 0 if false, -1 if error,
1066 1071 * same as this function, so we can just return it directly.*/
1067 1072 isfiltered = PyObject_IsTrue(result);
1068 1073 Py_DECREF(result);
1069 1074 return isfiltered;
1070 1075 } else {
1071 1076 return 0;
1072 1077 }
1073 1078 }
1074 1079
1075 1080 static Py_ssize_t add_roots_get_min(indexObject *self, PyObject *list,
1076 1081 Py_ssize_t marker, char *phases)
1077 1082 {
1078 1083 PyObject *iter = NULL;
1079 1084 PyObject *iter_item = NULL;
1080 1085 Py_ssize_t min_idx = index_length(self) + 1;
1081 1086 long iter_item_long;
1082 1087
1083 1088 if (PyList_GET_SIZE(list) != 0) {
1084 1089 iter = PyObject_GetIter(list);
1085 1090 if (iter == NULL)
1086 1091 return -2;
1087 1092 while ((iter_item = PyIter_Next(iter)))
1088 1093 {
1089 1094 iter_item_long = PyInt_AS_LONG(iter_item);
1090 1095 Py_DECREF(iter_item);
1091 1096 if (iter_item_long < min_idx)
1092 1097 min_idx = iter_item_long;
1093 1098 phases[iter_item_long] = marker;
1094 1099 }
1095 1100 Py_DECREF(iter);
1096 1101 }
1097 1102
1098 1103 return min_idx;
1099 1104 }
1100 1105
1101 1106 static inline void set_phase_from_parents(char *phases, int parent_1,
1102 1107 int parent_2, Py_ssize_t i)
1103 1108 {
1104 1109 if (parent_1 >= 0 && phases[parent_1] > phases[i])
1105 1110 phases[i] = phases[parent_1];
1106 1111 if (parent_2 >= 0 && phases[parent_2] > phases[i])
1107 1112 phases[i] = phases[parent_2];
1108 1113 }
1109 1114
1110 1115 static PyObject *reachableroots2(indexObject *self, PyObject *args)
1111 1116 {
1112 1117
1113 1118 /* Input */
1114 1119 long minroot;
1115 1120 PyObject *includepatharg = NULL;
1116 1121 int includepath = 0;
1117 1122 /* heads and roots are lists */
1118 1123 PyObject *heads = NULL;
1119 1124 PyObject *roots = NULL;
1120 1125 PyObject *reachable = NULL;
1121 1126
1122 1127 PyObject *val;
1123 1128 Py_ssize_t len = index_length(self) - 1;
1124 1129 long revnum;
1125 1130 Py_ssize_t k;
1126 1131 Py_ssize_t i;
1127 1132 Py_ssize_t l;
1128 1133 int r;
1129 1134 int parents[2];
1130 1135
1131 1136 /* Internal data structure:
1132 1137 * tovisit: array of length len+1 (all revs + nullrev), filled upto lentovisit
1133 1138 * revstates: array of length len+1 (all revs + nullrev) */
1134 1139 int *tovisit = NULL;
1135 1140 long lentovisit = 0;
1136 1141 enum { RS_SEEN = 1, RS_ROOT = 2, RS_REACHABLE = 4 };
1137 1142 char *revstates = NULL;
1138 1143
1139 1144 /* Get arguments */
1140 1145 if (!PyArg_ParseTuple(args, "lO!O!O!", &minroot, &PyList_Type, &heads,
1141 1146 &PyList_Type, &roots,
1142 1147 &PyBool_Type, &includepatharg))
1143 1148 goto bail;
1144 1149
1145 1150 if (includepatharg == Py_True)
1146 1151 includepath = 1;
1147 1152
1148 1153 /* Initialize return set */
1149 1154 reachable = PyList_New(0);
1150 1155 if (reachable == NULL)
1151 1156 goto bail;
1152 1157
1153 1158 /* Initialize internal datastructures */
1154 1159 tovisit = (int *)malloc((len + 1) * sizeof(int));
1155 1160 if (tovisit == NULL) {
1156 1161 PyErr_NoMemory();
1157 1162 goto bail;
1158 1163 }
1159 1164
1160 1165 revstates = (char *)calloc(len + 1, 1);
1161 1166 if (revstates == NULL) {
1162 1167 PyErr_NoMemory();
1163 1168 goto bail;
1164 1169 }
1165 1170
1166 1171 l = PyList_GET_SIZE(roots);
1167 1172 for (i = 0; i < l; i++) {
1168 1173 revnum = PyInt_AsLong(PyList_GET_ITEM(roots, i));
1169 1174 if (revnum == -1 && PyErr_Occurred())
1170 1175 goto bail;
1171 1176 /* If root is out of range, e.g. wdir(), it must be unreachable
1172 1177 * from heads. So we can just ignore it. */
1173 1178 if (revnum + 1 < 0 || revnum + 1 >= len + 1)
1174 1179 continue;
1175 1180 revstates[revnum + 1] |= RS_ROOT;
1176 1181 }
1177 1182
1178 1183 /* Populate tovisit with all the heads */
1179 1184 l = PyList_GET_SIZE(heads);
1180 1185 for (i = 0; i < l; i++) {
1181 1186 revnum = PyInt_AsLong(PyList_GET_ITEM(heads, i));
1182 1187 if (revnum == -1 && PyErr_Occurred())
1183 1188 goto bail;
1184 1189 if (revnum + 1 < 0 || revnum + 1 >= len + 1) {
1185 1190 PyErr_SetString(PyExc_IndexError, "head out of range");
1186 1191 goto bail;
1187 1192 }
1188 1193 if (!(revstates[revnum + 1] & RS_SEEN)) {
1189 1194 tovisit[lentovisit++] = (int)revnum;
1190 1195 revstates[revnum + 1] |= RS_SEEN;
1191 1196 }
1192 1197 }
1193 1198
1194 1199 /* Visit the tovisit list and find the reachable roots */
1195 1200 k = 0;
1196 1201 while (k < lentovisit) {
1197 1202 /* Add the node to reachable if it is a root*/
1198 1203 revnum = tovisit[k++];
1199 1204 if (revstates[revnum + 1] & RS_ROOT) {
1200 1205 revstates[revnum + 1] |= RS_REACHABLE;
1201 1206 val = PyInt_FromLong(revnum);
1202 1207 if (val == NULL)
1203 1208 goto bail;
1204 1209 r = PyList_Append(reachable, val);
1205 1210 Py_DECREF(val);
1206 1211 if (r < 0)
1207 1212 goto bail;
1208 1213 if (includepath == 0)
1209 1214 continue;
1210 1215 }
1211 1216
1212 1217 /* Add its parents to the list of nodes to visit */
1213 1218 if (revnum == -1)
1214 1219 continue;
1215 1220 r = index_get_parents(self, revnum, parents, (int)len - 1);
1216 1221 if (r < 0)
1217 1222 goto bail;
1218 1223 for (i = 0; i < 2; i++) {
1219 1224 if (!(revstates[parents[i] + 1] & RS_SEEN)
1220 1225 && parents[i] >= minroot) {
1221 1226 tovisit[lentovisit++] = parents[i];
1222 1227 revstates[parents[i] + 1] |= RS_SEEN;
1223 1228 }
1224 1229 }
1225 1230 }
1226 1231
1227 1232 /* Find all the nodes in between the roots we found and the heads
1228 1233 * and add them to the reachable set */
1229 1234 if (includepath == 1) {
1230 1235 long minidx = minroot;
1231 1236 if (minidx < 0)
1232 1237 minidx = 0;
1233 1238 for (i = minidx; i < len; i++) {
1234 1239 if (!(revstates[i + 1] & RS_SEEN))
1235 1240 continue;
1236 1241 r = index_get_parents(self, i, parents, (int)len - 1);
1237 1242 /* Corrupted index file, error is set from
1238 1243 * index_get_parents */
1239 1244 if (r < 0)
1240 1245 goto bail;
1241 1246 if (((revstates[parents[0] + 1] |
1242 1247 revstates[parents[1] + 1]) & RS_REACHABLE)
1243 1248 && !(revstates[i + 1] & RS_REACHABLE)) {
1244 1249 revstates[i + 1] |= RS_REACHABLE;
1245 1250 val = PyInt_FromLong(i);
1246 1251 if (val == NULL)
1247 1252 goto bail;
1248 1253 r = PyList_Append(reachable, val);
1249 1254 Py_DECREF(val);
1250 1255 if (r < 0)
1251 1256 goto bail;
1252 1257 }
1253 1258 }
1254 1259 }
1255 1260
1256 1261 free(revstates);
1257 1262 free(tovisit);
1258 1263 return reachable;
1259 1264 bail:
1260 1265 Py_XDECREF(reachable);
1261 1266 free(revstates);
1262 1267 free(tovisit);
1263 1268 return NULL;
1264 1269 }
1265 1270
1266 1271 static PyObject *compute_phases_map_sets(indexObject *self, PyObject *args)
1267 1272 {
1268 1273 PyObject *roots = Py_None;
1269 1274 PyObject *ret = NULL;
1270 1275 PyObject *phaseslist = NULL;
1271 1276 PyObject *phaseroots = NULL;
1272 1277 PyObject *phaseset = NULL;
1273 1278 PyObject *phasessetlist = NULL;
1274 1279 PyObject *rev = NULL;
1275 1280 Py_ssize_t len = index_length(self) - 1;
1276 1281 Py_ssize_t numphase = 0;
1277 1282 Py_ssize_t minrevallphases = 0;
1278 1283 Py_ssize_t minrevphase = 0;
1279 1284 Py_ssize_t i = 0;
1280 1285 char *phases = NULL;
1281 1286 long phase;
1282 1287
1283 1288 if (!PyArg_ParseTuple(args, "O", &roots))
1284 1289 goto release_none;
1285 1290 if (roots == NULL || !PyList_Check(roots))
1286 1291 goto release_none;
1287 1292
1288 1293 phases = calloc(len, 1); /* phase per rev: {0: public, 1: draft, 2: secret} */
1289 1294 if (phases == NULL)
1290 1295 goto release_none;
1291 1296 /* Put the phase information of all the roots in phases */
1292 1297 numphase = PyList_GET_SIZE(roots)+1;
1293 1298 minrevallphases = len + 1;
1294 1299 phasessetlist = PyList_New(numphase);
1295 1300 if (phasessetlist == NULL)
1296 1301 goto release_none;
1297 1302
1298 1303 PyList_SET_ITEM(phasessetlist, 0, Py_None);
1299 1304 Py_INCREF(Py_None);
1300 1305
1301 1306 for (i = 0; i < numphase-1; i++) {
1302 1307 phaseroots = PyList_GET_ITEM(roots, i);
1303 1308 phaseset = PySet_New(NULL);
1304 1309 if (phaseset == NULL)
1305 1310 goto release_phasesetlist;
1306 1311 PyList_SET_ITEM(phasessetlist, i+1, phaseset);
1307 1312 if (!PyList_Check(phaseroots))
1308 1313 goto release_phasesetlist;
1309 1314 minrevphase = add_roots_get_min(self, phaseroots, i+1, phases);
1310 1315 if (minrevphase == -2) /* Error from add_roots_get_min */
1311 1316 goto release_phasesetlist;
1312 1317 minrevallphases = MIN(minrevallphases, minrevphase);
1313 1318 }
1314 1319 /* Propagate the phase information from the roots to the revs */
1315 1320 if (minrevallphases != -1) {
1316 1321 int parents[2];
1317 1322 for (i = minrevallphases; i < len; i++) {
1318 1323 if (index_get_parents(self, i, parents,
1319 1324 (int)len - 1) < 0)
1320 1325 goto release_phasesetlist;
1321 1326 set_phase_from_parents(phases, parents[0], parents[1], i);
1322 1327 }
1323 1328 }
1324 1329 /* Transform phase list to a python list */
1325 1330 phaseslist = PyList_New(len);
1326 1331 if (phaseslist == NULL)
1327 1332 goto release_phasesetlist;
1328 1333 for (i = 0; i < len; i++) {
1329 1334 phase = phases[i];
1330 1335 /* We only store the sets of phase for non public phase, the public phase
1331 1336 * is computed as a difference */
1332 1337 if (phase != 0) {
1333 1338 phaseset = PyList_GET_ITEM(phasessetlist, phase);
1334 1339 rev = PyInt_FromLong(i);
1335 1340 PySet_Add(phaseset, rev);
1336 1341 Py_XDECREF(rev);
1337 1342 }
1338 1343 PyList_SET_ITEM(phaseslist, i, PyInt_FromLong(phase));
1339 1344 }
1340 1345 ret = PyList_New(2);
1341 1346 if (ret == NULL)
1342 1347 goto release_phaseslist;
1343 1348
1344 1349 PyList_SET_ITEM(ret, 0, phaseslist);
1345 1350 PyList_SET_ITEM(ret, 1, phasessetlist);
1346 1351 /* We don't release phaseslist and phasessetlist as we return them to
1347 1352 * python */
1348 1353 goto release_phases;
1349 1354
1350 1355 release_phaseslist:
1351 1356 Py_XDECREF(phaseslist);
1352 1357 release_phasesetlist:
1353 1358 Py_XDECREF(phasessetlist);
1354 1359 release_phases:
1355 1360 free(phases);
1356 1361 release_none:
1357 1362 return ret;
1358 1363 }
1359 1364
1360 1365 static PyObject *index_headrevs(indexObject *self, PyObject *args)
1361 1366 {
1362 1367 Py_ssize_t i, j, len;
1363 1368 char *nothead = NULL;
1364 1369 PyObject *heads = NULL;
1365 1370 PyObject *filter = NULL;
1366 1371 PyObject *filteredrevs = Py_None;
1367 1372
1368 1373 if (!PyArg_ParseTuple(args, "|O", &filteredrevs)) {
1369 1374 return NULL;
1370 1375 }
1371 1376
1372 1377 if (self->headrevs && filteredrevs == self->filteredrevs)
1373 1378 return list_copy(self->headrevs);
1374 1379
1375 1380 Py_DECREF(self->filteredrevs);
1376 1381 self->filteredrevs = filteredrevs;
1377 1382 Py_INCREF(filteredrevs);
1378 1383
1379 1384 if (filteredrevs != Py_None) {
1380 1385 filter = PyObject_GetAttrString(filteredrevs, "__contains__");
1381 1386 if (!filter) {
1382 1387 PyErr_SetString(PyExc_TypeError,
1383 1388 "filteredrevs has no attribute __contains__");
1384 1389 goto bail;
1385 1390 }
1386 1391 }
1387 1392
1388 1393 len = index_length(self) - 1;
1389 1394 heads = PyList_New(0);
1390 1395 if (heads == NULL)
1391 1396 goto bail;
1392 1397 if (len == 0) {
1393 1398 PyObject *nullid = PyInt_FromLong(-1);
1394 1399 if (nullid == NULL || PyList_Append(heads, nullid) == -1) {
1395 1400 Py_XDECREF(nullid);
1396 1401 goto bail;
1397 1402 }
1398 1403 goto done;
1399 1404 }
1400 1405
1401 1406 nothead = calloc(len, 1);
1402 1407 if (nothead == NULL)
1403 1408 goto bail;
1404 1409
1405 1410 for (i = 0; i < len; i++) {
1406 1411 int isfiltered;
1407 1412 int parents[2];
1408 1413
1409 1414 isfiltered = check_filter(filter, i);
1410 1415 if (isfiltered == -1) {
1411 1416 PyErr_SetString(PyExc_TypeError,
1412 1417 "unable to check filter");
1413 1418 goto bail;
1414 1419 }
1415 1420
1416 1421 if (isfiltered) {
1417 1422 nothead[i] = 1;
1418 1423 continue;
1419 1424 }
1420 1425
1421 1426 if (index_get_parents(self, i, parents, (int)len - 1) < 0)
1422 1427 goto bail;
1423 1428 for (j = 0; j < 2; j++) {
1424 1429 if (parents[j] >= 0)
1425 1430 nothead[parents[j]] = 1;
1426 1431 }
1427 1432 }
1428 1433
1429 1434 for (i = 0; i < len; i++) {
1430 1435 PyObject *head;
1431 1436
1432 1437 if (nothead[i])
1433 1438 continue;
1434 1439 head = PyInt_FromSsize_t(i);
1435 1440 if (head == NULL || PyList_Append(heads, head) == -1) {
1436 1441 Py_XDECREF(head);
1437 1442 goto bail;
1438 1443 }
1439 1444 }
1440 1445
1441 1446 done:
1442 1447 self->headrevs = heads;
1443 1448 Py_XDECREF(filter);
1444 1449 free(nothead);
1445 1450 return list_copy(self->headrevs);
1446 1451 bail:
1447 1452 Py_XDECREF(filter);
1448 1453 Py_XDECREF(heads);
1449 1454 free(nothead);
1450 1455 return NULL;
1451 1456 }
1452 1457
1453 1458 static inline int nt_level(const char *node, Py_ssize_t level)
1454 1459 {
1455 1460 int v = node[level>>1];
1456 1461 if (!(level & 1))
1457 1462 v >>= 4;
1458 1463 return v & 0xf;
1459 1464 }
1460 1465
1461 1466 /*
1462 1467 * Return values:
1463 1468 *
1464 1469 * -4: match is ambiguous (multiple candidates)
1465 1470 * -2: not found
1466 1471 * rest: valid rev
1467 1472 */
1468 1473 static int nt_find(indexObject *self, const char *node, Py_ssize_t nodelen,
1469 1474 int hex)
1470 1475 {
1471 1476 int (*getnybble)(const char *, Py_ssize_t) = hex ? hexdigit : nt_level;
1472 1477 int level, maxlevel, off;
1473 1478
1474 1479 if (nodelen == 20 && node[0] == '\0' && memcmp(node, nullid, 20) == 0)
1475 1480 return -1;
1476 1481
1477 1482 if (self->nt == NULL)
1478 1483 return -2;
1479 1484
1480 1485 if (hex)
1481 1486 maxlevel = nodelen > 40 ? 40 : (int)nodelen;
1482 1487 else
1483 1488 maxlevel = nodelen > 20 ? 40 : ((int)nodelen * 2);
1484 1489
1485 1490 for (level = off = 0; level < maxlevel; level++) {
1486 1491 int k = getnybble(node, level);
1487 1492 nodetree *n = &self->nt[off];
1488 1493 int v = n->children[k];
1489 1494
1490 1495 if (v < 0) {
1491 1496 const char *n;
1492 1497 Py_ssize_t i;
1493 1498
1494 1499 v = -(v + 1);
1495 1500 n = index_node(self, v);
1496 1501 if (n == NULL)
1497 1502 return -2;
1498 1503 for (i = level; i < maxlevel; i++)
1499 1504 if (getnybble(node, i) != nt_level(n, i))
1500 1505 return -2;
1501 1506 return v;
1502 1507 }
1503 1508 if (v == 0)
1504 1509 return -2;
1505 1510 off = v;
1506 1511 }
1507 1512 /* multiple matches against an ambiguous prefix */
1508 1513 return -4;
1509 1514 }
1510 1515
1511 1516 static int nt_new(indexObject *self)
1512 1517 {
1513 1518 if (self->ntlength == self->ntcapacity) {
1514 1519 if (self->ntcapacity >= INT_MAX / (sizeof(nodetree) * 2)) {
1515 1520 PyErr_SetString(PyExc_MemoryError,
1516 1521 "overflow in nt_new");
1517 1522 return -1;
1518 1523 }
1519 1524 self->ntcapacity *= 2;
1520 1525 self->nt = realloc(self->nt,
1521 1526 self->ntcapacity * sizeof(nodetree));
1522 1527 if (self->nt == NULL) {
1523 1528 PyErr_SetString(PyExc_MemoryError, "out of memory");
1524 1529 return -1;
1525 1530 }
1526 1531 memset(&self->nt[self->ntlength], 0,
1527 1532 sizeof(nodetree) * (self->ntcapacity - self->ntlength));
1528 1533 }
1529 1534 return self->ntlength++;
1530 1535 }
1531 1536
1532 1537 static int nt_insert(indexObject *self, const char *node, int rev)
1533 1538 {
1534 1539 int level = 0;
1535 1540 int off = 0;
1536 1541
1537 1542 while (level < 40) {
1538 1543 int k = nt_level(node, level);
1539 1544 nodetree *n;
1540 1545 int v;
1541 1546
1542 1547 n = &self->nt[off];
1543 1548 v = n->children[k];
1544 1549
1545 1550 if (v == 0) {
1546 1551 n->children[k] = -rev - 1;
1547 1552 return 0;
1548 1553 }
1549 1554 if (v < 0) {
1550 1555 const char *oldnode = index_node(self, -(v + 1));
1551 1556 int noff;
1552 1557
1553 1558 if (!oldnode || !memcmp(oldnode, node, 20)) {
1554 1559 n->children[k] = -rev - 1;
1555 1560 return 0;
1556 1561 }
1557 1562 noff = nt_new(self);
1558 1563 if (noff == -1)
1559 1564 return -1;
1560 1565 /* self->nt may have been changed by realloc */
1561 1566 self->nt[off].children[k] = noff;
1562 1567 off = noff;
1563 1568 n = &self->nt[off];
1564 1569 n->children[nt_level(oldnode, ++level)] = v;
1565 1570 if (level > self->ntdepth)
1566 1571 self->ntdepth = level;
1567 1572 self->ntsplits += 1;
1568 1573 } else {
1569 1574 level += 1;
1570 1575 off = v;
1571 1576 }
1572 1577 }
1573 1578
1574 1579 return -1;
1575 1580 }
1576 1581
1577 1582 static int nt_init(indexObject *self)
1578 1583 {
1579 1584 if (self->nt == NULL) {
1580 1585 if ((size_t)self->raw_length > INT_MAX / sizeof(nodetree)) {
1581 1586 PyErr_SetString(PyExc_ValueError, "overflow in nt_init");
1582 1587 return -1;
1583 1588 }
1584 1589 self->ntcapacity = self->raw_length < 4
1585 1590 ? 4 : (int)self->raw_length / 2;
1586 1591
1587 1592 self->nt = calloc(self->ntcapacity, sizeof(nodetree));
1588 1593 if (self->nt == NULL) {
1589 1594 PyErr_NoMemory();
1590 1595 return -1;
1591 1596 }
1592 1597 self->ntlength = 1;
1593 1598 self->ntrev = (int)index_length(self) - 1;
1594 1599 self->ntlookups = 1;
1595 1600 self->ntmisses = 0;
1596 1601 if (nt_insert(self, nullid, INT_MAX) == -1)
1597 1602 return -1;
1598 1603 }
1599 1604 return 0;
1600 1605 }
1601 1606
1602 1607 /*
1603 1608 * Return values:
1604 1609 *
1605 1610 * -3: error (exception set)
1606 1611 * -2: not found (no exception set)
1607 1612 * rest: valid rev
1608 1613 */
1609 1614 static int index_find_node(indexObject *self,
1610 1615 const char *node, Py_ssize_t nodelen)
1611 1616 {
1612 1617 int rev;
1613 1618
1614 1619 self->ntlookups++;
1615 1620 rev = nt_find(self, node, nodelen, 0);
1616 1621 if (rev >= -1)
1617 1622 return rev;
1618 1623
1619 1624 if (nt_init(self) == -1)
1620 1625 return -3;
1621 1626
1622 1627 /*
1623 1628 * For the first handful of lookups, we scan the entire index,
1624 1629 * and cache only the matching nodes. This optimizes for cases
1625 1630 * like "hg tip", where only a few nodes are accessed.
1626 1631 *
1627 1632 * After that, we cache every node we visit, using a single
1628 1633 * scan amortized over multiple lookups. This gives the best
1629 1634 * bulk performance, e.g. for "hg log".
1630 1635 */
1631 1636 if (self->ntmisses++ < 4) {
1632 1637 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1633 1638 const char *n = index_node(self, rev);
1634 1639 if (n == NULL)
1635 1640 return -2;
1636 1641 if (memcmp(node, n, nodelen > 20 ? 20 : nodelen) == 0) {
1637 1642 if (nt_insert(self, n, rev) == -1)
1638 1643 return -3;
1639 1644 break;
1640 1645 }
1641 1646 }
1642 1647 } else {
1643 1648 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1644 1649 const char *n = index_node(self, rev);
1645 1650 if (n == NULL) {
1646 1651 self->ntrev = rev + 1;
1647 1652 return -2;
1648 1653 }
1649 1654 if (nt_insert(self, n, rev) == -1) {
1650 1655 self->ntrev = rev + 1;
1651 1656 return -3;
1652 1657 }
1653 1658 if (memcmp(node, n, nodelen > 20 ? 20 : nodelen) == 0) {
1654 1659 break;
1655 1660 }
1656 1661 }
1657 1662 self->ntrev = rev;
1658 1663 }
1659 1664
1660 1665 if (rev >= 0)
1661 1666 return rev;
1662 1667 return -2;
1663 1668 }
1664 1669
1665 1670 static void raise_revlog_error(void)
1666 1671 {
1667 1672 PyObject *mod = NULL, *dict = NULL, *errclass = NULL;
1668 1673
1669 1674 mod = PyImport_ImportModule("mercurial.error");
1670 1675 if (mod == NULL) {
1671 1676 goto cleanup;
1672 1677 }
1673 1678
1674 1679 dict = PyModule_GetDict(mod);
1675 1680 if (dict == NULL) {
1676 1681 goto cleanup;
1677 1682 }
1678 1683 Py_INCREF(dict);
1679 1684
1680 1685 errclass = PyDict_GetItemString(dict, "RevlogError");
1681 1686 if (errclass == NULL) {
1682 1687 PyErr_SetString(PyExc_SystemError,
1683 1688 "could not find RevlogError");
1684 1689 goto cleanup;
1685 1690 }
1686 1691
1687 1692 /* value of exception is ignored by callers */
1688 1693 PyErr_SetString(errclass, "RevlogError");
1689 1694
1690 1695 cleanup:
1691 1696 Py_XDECREF(dict);
1692 1697 Py_XDECREF(mod);
1693 1698 }
1694 1699
1695 1700 static PyObject *index_getitem(indexObject *self, PyObject *value)
1696 1701 {
1697 1702 char *node;
1698 1703 Py_ssize_t nodelen;
1699 1704 int rev;
1700 1705
1701 1706 if (PyInt_Check(value))
1702 1707 return index_get(self, PyInt_AS_LONG(value));
1703 1708
1704 1709 if (node_check(value, &node, &nodelen) == -1)
1705 1710 return NULL;
1706 1711 rev = index_find_node(self, node, nodelen);
1707 1712 if (rev >= -1)
1708 1713 return PyInt_FromLong(rev);
1709 1714 if (rev == -2)
1710 1715 raise_revlog_error();
1711 1716 return NULL;
1712 1717 }
1713 1718
1714 1719 static int nt_partialmatch(indexObject *self, const char *node,
1715 1720 Py_ssize_t nodelen)
1716 1721 {
1717 1722 int rev;
1718 1723
1719 1724 if (nt_init(self) == -1)
1720 1725 return -3;
1721 1726
1722 1727 if (self->ntrev > 0) {
1723 1728 /* ensure that the radix tree is fully populated */
1724 1729 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1725 1730 const char *n = index_node(self, rev);
1726 1731 if (n == NULL)
1727 1732 return -2;
1728 1733 if (nt_insert(self, n, rev) == -1)
1729 1734 return -3;
1730 1735 }
1731 1736 self->ntrev = rev;
1732 1737 }
1733 1738
1734 1739 return nt_find(self, node, nodelen, 1);
1735 1740 }
1736 1741
1737 1742 static PyObject *index_partialmatch(indexObject *self, PyObject *args)
1738 1743 {
1739 1744 const char *fullnode;
1740 1745 int nodelen;
1741 1746 char *node;
1742 1747 int rev, i;
1743 1748
1744 1749 if (!PyArg_ParseTuple(args, "s#", &node, &nodelen))
1745 1750 return NULL;
1746 1751
1747 1752 if (nodelen < 4) {
1748 1753 PyErr_SetString(PyExc_ValueError, "key too short");
1749 1754 return NULL;
1750 1755 }
1751 1756
1752 1757 if (nodelen > 40) {
1753 1758 PyErr_SetString(PyExc_ValueError, "key too long");
1754 1759 return NULL;
1755 1760 }
1756 1761
1757 1762 for (i = 0; i < nodelen; i++)
1758 1763 hexdigit(node, i);
1759 1764 if (PyErr_Occurred()) {
1760 1765 /* input contains non-hex characters */
1761 1766 PyErr_Clear();
1762 1767 Py_RETURN_NONE;
1763 1768 }
1764 1769
1765 1770 rev = nt_partialmatch(self, node, nodelen);
1766 1771
1767 1772 switch (rev) {
1768 1773 case -4:
1769 1774 raise_revlog_error();
1770 1775 case -3:
1771 1776 return NULL;
1772 1777 case -2:
1773 1778 Py_RETURN_NONE;
1774 1779 case -1:
1775 1780 return PyString_FromStringAndSize(nullid, 20);
1776 1781 }
1777 1782
1778 1783 fullnode = index_node(self, rev);
1779 1784 if (fullnode == NULL) {
1780 1785 PyErr_Format(PyExc_IndexError,
1781 1786 "could not access rev %d", rev);
1782 1787 return NULL;
1783 1788 }
1784 1789 return PyString_FromStringAndSize(fullnode, 20);
1785 1790 }
1786 1791
1787 1792 static PyObject *index_m_get(indexObject *self, PyObject *args)
1788 1793 {
1789 1794 Py_ssize_t nodelen;
1790 1795 PyObject *val;
1791 1796 char *node;
1792 1797 int rev;
1793 1798
1794 1799 if (!PyArg_ParseTuple(args, "O", &val))
1795 1800 return NULL;
1796 1801 if (node_check(val, &node, &nodelen) == -1)
1797 1802 return NULL;
1798 1803 rev = index_find_node(self, node, nodelen);
1799 1804 if (rev == -3)
1800 1805 return NULL;
1801 1806 if (rev == -2)
1802 1807 Py_RETURN_NONE;
1803 1808 return PyInt_FromLong(rev);
1804 1809 }
1805 1810
1806 1811 static int index_contains(indexObject *self, PyObject *value)
1807 1812 {
1808 1813 char *node;
1809 1814 Py_ssize_t nodelen;
1810 1815
1811 1816 if (PyInt_Check(value)) {
1812 1817 long rev = PyInt_AS_LONG(value);
1813 1818 return rev >= -1 && rev < index_length(self);
1814 1819 }
1815 1820
1816 1821 if (node_check(value, &node, &nodelen) == -1)
1817 1822 return -1;
1818 1823
1819 1824 switch (index_find_node(self, node, nodelen)) {
1820 1825 case -3:
1821 1826 return -1;
1822 1827 case -2:
1823 1828 return 0;
1824 1829 default:
1825 1830 return 1;
1826 1831 }
1827 1832 }
1828 1833
1829 1834 typedef uint64_t bitmask;
1830 1835
1831 1836 /*
1832 1837 * Given a disjoint set of revs, return all candidates for the
1833 1838 * greatest common ancestor. In revset notation, this is the set
1834 1839 * "heads(::a and ::b and ...)"
1835 1840 */
1836 1841 static PyObject *find_gca_candidates(indexObject *self, const int *revs,
1837 1842 int revcount)
1838 1843 {
1839 1844 const bitmask allseen = (1ull << revcount) - 1;
1840 1845 const bitmask poison = 1ull << revcount;
1841 1846 PyObject *gca = PyList_New(0);
1842 1847 int i, v, interesting;
1843 1848 int maxrev = -1;
1844 1849 bitmask sp;
1845 1850 bitmask *seen;
1846 1851
1847 1852 if (gca == NULL)
1848 1853 return PyErr_NoMemory();
1849 1854
1850 1855 for (i = 0; i < revcount; i++) {
1851 1856 if (revs[i] > maxrev)
1852 1857 maxrev = revs[i];
1853 1858 }
1854 1859
1855 1860 seen = calloc(sizeof(*seen), maxrev + 1);
1856 1861 if (seen == NULL) {
1857 1862 Py_DECREF(gca);
1858 1863 return PyErr_NoMemory();
1859 1864 }
1860 1865
1861 1866 for (i = 0; i < revcount; i++)
1862 1867 seen[revs[i]] = 1ull << i;
1863 1868
1864 1869 interesting = revcount;
1865 1870
1866 1871 for (v = maxrev; v >= 0 && interesting; v--) {
1867 1872 bitmask sv = seen[v];
1868 1873 int parents[2];
1869 1874
1870 1875 if (!sv)
1871 1876 continue;
1872 1877
1873 1878 if (sv < poison) {
1874 1879 interesting -= 1;
1875 1880 if (sv == allseen) {
1876 1881 PyObject *obj = PyInt_FromLong(v);
1877 1882 if (obj == NULL)
1878 1883 goto bail;
1879 1884 if (PyList_Append(gca, obj) == -1) {
1880 1885 Py_DECREF(obj);
1881 1886 goto bail;
1882 1887 }
1883 1888 sv |= poison;
1884 1889 for (i = 0; i < revcount; i++) {
1885 1890 if (revs[i] == v)
1886 1891 goto done;
1887 1892 }
1888 1893 }
1889 1894 }
1890 1895 if (index_get_parents(self, v, parents, maxrev) < 0)
1891 1896 goto bail;
1892 1897
1893 1898 for (i = 0; i < 2; i++) {
1894 1899 int p = parents[i];
1895 1900 if (p == -1)
1896 1901 continue;
1897 1902 sp = seen[p];
1898 1903 if (sv < poison) {
1899 1904 if (sp == 0) {
1900 1905 seen[p] = sv;
1901 1906 interesting++;
1902 1907 }
1903 1908 else if (sp != sv)
1904 1909 seen[p] |= sv;
1905 1910 } else {
1906 1911 if (sp && sp < poison)
1907 1912 interesting--;
1908 1913 seen[p] = sv;
1909 1914 }
1910 1915 }
1911 1916 }
1912 1917
1913 1918 done:
1914 1919 free(seen);
1915 1920 return gca;
1916 1921 bail:
1917 1922 free(seen);
1918 1923 Py_XDECREF(gca);
1919 1924 return NULL;
1920 1925 }
1921 1926
1922 1927 /*
1923 1928 * Given a disjoint set of revs, return the subset with the longest
1924 1929 * path to the root.
1925 1930 */
1926 1931 static PyObject *find_deepest(indexObject *self, PyObject *revs)
1927 1932 {
1928 1933 const Py_ssize_t revcount = PyList_GET_SIZE(revs);
1929 1934 static const Py_ssize_t capacity = 24;
1930 1935 int *depth, *interesting = NULL;
1931 1936 int i, j, v, ninteresting;
1932 1937 PyObject *dict = NULL, *keys = NULL;
1933 1938 long *seen = NULL;
1934 1939 int maxrev = -1;
1935 1940 long final;
1936 1941
1937 1942 if (revcount > capacity) {
1938 1943 PyErr_Format(PyExc_OverflowError,
1939 1944 "bitset size (%ld) > capacity (%ld)",
1940 1945 (long)revcount, (long)capacity);
1941 1946 return NULL;
1942 1947 }
1943 1948
1944 1949 for (i = 0; i < revcount; i++) {
1945 1950 int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i));
1946 1951 if (n > maxrev)
1947 1952 maxrev = n;
1948 1953 }
1949 1954
1950 1955 depth = calloc(sizeof(*depth), maxrev + 1);
1951 1956 if (depth == NULL)
1952 1957 return PyErr_NoMemory();
1953 1958
1954 1959 seen = calloc(sizeof(*seen), maxrev + 1);
1955 1960 if (seen == NULL) {
1956 1961 PyErr_NoMemory();
1957 1962 goto bail;
1958 1963 }
1959 1964
1960 1965 interesting = calloc(sizeof(*interesting), 2 << revcount);
1961 1966 if (interesting == NULL) {
1962 1967 PyErr_NoMemory();
1963 1968 goto bail;
1964 1969 }
1965 1970
1966 1971 if (PyList_Sort(revs) == -1)
1967 1972 goto bail;
1968 1973
1969 1974 for (i = 0; i < revcount; i++) {
1970 1975 int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i));
1971 1976 long b = 1l << i;
1972 1977 depth[n] = 1;
1973 1978 seen[n] = b;
1974 1979 interesting[b] = 1;
1975 1980 }
1976 1981
1977 1982 ninteresting = (int)revcount;
1978 1983
1979 1984 for (v = maxrev; v >= 0 && ninteresting > 1; v--) {
1980 1985 int dv = depth[v];
1981 1986 int parents[2];
1982 1987 long sv;
1983 1988
1984 1989 if (dv == 0)
1985 1990 continue;
1986 1991
1987 1992 sv = seen[v];
1988 1993 if (index_get_parents(self, v, parents, maxrev) < 0)
1989 1994 goto bail;
1990 1995
1991 1996 for (i = 0; i < 2; i++) {
1992 1997 int p = parents[i];
1993 1998 long nsp, sp;
1994 1999 int dp;
1995 2000
1996 2001 if (p == -1)
1997 2002 continue;
1998 2003
1999 2004 dp = depth[p];
2000 2005 nsp = sp = seen[p];
2001 2006 if (dp <= dv) {
2002 2007 depth[p] = dv + 1;
2003 2008 if (sp != sv) {
2004 2009 interesting[sv] += 1;
2005 2010 nsp = seen[p] = sv;
2006 2011 if (sp) {
2007 2012 interesting[sp] -= 1;
2008 2013 if (interesting[sp] == 0)
2009 2014 ninteresting -= 1;
2010 2015 }
2011 2016 }
2012 2017 }
2013 2018 else if (dv == dp - 1) {
2014 2019 nsp = sp | sv;
2015 2020 if (nsp == sp)
2016 2021 continue;
2017 2022 seen[p] = nsp;
2018 2023 interesting[sp] -= 1;
2019 2024 if (interesting[sp] == 0 && interesting[nsp] > 0)
2020 2025 ninteresting -= 1;
2021 2026 interesting[nsp] += 1;
2022 2027 }
2023 2028 }
2024 2029 interesting[sv] -= 1;
2025 2030 if (interesting[sv] == 0)
2026 2031 ninteresting -= 1;
2027 2032 }
2028 2033
2029 2034 final = 0;
2030 2035 j = ninteresting;
2031 2036 for (i = 0; i < (int)(2 << revcount) && j > 0; i++) {
2032 2037 if (interesting[i] == 0)
2033 2038 continue;
2034 2039 final |= i;
2035 2040 j -= 1;
2036 2041 }
2037 2042 if (final == 0) {
2038 2043 keys = PyList_New(0);
2039 2044 goto bail;
2040 2045 }
2041 2046
2042 2047 dict = PyDict_New();
2043 2048 if (dict == NULL)
2044 2049 goto bail;
2045 2050
2046 2051 for (i = 0; i < revcount; i++) {
2047 2052 PyObject *key;
2048 2053
2049 2054 if ((final & (1 << i)) == 0)
2050 2055 continue;
2051 2056
2052 2057 key = PyList_GET_ITEM(revs, i);
2053 2058 Py_INCREF(key);
2054 2059 Py_INCREF(Py_None);
2055 2060 if (PyDict_SetItem(dict, key, Py_None) == -1) {
2056 2061 Py_DECREF(key);
2057 2062 Py_DECREF(Py_None);
2058 2063 goto bail;
2059 2064 }
2060 2065 }
2061 2066
2062 2067 keys = PyDict_Keys(dict);
2063 2068
2064 2069 bail:
2065 2070 free(depth);
2066 2071 free(seen);
2067 2072 free(interesting);
2068 2073 Py_XDECREF(dict);
2069 2074
2070 2075 return keys;
2071 2076 }
2072 2077
2073 2078 /*
2074 2079 * Given a (possibly overlapping) set of revs, return all the
2075 2080 * common ancestors heads: heads(::args[0] and ::a[1] and ...)
2076 2081 */
2077 2082 static PyObject *index_commonancestorsheads(indexObject *self, PyObject *args)
2078 2083 {
2079 2084 PyObject *ret = NULL;
2080 2085 Py_ssize_t argcount, i, len;
2081 2086 bitmask repeat = 0;
2082 2087 int revcount = 0;
2083 2088 int *revs;
2084 2089
2085 2090 argcount = PySequence_Length(args);
2086 2091 revs = malloc(argcount * sizeof(*revs));
2087 2092 if (argcount > 0 && revs == NULL)
2088 2093 return PyErr_NoMemory();
2089 2094 len = index_length(self) - 1;
2090 2095
2091 2096 for (i = 0; i < argcount; i++) {
2092 2097 static const int capacity = 24;
2093 2098 PyObject *obj = PySequence_GetItem(args, i);
2094 2099 bitmask x;
2095 2100 long val;
2096 2101
2097 2102 if (!PyInt_Check(obj)) {
2098 2103 PyErr_SetString(PyExc_TypeError,
2099 2104 "arguments must all be ints");
2100 2105 Py_DECREF(obj);
2101 2106 goto bail;
2102 2107 }
2103 2108 val = PyInt_AsLong(obj);
2104 2109 Py_DECREF(obj);
2105 2110 if (val == -1) {
2106 2111 ret = PyList_New(0);
2107 2112 goto done;
2108 2113 }
2109 2114 if (val < 0 || val >= len) {
2110 2115 PyErr_SetString(PyExc_IndexError,
2111 2116 "index out of range");
2112 2117 goto bail;
2113 2118 }
2114 2119 /* this cheesy bloom filter lets us avoid some more
2115 2120 * expensive duplicate checks in the common set-is-disjoint
2116 2121 * case */
2117 2122 x = 1ull << (val & 0x3f);
2118 2123 if (repeat & x) {
2119 2124 int k;
2120 2125 for (k = 0; k < revcount; k++) {
2121 2126 if (val == revs[k])
2122 2127 goto duplicate;
2123 2128 }
2124 2129 }
2125 2130 else repeat |= x;
2126 2131 if (revcount >= capacity) {
2127 2132 PyErr_Format(PyExc_OverflowError,
2128 2133 "bitset size (%d) > capacity (%d)",
2129 2134 revcount, capacity);
2130 2135 goto bail;
2131 2136 }
2132 2137 revs[revcount++] = (int)val;
2133 2138 duplicate:;
2134 2139 }
2135 2140
2136 2141 if (revcount == 0) {
2137 2142 ret = PyList_New(0);
2138 2143 goto done;
2139 2144 }
2140 2145 if (revcount == 1) {
2141 2146 PyObject *obj;
2142 2147 ret = PyList_New(1);
2143 2148 if (ret == NULL)
2144 2149 goto bail;
2145 2150 obj = PyInt_FromLong(revs[0]);
2146 2151 if (obj == NULL)
2147 2152 goto bail;
2148 2153 PyList_SET_ITEM(ret, 0, obj);
2149 2154 goto done;
2150 2155 }
2151 2156
2152 2157 ret = find_gca_candidates(self, revs, revcount);
2153 2158 if (ret == NULL)
2154 2159 goto bail;
2155 2160
2156 2161 done:
2157 2162 free(revs);
2158 2163 return ret;
2159 2164
2160 2165 bail:
2161 2166 free(revs);
2162 2167 Py_XDECREF(ret);
2163 2168 return NULL;
2164 2169 }
2165 2170
2166 2171 /*
2167 2172 * Given a (possibly overlapping) set of revs, return the greatest
2168 2173 * common ancestors: those with the longest path to the root.
2169 2174 */
2170 2175 static PyObject *index_ancestors(indexObject *self, PyObject *args)
2171 2176 {
2172 2177 PyObject *ret;
2173 2178 PyObject *gca = index_commonancestorsheads(self, args);
2174 2179 if (gca == NULL)
2175 2180 return NULL;
2176 2181
2177 2182 if (PyList_GET_SIZE(gca) <= 1) {
2178 2183 return gca;
2179 2184 }
2180 2185
2181 2186 ret = find_deepest(self, gca);
2182 2187 Py_DECREF(gca);
2183 2188 return ret;
2184 2189 }
2185 2190
2186 2191 /*
2187 2192 * Invalidate any trie entries introduced by added revs.
2188 2193 */
2189 2194 static void nt_invalidate_added(indexObject *self, Py_ssize_t start)
2190 2195 {
2191 2196 Py_ssize_t i, len = PyList_GET_SIZE(self->added);
2192 2197
2193 2198 for (i = start; i < len; i++) {
2194 2199 PyObject *tuple = PyList_GET_ITEM(self->added, i);
2195 2200 PyObject *node = PyTuple_GET_ITEM(tuple, 7);
2196 2201
2197 2202 nt_insert(self, PyString_AS_STRING(node), -1);
2198 2203 }
2199 2204
2200 2205 if (start == 0)
2201 2206 Py_CLEAR(self->added);
2202 2207 }
2203 2208
2204 2209 /*
2205 2210 * Delete a numeric range of revs, which must be at the end of the
2206 2211 * range, but exclude the sentinel nullid entry.
2207 2212 */
2208 2213 static int index_slice_del(indexObject *self, PyObject *item)
2209 2214 {
2210 2215 Py_ssize_t start, stop, step, slicelength;
2211 2216 Py_ssize_t length = index_length(self);
2212 2217 int ret = 0;
2213 2218
2214 2219 if (PySlice_GetIndicesEx((PySliceObject*)item, length,
2215 2220 &start, &stop, &step, &slicelength) < 0)
2216 2221 return -1;
2217 2222
2218 2223 if (slicelength <= 0)
2219 2224 return 0;
2220 2225
2221 2226 if ((step < 0 && start < stop) || (step > 0 && start > stop))
2222 2227 stop = start;
2223 2228
2224 2229 if (step < 0) {
2225 2230 stop = start + 1;
2226 2231 start = stop + step*(slicelength - 1) - 1;
2227 2232 step = -step;
2228 2233 }
2229 2234
2230 2235 if (step != 1) {
2231 2236 PyErr_SetString(PyExc_ValueError,
2232 2237 "revlog index delete requires step size of 1");
2233 2238 return -1;
2234 2239 }
2235 2240
2236 2241 if (stop != length - 1) {
2237 2242 PyErr_SetString(PyExc_IndexError,
2238 2243 "revlog index deletion indices are invalid");
2239 2244 return -1;
2240 2245 }
2241 2246
2242 2247 if (start < self->length - 1) {
2243 2248 if (self->nt) {
2244 2249 Py_ssize_t i;
2245 2250
2246 2251 for (i = start + 1; i < self->length - 1; i++) {
2247 2252 const char *node = index_node(self, i);
2248 2253
2249 2254 if (node)
2250 2255 nt_insert(self, node, -1);
2251 2256 }
2252 2257 if (self->added)
2253 2258 nt_invalidate_added(self, 0);
2254 2259 if (self->ntrev > start)
2255 2260 self->ntrev = (int)start;
2256 2261 }
2257 2262 self->length = start + 1;
2258 2263 if (start < self->raw_length) {
2259 2264 if (self->cache) {
2260 2265 Py_ssize_t i;
2261 2266 for (i = start; i < self->raw_length; i++)
2262 2267 Py_CLEAR(self->cache[i]);
2263 2268 }
2264 2269 self->raw_length = start;
2265 2270 }
2266 2271 goto done;
2267 2272 }
2268 2273
2269 2274 if (self->nt) {
2270 2275 nt_invalidate_added(self, start - self->length + 1);
2271 2276 if (self->ntrev > start)
2272 2277 self->ntrev = (int)start;
2273 2278 }
2274 2279 if (self->added)
2275 2280 ret = PyList_SetSlice(self->added, start - self->length + 1,
2276 2281 PyList_GET_SIZE(self->added), NULL);
2277 2282 done:
2278 2283 Py_CLEAR(self->headrevs);
2279 2284 return ret;
2280 2285 }
2281 2286
2282 2287 /*
2283 2288 * Supported ops:
2284 2289 *
2285 2290 * slice deletion
2286 2291 * string assignment (extend node->rev mapping)
2287 2292 * string deletion (shrink node->rev mapping)
2288 2293 */
2289 2294 static int index_assign_subscript(indexObject *self, PyObject *item,
2290 2295 PyObject *value)
2291 2296 {
2292 2297 char *node;
2293 2298 Py_ssize_t nodelen;
2294 2299 long rev;
2295 2300
2296 2301 if (PySlice_Check(item) && value == NULL)
2297 2302 return index_slice_del(self, item);
2298 2303
2299 2304 if (node_check(item, &node, &nodelen) == -1)
2300 2305 return -1;
2301 2306
2302 2307 if (value == NULL)
2303 2308 return self->nt ? nt_insert(self, node, -1) : 0;
2304 2309 rev = PyInt_AsLong(value);
2305 2310 if (rev > INT_MAX || rev < 0) {
2306 2311 if (!PyErr_Occurred())
2307 2312 PyErr_SetString(PyExc_ValueError, "rev out of range");
2308 2313 return -1;
2309 2314 }
2310 2315
2311 2316 if (nt_init(self) == -1)
2312 2317 return -1;
2313 2318 return nt_insert(self, node, (int)rev);
2314 2319 }
2315 2320
2316 2321 /*
2317 2322 * Find all RevlogNG entries in an index that has inline data. Update
2318 2323 * the optional "offsets" table with those entries.
2319 2324 */
2320 2325 static Py_ssize_t inline_scan(indexObject *self, const char **offsets)
2321 2326 {
2322 2327 const char *data = PyString_AS_STRING(self->data);
2323 2328 Py_ssize_t pos = 0;
2324 2329 Py_ssize_t end = PyString_GET_SIZE(self->data);
2325 2330 long incr = v1_hdrsize;
2326 2331 Py_ssize_t len = 0;
2327 2332
2328 2333 while (pos + v1_hdrsize <= end && pos >= 0) {
2329 2334 uint32_t comp_len;
2330 2335 /* 3rd element of header is length of compressed inline data */
2331 2336 comp_len = getbe32(data + pos + 8);
2332 2337 incr = v1_hdrsize + comp_len;
2333 2338 if (offsets)
2334 2339 offsets[len] = data + pos;
2335 2340 len++;
2336 2341 pos += incr;
2337 2342 }
2338 2343
2339 2344 if (pos != end) {
2340 2345 if (!PyErr_Occurred())
2341 2346 PyErr_SetString(PyExc_ValueError, "corrupt index file");
2342 2347 return -1;
2343 2348 }
2344 2349
2345 2350 return len;
2346 2351 }
2347 2352
2348 2353 static int index_init(indexObject *self, PyObject *args)
2349 2354 {
2350 2355 PyObject *data_obj, *inlined_obj;
2351 2356 Py_ssize_t size;
2352 2357
2353 2358 /* Initialize before argument-checking to avoid index_dealloc() crash. */
2354 2359 self->raw_length = 0;
2355 2360 self->added = NULL;
2356 2361 self->cache = NULL;
2357 2362 self->data = NULL;
2358 2363 self->headrevs = NULL;
2359 2364 self->filteredrevs = Py_None;
2360 2365 Py_INCREF(Py_None);
2361 2366 self->nt = NULL;
2362 2367 self->offsets = NULL;
2363 2368
2364 2369 if (!PyArg_ParseTuple(args, "OO", &data_obj, &inlined_obj))
2365 2370 return -1;
2366 2371 if (!PyString_Check(data_obj)) {
2367 2372 PyErr_SetString(PyExc_TypeError, "data is not a string");
2368 2373 return -1;
2369 2374 }
2370 2375 size = PyString_GET_SIZE(data_obj);
2371 2376
2372 2377 self->inlined = inlined_obj && PyObject_IsTrue(inlined_obj);
2373 2378 self->data = data_obj;
2374 2379
2375 2380 self->ntlength = self->ntcapacity = 0;
2376 2381 self->ntdepth = self->ntsplits = 0;
2377 2382 self->ntlookups = self->ntmisses = 0;
2378 2383 self->ntrev = -1;
2379 2384 Py_INCREF(self->data);
2380 2385
2381 2386 if (self->inlined) {
2382 2387 Py_ssize_t len = inline_scan(self, NULL);
2383 2388 if (len == -1)
2384 2389 goto bail;
2385 2390 self->raw_length = len;
2386 2391 self->length = len + 1;
2387 2392 } else {
2388 2393 if (size % v1_hdrsize) {
2389 2394 PyErr_SetString(PyExc_ValueError, "corrupt index file");
2390 2395 goto bail;
2391 2396 }
2392 2397 self->raw_length = size / v1_hdrsize;
2393 2398 self->length = self->raw_length + 1;
2394 2399 }
2395 2400
2396 2401 return 0;
2397 2402 bail:
2398 2403 return -1;
2399 2404 }
2400 2405
2401 2406 static PyObject *index_nodemap(indexObject *self)
2402 2407 {
2403 2408 Py_INCREF(self);
2404 2409 return (PyObject *)self;
2405 2410 }
2406 2411
2407 2412 static void index_dealloc(indexObject *self)
2408 2413 {
2409 2414 _index_clearcaches(self);
2410 2415 Py_XDECREF(self->filteredrevs);
2411 2416 Py_XDECREF(self->data);
2412 2417 Py_XDECREF(self->added);
2413 2418 PyObject_Del(self);
2414 2419 }
2415 2420
2416 2421 static PySequenceMethods index_sequence_methods = {
2417 2422 (lenfunc)index_length, /* sq_length */
2418 2423 0, /* sq_concat */
2419 2424 0, /* sq_repeat */
2420 2425 (ssizeargfunc)index_get, /* sq_item */
2421 2426 0, /* sq_slice */
2422 2427 0, /* sq_ass_item */
2423 2428 0, /* sq_ass_slice */
2424 2429 (objobjproc)index_contains, /* sq_contains */
2425 2430 };
2426 2431
2427 2432 static PyMappingMethods index_mapping_methods = {
2428 2433 (lenfunc)index_length, /* mp_length */
2429 2434 (binaryfunc)index_getitem, /* mp_subscript */
2430 2435 (objobjargproc)index_assign_subscript, /* mp_ass_subscript */
2431 2436 };
2432 2437
2433 2438 static PyMethodDef index_methods[] = {
2434 2439 {"ancestors", (PyCFunction)index_ancestors, METH_VARARGS,
2435 2440 "return the gca set of the given revs"},
2436 2441 {"commonancestorsheads", (PyCFunction)index_commonancestorsheads,
2437 2442 METH_VARARGS,
2438 2443 "return the heads of the common ancestors of the given revs"},
2439 2444 {"clearcaches", (PyCFunction)index_clearcaches, METH_NOARGS,
2440 2445 "clear the index caches"},
2441 2446 {"get", (PyCFunction)index_m_get, METH_VARARGS,
2442 2447 "get an index entry"},
2443 2448 {"computephasesmapsets", (PyCFunction)compute_phases_map_sets,
2444 2449 METH_VARARGS, "compute phases"},
2445 2450 {"reachableroots2", (PyCFunction)reachableroots2, METH_VARARGS,
2446 2451 "reachableroots"},
2447 2452 {"headrevs", (PyCFunction)index_headrevs, METH_VARARGS,
2448 2453 "get head revisions"}, /* Can do filtering since 3.2 */
2449 2454 {"headrevsfiltered", (PyCFunction)index_headrevs, METH_VARARGS,
2450 2455 "get filtered head revisions"}, /* Can always do filtering */
2451 2456 {"insert", (PyCFunction)index_insert, METH_VARARGS,
2452 2457 "insert an index entry"},
2453 2458 {"partialmatch", (PyCFunction)index_partialmatch, METH_VARARGS,
2454 2459 "match a potentially ambiguous node ID"},
2455 2460 {"stats", (PyCFunction)index_stats, METH_NOARGS,
2456 2461 "stats for the index"},
2457 2462 {NULL} /* Sentinel */
2458 2463 };
2459 2464
2460 2465 static PyGetSetDef index_getset[] = {
2461 2466 {"nodemap", (getter)index_nodemap, NULL, "nodemap", NULL},
2462 2467 {NULL} /* Sentinel */
2463 2468 };
2464 2469
2465 2470 static PyTypeObject indexType = {
2466 2471 PyObject_HEAD_INIT(NULL)
2467 2472 0, /* ob_size */
2468 2473 "parsers.index", /* tp_name */
2469 2474 sizeof(indexObject), /* tp_basicsize */
2470 2475 0, /* tp_itemsize */
2471 2476 (destructor)index_dealloc, /* tp_dealloc */
2472 2477 0, /* tp_print */
2473 2478 0, /* tp_getattr */
2474 2479 0, /* tp_setattr */
2475 2480 0, /* tp_compare */
2476 2481 0, /* tp_repr */
2477 2482 0, /* tp_as_number */
2478 2483 &index_sequence_methods, /* tp_as_sequence */
2479 2484 &index_mapping_methods, /* tp_as_mapping */
2480 2485 0, /* tp_hash */
2481 2486 0, /* tp_call */
2482 2487 0, /* tp_str */
2483 2488 0, /* tp_getattro */
2484 2489 0, /* tp_setattro */
2485 2490 0, /* tp_as_buffer */
2486 2491 Py_TPFLAGS_DEFAULT, /* tp_flags */
2487 2492 "revlog index", /* tp_doc */
2488 2493 0, /* tp_traverse */
2489 2494 0, /* tp_clear */
2490 2495 0, /* tp_richcompare */
2491 2496 0, /* tp_weaklistoffset */
2492 2497 0, /* tp_iter */
2493 2498 0, /* tp_iternext */
2494 2499 index_methods, /* tp_methods */
2495 2500 0, /* tp_members */
2496 2501 index_getset, /* tp_getset */
2497 2502 0, /* tp_base */
2498 2503 0, /* tp_dict */
2499 2504 0, /* tp_descr_get */
2500 2505 0, /* tp_descr_set */
2501 2506 0, /* tp_dictoffset */
2502 2507 (initproc)index_init, /* tp_init */
2503 2508 0, /* tp_alloc */
2504 2509 };
2505 2510
2506 2511 /*
2507 2512 * returns a tuple of the form (index, index, cache) with elements as
2508 2513 * follows:
2509 2514 *
2510 2515 * index: an index object that lazily parses RevlogNG records
2511 2516 * cache: if data is inlined, a tuple (index_file_content, 0), else None
2512 2517 *
2513 2518 * added complications are for backwards compatibility
2514 2519 */
2515 2520 static PyObject *parse_index2(PyObject *self, PyObject *args)
2516 2521 {
2517 2522 PyObject *tuple = NULL, *cache = NULL;
2518 2523 indexObject *idx;
2519 2524 int ret;
2520 2525
2521 2526 idx = PyObject_New(indexObject, &indexType);
2522 2527 if (idx == NULL)
2523 2528 goto bail;
2524 2529
2525 2530 ret = index_init(idx, args);
2526 2531 if (ret == -1)
2527 2532 goto bail;
2528 2533
2529 2534 if (idx->inlined) {
2530 2535 cache = Py_BuildValue("iO", 0, idx->data);
2531 2536 if (cache == NULL)
2532 2537 goto bail;
2533 2538 } else {
2534 2539 cache = Py_None;
2535 2540 Py_INCREF(cache);
2536 2541 }
2537 2542
2538 2543 tuple = Py_BuildValue("NN", idx, cache);
2539 2544 if (!tuple)
2540 2545 goto bail;
2541 2546 return tuple;
2542 2547
2543 2548 bail:
2544 2549 Py_XDECREF(idx);
2545 2550 Py_XDECREF(cache);
2546 2551 Py_XDECREF(tuple);
2547 2552 return NULL;
2548 2553 }
2549 2554
2550 2555 #define BUMPED_FIX 1
2551 2556 #define USING_SHA_256 2
2552 2557 #define FM1_HEADER_SIZE (4 + 8 + 2 + 2 + 1 + 1 + 1)
2553 2558
2554 2559 static PyObject *readshas(
2555 2560 const char *source, unsigned char num, Py_ssize_t hashwidth)
2556 2561 {
2557 2562 int i;
2558 2563 PyObject *list = PyTuple_New(num);
2559 2564 if (list == NULL) {
2560 2565 return NULL;
2561 2566 }
2562 2567 for (i = 0; i < num; i++) {
2563 2568 PyObject *hash = PyString_FromStringAndSize(source, hashwidth);
2564 2569 if (hash == NULL) {
2565 2570 Py_DECREF(list);
2566 2571 return NULL;
2567 2572 }
2568 2573 PyTuple_SET_ITEM(list, i, hash);
2569 2574 source += hashwidth;
2570 2575 }
2571 2576 return list;
2572 2577 }
2573 2578
2574 2579 static PyObject *fm1readmarker(const char *databegin, const char *dataend,
2575 2580 uint32_t *msize)
2576 2581 {
2577 2582 const char *data = databegin;
2578 2583 const char *meta;
2579 2584
2580 2585 double mtime;
2581 2586 int16_t tz;
2582 2587 uint16_t flags;
2583 2588 unsigned char nsuccs, nparents, nmetadata;
2584 2589 Py_ssize_t hashwidth = 20;
2585 2590
2586 2591 PyObject *prec = NULL, *parents = NULL, *succs = NULL;
2587 2592 PyObject *metadata = NULL, *ret = NULL;
2588 2593 int i;
2589 2594
2590 2595 if (data + FM1_HEADER_SIZE > dataend) {
2591 2596 goto overflow;
2592 2597 }
2593 2598
2594 2599 *msize = getbe32(data);
2595 2600 data += 4;
2596 2601 mtime = getbefloat64(data);
2597 2602 data += 8;
2598 2603 tz = getbeint16(data);
2599 2604 data += 2;
2600 2605 flags = getbeuint16(data);
2601 2606 data += 2;
2602 2607
2603 2608 if (flags & USING_SHA_256) {
2604 2609 hashwidth = 32;
2605 2610 }
2606 2611
2607 2612 nsuccs = (unsigned char)(*data++);
2608 2613 nparents = (unsigned char)(*data++);
2609 2614 nmetadata = (unsigned char)(*data++);
2610 2615
2611 2616 if (databegin + *msize > dataend) {
2612 2617 goto overflow;
2613 2618 }
2614 2619 dataend = databegin + *msize; /* narrow down to marker size */
2615 2620
2616 2621 if (data + hashwidth > dataend) {
2617 2622 goto overflow;
2618 2623 }
2619 2624 prec = PyString_FromStringAndSize(data, hashwidth);
2620 2625 data += hashwidth;
2621 2626 if (prec == NULL) {
2622 2627 goto bail;
2623 2628 }
2624 2629
2625 2630 if (data + nsuccs * hashwidth > dataend) {
2626 2631 goto overflow;
2627 2632 }
2628 2633 succs = readshas(data, nsuccs, hashwidth);
2629 2634 if (succs == NULL) {
2630 2635 goto bail;
2631 2636 }
2632 2637 data += nsuccs * hashwidth;
2633 2638
2634 2639 if (nparents == 1 || nparents == 2) {
2635 2640 if (data + nparents * hashwidth > dataend) {
2636 2641 goto overflow;
2637 2642 }
2638 2643 parents = readshas(data, nparents, hashwidth);
2639 2644 if (parents == NULL) {
2640 2645 goto bail;
2641 2646 }
2642 2647 data += nparents * hashwidth;
2643 2648 } else {
2644 2649 parents = Py_None;
2645 2650 }
2646 2651
2647 2652 if (data + 2 * nmetadata > dataend) {
2648 2653 goto overflow;
2649 2654 }
2650 2655 meta = data + (2 * nmetadata);
2651 2656 metadata = PyTuple_New(nmetadata);
2652 2657 if (metadata == NULL) {
2653 2658 goto bail;
2654 2659 }
2655 2660 for (i = 0; i < nmetadata; i++) {
2656 2661 PyObject *tmp, *left = NULL, *right = NULL;
2657 2662 Py_ssize_t leftsize = (unsigned char)(*data++);
2658 2663 Py_ssize_t rightsize = (unsigned char)(*data++);
2659 2664 if (meta + leftsize + rightsize > dataend) {
2660 2665 goto overflow;
2661 2666 }
2662 2667 left = PyString_FromStringAndSize(meta, leftsize);
2663 2668 meta += leftsize;
2664 2669 right = PyString_FromStringAndSize(meta, rightsize);
2665 2670 meta += rightsize;
2666 2671 tmp = PyTuple_New(2);
2667 2672 if (!left || !right || !tmp) {
2668 2673 Py_XDECREF(left);
2669 2674 Py_XDECREF(right);
2670 2675 Py_XDECREF(tmp);
2671 2676 goto bail;
2672 2677 }
2673 2678 PyTuple_SET_ITEM(tmp, 0, left);
2674 2679 PyTuple_SET_ITEM(tmp, 1, right);
2675 2680 PyTuple_SET_ITEM(metadata, i, tmp);
2676 2681 }
2677 2682 ret = Py_BuildValue("(OOHO(di)O)", prec, succs, flags,
2678 2683 metadata, mtime, (int)tz * 60, parents);
2679 2684 goto bail; /* return successfully */
2680 2685
2681 2686 overflow:
2682 2687 PyErr_SetString(PyExc_ValueError, "overflow in obsstore");
2683 2688 bail:
2684 2689 Py_XDECREF(prec);
2685 2690 Py_XDECREF(succs);
2686 2691 Py_XDECREF(metadata);
2687 2692 if (parents != Py_None)
2688 2693 Py_XDECREF(parents);
2689 2694 return ret;
2690 2695 }
2691 2696
2692 2697
2693 2698 static PyObject *fm1readmarkers(PyObject *self, PyObject *args) {
2694 2699 const char *data, *dataend;
2695 2700 int datalen;
2696 2701 Py_ssize_t offset, stop;
2697 2702 PyObject *markers = NULL;
2698 2703
2699 2704 if (!PyArg_ParseTuple(args, "s#nn", &data, &datalen, &offset, &stop)) {
2700 2705 return NULL;
2701 2706 }
2702 2707 dataend = data + datalen;
2703 2708 data += offset;
2704 2709 markers = PyList_New(0);
2705 2710 if (!markers) {
2706 2711 return NULL;
2707 2712 }
2708 2713 while (offset < stop) {
2709 2714 uint32_t msize;
2710 2715 int error;
2711 2716 PyObject *record = fm1readmarker(data, dataend, &msize);
2712 2717 if (!record) {
2713 2718 goto bail;
2714 2719 }
2715 2720 error = PyList_Append(markers, record);
2716 2721 Py_DECREF(record);
2717 2722 if (error) {
2718 2723 goto bail;
2719 2724 }
2720 2725 data += msize;
2721 2726 offset += msize;
2722 2727 }
2723 2728 return markers;
2724 2729 bail:
2725 2730 Py_DECREF(markers);
2726 2731 return NULL;
2727 2732 }
2728 2733
2729 2734 static char parsers_doc[] = "Efficient content parsing.";
2730 2735
2731 2736 PyObject *encodedir(PyObject *self, PyObject *args);
2732 2737 PyObject *pathencode(PyObject *self, PyObject *args);
2733 2738 PyObject *lowerencode(PyObject *self, PyObject *args);
2734 2739
2735 2740 static PyMethodDef methods[] = {
2736 2741 {"pack_dirstate", pack_dirstate, METH_VARARGS, "pack a dirstate\n"},
2737 2742 {"parse_manifest", parse_manifest, METH_VARARGS, "parse a manifest\n"},
2738 2743 {"parse_dirstate", parse_dirstate, METH_VARARGS, "parse a dirstate\n"},
2739 2744 {"parse_index2", parse_index2, METH_VARARGS, "parse a revlog index\n"},
2740 2745 {"asciilower", asciilower, METH_VARARGS, "lowercase an ASCII string\n"},
2741 2746 {"asciiupper", asciiupper, METH_VARARGS, "uppercase an ASCII string\n"},
2742 2747 {"dict_new_presized", dict_new_presized, METH_VARARGS,
2743 2748 "construct a dict with an expected size\n"},
2744 2749 {"make_file_foldmap", make_file_foldmap, METH_VARARGS,
2745 2750 "make file foldmap\n"},
2746 2751 {"encodedir", encodedir, METH_VARARGS, "encodedir a path\n"},
2747 2752 {"pathencode", pathencode, METH_VARARGS, "fncache-encode a path\n"},
2748 2753 {"lowerencode", lowerencode, METH_VARARGS, "lower-encode a path\n"},
2749 2754 {"fm1readmarkers", fm1readmarkers, METH_VARARGS,
2750 2755 "parse v1 obsolete markers\n"},
2751 2756 {NULL, NULL}
2752 2757 };
2753 2758
2754 2759 void dirs_module_init(PyObject *mod);
2755 2760 void manifest_module_init(PyObject *mod);
2756 2761
2757 2762 static void module_init(PyObject *mod)
2758 2763 {
2759 2764 /* This module constant has two purposes. First, it lets us unit test
2760 2765 * the ImportError raised without hard-coding any error text. This
2761 2766 * means we can change the text in the future without breaking tests,
2762 2767 * even across changesets without a recompile. Second, its presence
2763 2768 * can be used to determine whether the version-checking logic is
2764 2769 * present, which also helps in testing across changesets without a
2765 2770 * recompile. Note that this means the pure-Python version of parsers
2766 2771 * should not have this module constant. */
2767 2772 PyModule_AddStringConstant(mod, "versionerrortext", versionerrortext);
2768 2773
2769 2774 dirs_module_init(mod);
2770 2775 manifest_module_init(mod);
2771 2776
2772 2777 indexType.tp_new = PyType_GenericNew;
2773 2778 if (PyType_Ready(&indexType) < 0 ||
2774 2779 PyType_Ready(&dirstateTupleType) < 0)
2775 2780 return;
2776 2781 Py_INCREF(&indexType);
2777 2782 PyModule_AddObject(mod, "index", (PyObject *)&indexType);
2778 2783 Py_INCREF(&dirstateTupleType);
2779 2784 PyModule_AddObject(mod, "dirstatetuple",
2780 2785 (PyObject *)&dirstateTupleType);
2781 2786
2782 2787 nullentry = Py_BuildValue("iiiiiiis#", 0, 0, 0,
2783 2788 -1, -1, -1, -1, nullid, 20);
2784 2789 if (nullentry)
2785 2790 PyObject_GC_UnTrack(nullentry);
2786 2791 }
2787 2792
2788 2793 static int check_python_version(void)
2789 2794 {
2790 2795 PyObject *sys = PyImport_ImportModule("sys"), *ver;
2791 2796 long hexversion;
2792 2797 if (!sys)
2793 2798 return -1;
2794 2799 ver = PyObject_GetAttrString(sys, "hexversion");
2795 2800 Py_DECREF(sys);
2796 2801 if (!ver)
2797 2802 return -1;
2798 2803 hexversion = PyInt_AsLong(ver);
2799 2804 Py_DECREF(ver);
2800 2805 /* sys.hexversion is a 32-bit number by default, so the -1 case
2801 2806 * should only occur in unusual circumstances (e.g. if sys.hexversion
2802 2807 * is manually set to an invalid value). */
2803 2808 if ((hexversion == -1) || (hexversion >> 16 != PY_VERSION_HEX >> 16)) {
2804 2809 PyErr_Format(PyExc_ImportError, "%s: The Mercurial extension "
2805 2810 "modules were compiled with Python " PY_VERSION ", but "
2806 2811 "Mercurial is currently using Python with sys.hexversion=%ld: "
2807 2812 "Python %s\n at: %s", versionerrortext, hexversion,
2808 2813 Py_GetVersion(), Py_GetProgramFullPath());
2809 2814 return -1;
2810 2815 }
2811 2816 return 0;
2812 2817 }
2813 2818
2814 2819 #ifdef IS_PY3K
2815 2820 static struct PyModuleDef parsers_module = {
2816 2821 PyModuleDef_HEAD_INIT,
2817 2822 "parsers",
2818 2823 parsers_doc,
2819 2824 -1,
2820 2825 methods
2821 2826 };
2822 2827
2823 2828 PyMODINIT_FUNC PyInit_parsers(void)
2824 2829 {
2825 2830 PyObject *mod;
2826 2831
2827 2832 if (check_python_version() == -1)
2828 2833 return;
2829 2834 mod = PyModule_Create(&parsers_module);
2830 2835 module_init(mod);
2831 2836 return mod;
2832 2837 }
2833 2838 #else
2834 2839 PyMODINIT_FUNC initparsers(void)
2835 2840 {
2836 2841 PyObject *mod;
2837 2842
2838 2843 if (check_python_version() == -1)
2839 2844 return;
2840 2845 mod = Py_InitModule3("parsers", methods, parsers_doc);
2841 2846 module_init(mod);
2842 2847 }
2843 2848 #endif
General Comments 0
You need to be logged in to leave comments. Login now