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