marshal.c 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903
  1. /* Write Python objects to files and read them back.
  2. This is primarily intended for writing and reading compiled Python code,
  3. even though dicts, lists, sets and frozensets, not commonly seen in
  4. code objects, are supported.
  5. Version 3 of this protocol properly supports circular links
  6. and sharing. */
  7. #define PY_SSIZE_T_CLEAN
  8. #include "Python.h"
  9. #include "pycore_call.h" // _PyObject_CallNoArgs()
  10. #include "pycore_code.h" // _PyCode_New()
  11. #include "pycore_long.h" // _PyLong_DigitCount
  12. #include "pycore_hashtable.h" // _Py_hashtable_t
  13. #include "marshal.h" // Py_MARSHAL_VERSION
  14. /*[clinic input]
  15. module marshal
  16. [clinic start generated code]*/
  17. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=c982b7930dee17db]*/
  18. #include "clinic/marshal.c.h"
  19. /* High water mark to determine when the marshalled object is dangerously deep
  20. * and risks coring the interpreter. When the object stack gets this deep,
  21. * raise an exception instead of continuing.
  22. * On Windows debug builds, reduce this value.
  23. *
  24. * BUG: https://bugs.python.org/issue33720
  25. * On Windows PGO builds, the r_object function overallocates its stack and
  26. * can cause a stack overflow. We reduce the maximum depth for all Windows
  27. * releases to protect against this.
  28. * #if defined(MS_WINDOWS) && defined(_DEBUG)
  29. */
  30. #if defined(MS_WINDOWS)
  31. #define MAX_MARSHAL_STACK_DEPTH 1000
  32. #elif defined(__wasi__)
  33. #define MAX_MARSHAL_STACK_DEPTH 1500
  34. #else
  35. #define MAX_MARSHAL_STACK_DEPTH 2000
  36. #endif
  37. #define TYPE_NULL '0'
  38. #define TYPE_NONE 'N'
  39. #define TYPE_FALSE 'F'
  40. #define TYPE_TRUE 'T'
  41. #define TYPE_STOPITER 'S'
  42. #define TYPE_ELLIPSIS '.'
  43. #define TYPE_INT 'i'
  44. /* TYPE_INT64 is not generated anymore.
  45. Supported for backward compatibility only. */
  46. #define TYPE_INT64 'I'
  47. #define TYPE_FLOAT 'f'
  48. #define TYPE_BINARY_FLOAT 'g'
  49. #define TYPE_COMPLEX 'x'
  50. #define TYPE_BINARY_COMPLEX 'y'
  51. #define TYPE_LONG 'l'
  52. #define TYPE_STRING 's'
  53. #define TYPE_INTERNED 't'
  54. #define TYPE_REF 'r'
  55. #define TYPE_TUPLE '('
  56. #define TYPE_LIST '['
  57. #define TYPE_DICT '{'
  58. #define TYPE_CODE 'c'
  59. #define TYPE_UNICODE 'u'
  60. #define TYPE_UNKNOWN '?'
  61. #define TYPE_SET '<'
  62. #define TYPE_FROZENSET '>'
  63. #define FLAG_REF '\x80' /* with a type, add obj to index */
  64. #define TYPE_ASCII 'a'
  65. #define TYPE_ASCII_INTERNED 'A'
  66. #define TYPE_SMALL_TUPLE ')'
  67. #define TYPE_SHORT_ASCII 'z'
  68. #define TYPE_SHORT_ASCII_INTERNED 'Z'
  69. #define WFERR_OK 0
  70. #define WFERR_UNMARSHALLABLE 1
  71. #define WFERR_NESTEDTOODEEP 2
  72. #define WFERR_NOMEMORY 3
  73. typedef struct {
  74. FILE *fp;
  75. int error; /* see WFERR_* values */
  76. int depth;
  77. PyObject *str;
  78. char *ptr;
  79. const char *end;
  80. char *buf;
  81. _Py_hashtable_t *hashtable;
  82. int version;
  83. } WFILE;
  84. #define w_byte(c, p) do { \
  85. if ((p)->ptr != (p)->end || w_reserve((p), 1)) \
  86. *(p)->ptr++ = (c); \
  87. } while(0)
  88. static void
  89. w_flush(WFILE *p)
  90. {
  91. assert(p->fp != NULL);
  92. fwrite(p->buf, 1, p->ptr - p->buf, p->fp);
  93. p->ptr = p->buf;
  94. }
  95. static int
  96. w_reserve(WFILE *p, Py_ssize_t needed)
  97. {
  98. Py_ssize_t pos, size, delta;
  99. if (p->ptr == NULL)
  100. return 0; /* An error already occurred */
  101. if (p->fp != NULL) {
  102. w_flush(p);
  103. return needed <= p->end - p->ptr;
  104. }
  105. assert(p->str != NULL);
  106. pos = p->ptr - p->buf;
  107. size = PyBytes_GET_SIZE(p->str);
  108. if (size > 16*1024*1024)
  109. delta = (size >> 3); /* 12.5% overallocation */
  110. else
  111. delta = size + 1024;
  112. delta = Py_MAX(delta, needed);
  113. if (delta > PY_SSIZE_T_MAX - size) {
  114. p->error = WFERR_NOMEMORY;
  115. return 0;
  116. }
  117. size += delta;
  118. if (_PyBytes_Resize(&p->str, size) != 0) {
  119. p->end = p->ptr = p->buf = NULL;
  120. return 0;
  121. }
  122. else {
  123. p->buf = PyBytes_AS_STRING(p->str);
  124. p->ptr = p->buf + pos;
  125. p->end = p->buf + size;
  126. return 1;
  127. }
  128. }
  129. static void
  130. w_string(const void *s, Py_ssize_t n, WFILE *p)
  131. {
  132. Py_ssize_t m;
  133. if (!n || p->ptr == NULL)
  134. return;
  135. m = p->end - p->ptr;
  136. if (p->fp != NULL) {
  137. if (n <= m) {
  138. memcpy(p->ptr, s, n);
  139. p->ptr += n;
  140. }
  141. else {
  142. w_flush(p);
  143. fwrite(s, 1, n, p->fp);
  144. }
  145. }
  146. else {
  147. if (n <= m || w_reserve(p, n - m)) {
  148. memcpy(p->ptr, s, n);
  149. p->ptr += n;
  150. }
  151. }
  152. }
  153. static void
  154. w_short(int x, WFILE *p)
  155. {
  156. w_byte((char)( x & 0xff), p);
  157. w_byte((char)((x>> 8) & 0xff), p);
  158. }
  159. static void
  160. w_long(long x, WFILE *p)
  161. {
  162. w_byte((char)( x & 0xff), p);
  163. w_byte((char)((x>> 8) & 0xff), p);
  164. w_byte((char)((x>>16) & 0xff), p);
  165. w_byte((char)((x>>24) & 0xff), p);
  166. }
  167. #define SIZE32_MAX 0x7FFFFFFF
  168. #if SIZEOF_SIZE_T > 4
  169. # define W_SIZE(n, p) do { \
  170. if ((n) > SIZE32_MAX) { \
  171. (p)->depth--; \
  172. (p)->error = WFERR_UNMARSHALLABLE; \
  173. return; \
  174. } \
  175. w_long((long)(n), p); \
  176. } while(0)
  177. #else
  178. # define W_SIZE w_long
  179. #endif
  180. static void
  181. w_pstring(const void *s, Py_ssize_t n, WFILE *p)
  182. {
  183. W_SIZE(n, p);
  184. w_string(s, n, p);
  185. }
  186. static void
  187. w_short_pstring(const void *s, Py_ssize_t n, WFILE *p)
  188. {
  189. w_byte(Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char), p);
  190. w_string(s, n, p);
  191. }
  192. /* We assume that Python ints are stored internally in base some power of
  193. 2**15; for the sake of portability we'll always read and write them in base
  194. exactly 2**15. */
  195. #define PyLong_MARSHAL_SHIFT 15
  196. #define PyLong_MARSHAL_BASE ((short)1 << PyLong_MARSHAL_SHIFT)
  197. #define PyLong_MARSHAL_MASK (PyLong_MARSHAL_BASE - 1)
  198. #if PyLong_SHIFT % PyLong_MARSHAL_SHIFT != 0
  199. #error "PyLong_SHIFT must be a multiple of PyLong_MARSHAL_SHIFT"
  200. #endif
  201. #define PyLong_MARSHAL_RATIO (PyLong_SHIFT / PyLong_MARSHAL_SHIFT)
  202. #define W_TYPE(t, p) do { \
  203. w_byte((t) | flag, (p)); \
  204. } while(0)
  205. static void
  206. w_PyLong(const PyLongObject *ob, char flag, WFILE *p)
  207. {
  208. Py_ssize_t i, j, n, l;
  209. digit d;
  210. W_TYPE(TYPE_LONG, p);
  211. if (_PyLong_IsZero(ob)) {
  212. w_long((long)0, p);
  213. return;
  214. }
  215. /* set l to number of base PyLong_MARSHAL_BASE digits */
  216. n = _PyLong_DigitCount(ob);
  217. l = (n-1) * PyLong_MARSHAL_RATIO;
  218. d = ob->long_value.ob_digit[n-1];
  219. assert(d != 0); /* a PyLong is always normalized */
  220. do {
  221. d >>= PyLong_MARSHAL_SHIFT;
  222. l++;
  223. } while (d != 0);
  224. if (l > SIZE32_MAX) {
  225. p->depth--;
  226. p->error = WFERR_UNMARSHALLABLE;
  227. return;
  228. }
  229. w_long((long)(_PyLong_IsNegative(ob) ? -l : l), p);
  230. for (i=0; i < n-1; i++) {
  231. d = ob->long_value.ob_digit[i];
  232. for (j=0; j < PyLong_MARSHAL_RATIO; j++) {
  233. w_short(d & PyLong_MARSHAL_MASK, p);
  234. d >>= PyLong_MARSHAL_SHIFT;
  235. }
  236. assert (d == 0);
  237. }
  238. d = ob->long_value.ob_digit[n-1];
  239. do {
  240. w_short(d & PyLong_MARSHAL_MASK, p);
  241. d >>= PyLong_MARSHAL_SHIFT;
  242. } while (d != 0);
  243. }
  244. static void
  245. w_float_bin(double v, WFILE *p)
  246. {
  247. char buf[8];
  248. if (PyFloat_Pack8(v, buf, 1) < 0) {
  249. p->error = WFERR_UNMARSHALLABLE;
  250. return;
  251. }
  252. w_string(buf, 8, p);
  253. }
  254. static void
  255. w_float_str(double v, WFILE *p)
  256. {
  257. char *buf = PyOS_double_to_string(v, 'g', 17, 0, NULL);
  258. if (!buf) {
  259. p->error = WFERR_NOMEMORY;
  260. return;
  261. }
  262. w_short_pstring(buf, strlen(buf), p);
  263. PyMem_Free(buf);
  264. }
  265. static int
  266. w_ref(PyObject *v, char *flag, WFILE *p)
  267. {
  268. _Py_hashtable_entry_t *entry;
  269. int w;
  270. if (p->version < 3 || p->hashtable == NULL)
  271. return 0; /* not writing object references */
  272. /* If it has only one reference, it definitely isn't shared.
  273. * But we use TYPE_REF always for interned string, to PYC file stable
  274. * as possible.
  275. */
  276. if (Py_REFCNT(v) == 1 &&
  277. !(PyUnicode_CheckExact(v) && PyUnicode_CHECK_INTERNED(v))) {
  278. return 0;
  279. }
  280. entry = _Py_hashtable_get_entry(p->hashtable, v);
  281. if (entry != NULL) {
  282. /* write the reference index to the stream */
  283. w = (int)(uintptr_t)entry->value;
  284. /* we don't store "long" indices in the dict */
  285. assert(0 <= w && w <= 0x7fffffff);
  286. w_byte(TYPE_REF, p);
  287. w_long(w, p);
  288. return 1;
  289. } else {
  290. size_t s = p->hashtable->nentries;
  291. /* we don't support long indices */
  292. if (s >= 0x7fffffff) {
  293. PyErr_SetString(PyExc_ValueError, "too many objects");
  294. goto err;
  295. }
  296. w = (int)s;
  297. if (_Py_hashtable_set(p->hashtable, Py_NewRef(v),
  298. (void *)(uintptr_t)w) < 0) {
  299. Py_DECREF(v);
  300. goto err;
  301. }
  302. *flag |= FLAG_REF;
  303. return 0;
  304. }
  305. err:
  306. p->error = WFERR_UNMARSHALLABLE;
  307. return 1;
  308. }
  309. static void
  310. w_complex_object(PyObject *v, char flag, WFILE *p);
  311. static void
  312. w_object(PyObject *v, WFILE *p)
  313. {
  314. char flag = '\0';
  315. p->depth++;
  316. if (p->depth > MAX_MARSHAL_STACK_DEPTH) {
  317. p->error = WFERR_NESTEDTOODEEP;
  318. }
  319. else if (v == NULL) {
  320. w_byte(TYPE_NULL, p);
  321. }
  322. else if (v == Py_None) {
  323. w_byte(TYPE_NONE, p);
  324. }
  325. else if (v == PyExc_StopIteration) {
  326. w_byte(TYPE_STOPITER, p);
  327. }
  328. else if (v == Py_Ellipsis) {
  329. w_byte(TYPE_ELLIPSIS, p);
  330. }
  331. else if (v == Py_False) {
  332. w_byte(TYPE_FALSE, p);
  333. }
  334. else if (v == Py_True) {
  335. w_byte(TYPE_TRUE, p);
  336. }
  337. else if (!w_ref(v, &flag, p))
  338. w_complex_object(v, flag, p);
  339. p->depth--;
  340. }
  341. static void
  342. w_complex_object(PyObject *v, char flag, WFILE *p)
  343. {
  344. Py_ssize_t i, n;
  345. if (PyLong_CheckExact(v)) {
  346. int overflow;
  347. long x = PyLong_AsLongAndOverflow(v, &overflow);
  348. if (overflow) {
  349. w_PyLong((PyLongObject *)v, flag, p);
  350. }
  351. else {
  352. #if SIZEOF_LONG > 4
  353. long y = Py_ARITHMETIC_RIGHT_SHIFT(long, x, 31);
  354. if (y && y != -1) {
  355. /* Too large for TYPE_INT */
  356. w_PyLong((PyLongObject*)v, flag, p);
  357. }
  358. else
  359. #endif
  360. {
  361. W_TYPE(TYPE_INT, p);
  362. w_long(x, p);
  363. }
  364. }
  365. }
  366. else if (PyFloat_CheckExact(v)) {
  367. if (p->version > 1) {
  368. W_TYPE(TYPE_BINARY_FLOAT, p);
  369. w_float_bin(PyFloat_AS_DOUBLE(v), p);
  370. }
  371. else {
  372. W_TYPE(TYPE_FLOAT, p);
  373. w_float_str(PyFloat_AS_DOUBLE(v), p);
  374. }
  375. }
  376. else if (PyComplex_CheckExact(v)) {
  377. if (p->version > 1) {
  378. W_TYPE(TYPE_BINARY_COMPLEX, p);
  379. w_float_bin(PyComplex_RealAsDouble(v), p);
  380. w_float_bin(PyComplex_ImagAsDouble(v), p);
  381. }
  382. else {
  383. W_TYPE(TYPE_COMPLEX, p);
  384. w_float_str(PyComplex_RealAsDouble(v), p);
  385. w_float_str(PyComplex_ImagAsDouble(v), p);
  386. }
  387. }
  388. else if (PyBytes_CheckExact(v)) {
  389. W_TYPE(TYPE_STRING, p);
  390. w_pstring(PyBytes_AS_STRING(v), PyBytes_GET_SIZE(v), p);
  391. }
  392. else if (PyUnicode_CheckExact(v)) {
  393. if (p->version >= 4 && PyUnicode_IS_ASCII(v)) {
  394. int is_short = PyUnicode_GET_LENGTH(v) < 256;
  395. if (is_short) {
  396. if (PyUnicode_CHECK_INTERNED(v))
  397. W_TYPE(TYPE_SHORT_ASCII_INTERNED, p);
  398. else
  399. W_TYPE(TYPE_SHORT_ASCII, p);
  400. w_short_pstring(PyUnicode_1BYTE_DATA(v),
  401. PyUnicode_GET_LENGTH(v), p);
  402. }
  403. else {
  404. if (PyUnicode_CHECK_INTERNED(v))
  405. W_TYPE(TYPE_ASCII_INTERNED, p);
  406. else
  407. W_TYPE(TYPE_ASCII, p);
  408. w_pstring(PyUnicode_1BYTE_DATA(v),
  409. PyUnicode_GET_LENGTH(v), p);
  410. }
  411. }
  412. else {
  413. PyObject *utf8;
  414. utf8 = PyUnicode_AsEncodedString(v, "utf8", "surrogatepass");
  415. if (utf8 == NULL) {
  416. p->depth--;
  417. p->error = WFERR_UNMARSHALLABLE;
  418. return;
  419. }
  420. if (p->version >= 3 && PyUnicode_CHECK_INTERNED(v))
  421. W_TYPE(TYPE_INTERNED, p);
  422. else
  423. W_TYPE(TYPE_UNICODE, p);
  424. w_pstring(PyBytes_AS_STRING(utf8), PyBytes_GET_SIZE(utf8), p);
  425. Py_DECREF(utf8);
  426. }
  427. }
  428. else if (PyTuple_CheckExact(v)) {
  429. n = PyTuple_GET_SIZE(v);
  430. if (p->version >= 4 && n < 256) {
  431. W_TYPE(TYPE_SMALL_TUPLE, p);
  432. w_byte((unsigned char)n, p);
  433. }
  434. else {
  435. W_TYPE(TYPE_TUPLE, p);
  436. W_SIZE(n, p);
  437. }
  438. for (i = 0; i < n; i++) {
  439. w_object(PyTuple_GET_ITEM(v, i), p);
  440. }
  441. }
  442. else if (PyList_CheckExact(v)) {
  443. W_TYPE(TYPE_LIST, p);
  444. n = PyList_GET_SIZE(v);
  445. W_SIZE(n, p);
  446. for (i = 0; i < n; i++) {
  447. w_object(PyList_GET_ITEM(v, i), p);
  448. }
  449. }
  450. else if (PyDict_CheckExact(v)) {
  451. Py_ssize_t pos;
  452. PyObject *key, *value;
  453. W_TYPE(TYPE_DICT, p);
  454. /* This one is NULL object terminated! */
  455. pos = 0;
  456. while (PyDict_Next(v, &pos, &key, &value)) {
  457. w_object(key, p);
  458. w_object(value, p);
  459. }
  460. w_object((PyObject *)NULL, p);
  461. }
  462. else if (PyAnySet_CheckExact(v)) {
  463. PyObject *value;
  464. Py_ssize_t pos = 0;
  465. Py_hash_t hash;
  466. if (PyFrozenSet_CheckExact(v))
  467. W_TYPE(TYPE_FROZENSET, p);
  468. else
  469. W_TYPE(TYPE_SET, p);
  470. n = PySet_GET_SIZE(v);
  471. W_SIZE(n, p);
  472. // bpo-37596: To support reproducible builds, sets and frozensets need
  473. // to have their elements serialized in a consistent order (even when
  474. // they have been scrambled by hash randomization). To ensure this, we
  475. // use an order equivalent to sorted(v, key=marshal.dumps):
  476. PyObject *pairs = PyList_New(n);
  477. if (pairs == NULL) {
  478. p->error = WFERR_NOMEMORY;
  479. return;
  480. }
  481. Py_ssize_t i = 0;
  482. while (_PySet_NextEntry(v, &pos, &value, &hash)) {
  483. PyObject *dump = PyMarshal_WriteObjectToString(value, p->version);
  484. if (dump == NULL) {
  485. p->error = WFERR_UNMARSHALLABLE;
  486. Py_DECREF(pairs);
  487. return;
  488. }
  489. PyObject *pair = PyTuple_Pack(2, dump, value);
  490. Py_DECREF(dump);
  491. if (pair == NULL) {
  492. p->error = WFERR_NOMEMORY;
  493. Py_DECREF(pairs);
  494. return;
  495. }
  496. PyList_SET_ITEM(pairs, i++, pair);
  497. }
  498. assert(i == n);
  499. if (PyList_Sort(pairs)) {
  500. p->error = WFERR_NOMEMORY;
  501. Py_DECREF(pairs);
  502. return;
  503. }
  504. for (Py_ssize_t i = 0; i < n; i++) {
  505. PyObject *pair = PyList_GET_ITEM(pairs, i);
  506. value = PyTuple_GET_ITEM(pair, 1);
  507. w_object(value, p);
  508. }
  509. Py_DECREF(pairs);
  510. }
  511. else if (PyCode_Check(v)) {
  512. PyCodeObject *co = (PyCodeObject *)v;
  513. PyObject *co_code = _PyCode_GetCode(co);
  514. if (co_code == NULL) {
  515. p->error = WFERR_NOMEMORY;
  516. return;
  517. }
  518. W_TYPE(TYPE_CODE, p);
  519. w_long(co->co_argcount, p);
  520. w_long(co->co_posonlyargcount, p);
  521. w_long(co->co_kwonlyargcount, p);
  522. w_long(co->co_stacksize, p);
  523. w_long(co->co_flags, p);
  524. w_object(co_code, p);
  525. w_object(co->co_consts, p);
  526. w_object(co->co_names, p);
  527. w_object(co->co_localsplusnames, p);
  528. w_object(co->co_localspluskinds, p);
  529. w_object(co->co_filename, p);
  530. w_object(co->co_name, p);
  531. w_object(co->co_qualname, p);
  532. w_long(co->co_firstlineno, p);
  533. w_object(co->co_linetable, p);
  534. w_object(co->co_exceptiontable, p);
  535. Py_DECREF(co_code);
  536. }
  537. else if (PyObject_CheckBuffer(v)) {
  538. /* Write unknown bytes-like objects as a bytes object */
  539. Py_buffer view;
  540. if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) != 0) {
  541. w_byte(TYPE_UNKNOWN, p);
  542. p->depth--;
  543. p->error = WFERR_UNMARSHALLABLE;
  544. return;
  545. }
  546. W_TYPE(TYPE_STRING, p);
  547. w_pstring(view.buf, view.len, p);
  548. PyBuffer_Release(&view);
  549. }
  550. else {
  551. W_TYPE(TYPE_UNKNOWN, p);
  552. p->error = WFERR_UNMARSHALLABLE;
  553. }
  554. }
  555. static void
  556. w_decref_entry(void *key)
  557. {
  558. PyObject *entry_key = (PyObject *)key;
  559. Py_XDECREF(entry_key);
  560. }
  561. static int
  562. w_init_refs(WFILE *wf, int version)
  563. {
  564. if (version >= 3) {
  565. wf->hashtable = _Py_hashtable_new_full(_Py_hashtable_hash_ptr,
  566. _Py_hashtable_compare_direct,
  567. w_decref_entry, NULL, NULL);
  568. if (wf->hashtable == NULL) {
  569. PyErr_NoMemory();
  570. return -1;
  571. }
  572. }
  573. return 0;
  574. }
  575. static void
  576. w_clear_refs(WFILE *wf)
  577. {
  578. if (wf->hashtable != NULL) {
  579. _Py_hashtable_destroy(wf->hashtable);
  580. }
  581. }
  582. /* version currently has no effect for writing ints. */
  583. /* Note that while the documentation states that this function
  584. * can error, currently it never does. Setting an exception in
  585. * this function should be regarded as an API-breaking change.
  586. */
  587. void
  588. PyMarshal_WriteLongToFile(long x, FILE *fp, int version)
  589. {
  590. char buf[4];
  591. WFILE wf;
  592. memset(&wf, 0, sizeof(wf));
  593. wf.fp = fp;
  594. wf.ptr = wf.buf = buf;
  595. wf.end = wf.ptr + sizeof(buf);
  596. wf.error = WFERR_OK;
  597. wf.version = version;
  598. w_long(x, &wf);
  599. w_flush(&wf);
  600. }
  601. void
  602. PyMarshal_WriteObjectToFile(PyObject *x, FILE *fp, int version)
  603. {
  604. char buf[BUFSIZ];
  605. WFILE wf;
  606. if (PySys_Audit("marshal.dumps", "Oi", x, version) < 0) {
  607. return; /* caller must check PyErr_Occurred() */
  608. }
  609. memset(&wf, 0, sizeof(wf));
  610. wf.fp = fp;
  611. wf.ptr = wf.buf = buf;
  612. wf.end = wf.ptr + sizeof(buf);
  613. wf.error = WFERR_OK;
  614. wf.version = version;
  615. if (w_init_refs(&wf, version)) {
  616. return; /* caller must check PyErr_Occurred() */
  617. }
  618. w_object(x, &wf);
  619. w_clear_refs(&wf);
  620. w_flush(&wf);
  621. }
  622. typedef struct {
  623. FILE *fp;
  624. int depth;
  625. PyObject *readable; /* Stream-like object being read from */
  626. const char *ptr;
  627. const char *end;
  628. char *buf;
  629. Py_ssize_t buf_size;
  630. PyObject *refs; /* a list */
  631. } RFILE;
  632. static const char *
  633. r_string(Py_ssize_t n, RFILE *p)
  634. {
  635. Py_ssize_t read = -1;
  636. if (p->ptr != NULL) {
  637. /* Fast path for loads() */
  638. const char *res = p->ptr;
  639. Py_ssize_t left = p->end - p->ptr;
  640. if (left < n) {
  641. PyErr_SetString(PyExc_EOFError,
  642. "marshal data too short");
  643. return NULL;
  644. }
  645. p->ptr += n;
  646. return res;
  647. }
  648. if (p->buf == NULL) {
  649. p->buf = PyMem_Malloc(n);
  650. if (p->buf == NULL) {
  651. PyErr_NoMemory();
  652. return NULL;
  653. }
  654. p->buf_size = n;
  655. }
  656. else if (p->buf_size < n) {
  657. char *tmp = PyMem_Realloc(p->buf, n);
  658. if (tmp == NULL) {
  659. PyErr_NoMemory();
  660. return NULL;
  661. }
  662. p->buf = tmp;
  663. p->buf_size = n;
  664. }
  665. if (!p->readable) {
  666. assert(p->fp != NULL);
  667. read = fread(p->buf, 1, n, p->fp);
  668. }
  669. else {
  670. PyObject *res, *mview;
  671. Py_buffer buf;
  672. if (PyBuffer_FillInfo(&buf, NULL, p->buf, n, 0, PyBUF_CONTIG) == -1)
  673. return NULL;
  674. mview = PyMemoryView_FromBuffer(&buf);
  675. if (mview == NULL)
  676. return NULL;
  677. res = _PyObject_CallMethod(p->readable, &_Py_ID(readinto), "N", mview);
  678. if (res != NULL) {
  679. read = PyNumber_AsSsize_t(res, PyExc_ValueError);
  680. Py_DECREF(res);
  681. }
  682. }
  683. if (read != n) {
  684. if (!PyErr_Occurred()) {
  685. if (read > n)
  686. PyErr_Format(PyExc_ValueError,
  687. "read() returned too much data: "
  688. "%zd bytes requested, %zd returned",
  689. n, read);
  690. else
  691. PyErr_SetString(PyExc_EOFError,
  692. "EOF read where not expected");
  693. }
  694. return NULL;
  695. }
  696. return p->buf;
  697. }
  698. static int
  699. r_byte(RFILE *p)
  700. {
  701. if (p->ptr != NULL) {
  702. if (p->ptr < p->end) {
  703. return (unsigned char) *p->ptr++;
  704. }
  705. }
  706. else if (!p->readable) {
  707. assert(p->fp);
  708. int c = getc(p->fp);
  709. if (c != EOF) {
  710. return c;
  711. }
  712. }
  713. else {
  714. const char *ptr = r_string(1, p);
  715. if (ptr != NULL) {
  716. return *(const unsigned char *) ptr;
  717. }
  718. return EOF;
  719. }
  720. PyErr_SetString(PyExc_EOFError,
  721. "EOF read where not expected");
  722. return EOF;
  723. }
  724. static int
  725. r_short(RFILE *p)
  726. {
  727. short x = -1;
  728. const unsigned char *buffer;
  729. buffer = (const unsigned char *) r_string(2, p);
  730. if (buffer != NULL) {
  731. x = buffer[0];
  732. x |= buffer[1] << 8;
  733. /* Sign-extension, in case short greater than 16 bits */
  734. x |= -(x & 0x8000);
  735. }
  736. return x;
  737. }
  738. static long
  739. r_long(RFILE *p)
  740. {
  741. long x = -1;
  742. const unsigned char *buffer;
  743. buffer = (const unsigned char *) r_string(4, p);
  744. if (buffer != NULL) {
  745. x = buffer[0];
  746. x |= (long)buffer[1] << 8;
  747. x |= (long)buffer[2] << 16;
  748. x |= (long)buffer[3] << 24;
  749. #if SIZEOF_LONG > 4
  750. /* Sign extension for 64-bit machines */
  751. x |= -(x & 0x80000000L);
  752. #endif
  753. }
  754. return x;
  755. }
  756. /* r_long64 deals with the TYPE_INT64 code. */
  757. static PyObject *
  758. r_long64(RFILE *p)
  759. {
  760. const unsigned char *buffer = (const unsigned char *) r_string(8, p);
  761. if (buffer == NULL) {
  762. return NULL;
  763. }
  764. return _PyLong_FromByteArray(buffer, 8,
  765. 1 /* little endian */,
  766. 1 /* signed */);
  767. }
  768. static PyObject *
  769. r_PyLong(RFILE *p)
  770. {
  771. PyLongObject *ob;
  772. long n, size, i;
  773. int j, md, shorts_in_top_digit;
  774. digit d;
  775. n = r_long(p);
  776. if (n == 0)
  777. return (PyObject *)_PyLong_New(0);
  778. if (n == -1 && PyErr_Occurred()) {
  779. return NULL;
  780. }
  781. if (n < -SIZE32_MAX || n > SIZE32_MAX) {
  782. PyErr_SetString(PyExc_ValueError,
  783. "bad marshal data (long size out of range)");
  784. return NULL;
  785. }
  786. size = 1 + (Py_ABS(n) - 1) / PyLong_MARSHAL_RATIO;
  787. shorts_in_top_digit = 1 + (Py_ABS(n) - 1) % PyLong_MARSHAL_RATIO;
  788. ob = _PyLong_New(size);
  789. if (ob == NULL)
  790. return NULL;
  791. _PyLong_SetSignAndDigitCount(ob, n < 0 ? -1 : 1, size);
  792. for (i = 0; i < size-1; i++) {
  793. d = 0;
  794. for (j=0; j < PyLong_MARSHAL_RATIO; j++) {
  795. md = r_short(p);
  796. if (md < 0 || md > PyLong_MARSHAL_BASE)
  797. goto bad_digit;
  798. d += (digit)md << j*PyLong_MARSHAL_SHIFT;
  799. }
  800. ob->long_value.ob_digit[i] = d;
  801. }
  802. d = 0;
  803. for (j=0; j < shorts_in_top_digit; j++) {
  804. md = r_short(p);
  805. if (md < 0 || md > PyLong_MARSHAL_BASE)
  806. goto bad_digit;
  807. /* topmost marshal digit should be nonzero */
  808. if (md == 0 && j == shorts_in_top_digit - 1) {
  809. Py_DECREF(ob);
  810. PyErr_SetString(PyExc_ValueError,
  811. "bad marshal data (unnormalized long data)");
  812. return NULL;
  813. }
  814. d += (digit)md << j*PyLong_MARSHAL_SHIFT;
  815. }
  816. assert(!PyErr_Occurred());
  817. /* top digit should be nonzero, else the resulting PyLong won't be
  818. normalized */
  819. ob->long_value.ob_digit[size-1] = d;
  820. return (PyObject *)ob;
  821. bad_digit:
  822. Py_DECREF(ob);
  823. if (!PyErr_Occurred()) {
  824. PyErr_SetString(PyExc_ValueError,
  825. "bad marshal data (digit out of range in long)");
  826. }
  827. return NULL;
  828. }
  829. static double
  830. r_float_bin(RFILE *p)
  831. {
  832. const char *buf = r_string(8, p);
  833. if (buf == NULL)
  834. return -1;
  835. return PyFloat_Unpack8(buf, 1);
  836. }
  837. /* Issue #33720: Disable inlining for reducing the C stack consumption
  838. on PGO builds. */
  839. Py_NO_INLINE static double
  840. r_float_str(RFILE *p)
  841. {
  842. int n;
  843. char buf[256];
  844. const char *ptr;
  845. n = r_byte(p);
  846. if (n == EOF) {
  847. return -1;
  848. }
  849. ptr = r_string(n, p);
  850. if (ptr == NULL) {
  851. return -1;
  852. }
  853. memcpy(buf, ptr, n);
  854. buf[n] = '\0';
  855. return PyOS_string_to_double(buf, NULL, NULL);
  856. }
  857. /* allocate the reflist index for a new object. Return -1 on failure */
  858. static Py_ssize_t
  859. r_ref_reserve(int flag, RFILE *p)
  860. {
  861. if (flag) { /* currently only FLAG_REF is defined */
  862. Py_ssize_t idx = PyList_GET_SIZE(p->refs);
  863. if (idx >= 0x7ffffffe) {
  864. PyErr_SetString(PyExc_ValueError, "bad marshal data (index list too large)");
  865. return -1;
  866. }
  867. if (PyList_Append(p->refs, Py_None) < 0)
  868. return -1;
  869. return idx;
  870. } else
  871. return 0;
  872. }
  873. /* insert the new object 'o' to the reflist at previously
  874. * allocated index 'idx'.
  875. * 'o' can be NULL, in which case nothing is done.
  876. * if 'o' was non-NULL, and the function succeeds, 'o' is returned.
  877. * if 'o' was non-NULL, and the function fails, 'o' is released and
  878. * NULL returned. This simplifies error checking at the call site since
  879. * a single test for NULL for the function result is enough.
  880. */
  881. static PyObject *
  882. r_ref_insert(PyObject *o, Py_ssize_t idx, int flag, RFILE *p)
  883. {
  884. if (o != NULL && flag) { /* currently only FLAG_REF is defined */
  885. PyObject *tmp = PyList_GET_ITEM(p->refs, idx);
  886. PyList_SET_ITEM(p->refs, idx, Py_NewRef(o));
  887. Py_DECREF(tmp);
  888. }
  889. return o;
  890. }
  891. /* combination of both above, used when an object can be
  892. * created whenever it is seen in the file, as opposed to
  893. * after having loaded its sub-objects.
  894. */
  895. static PyObject *
  896. r_ref(PyObject *o, int flag, RFILE *p)
  897. {
  898. assert(flag & FLAG_REF);
  899. if (o == NULL)
  900. return NULL;
  901. if (PyList_Append(p->refs, o) < 0) {
  902. Py_DECREF(o); /* release the new object */
  903. return NULL;
  904. }
  905. return o;
  906. }
  907. static PyObject *
  908. r_object(RFILE *p)
  909. {
  910. /* NULL is a valid return value, it does not necessarily means that
  911. an exception is set. */
  912. PyObject *v, *v2;
  913. Py_ssize_t idx = 0;
  914. long i, n;
  915. int type, code = r_byte(p);
  916. int flag, is_interned = 0;
  917. PyObject *retval = NULL;
  918. if (code == EOF) {
  919. if (PyErr_ExceptionMatches(PyExc_EOFError)) {
  920. PyErr_SetString(PyExc_EOFError,
  921. "EOF read where object expected");
  922. }
  923. return NULL;
  924. }
  925. p->depth++;
  926. if (p->depth > MAX_MARSHAL_STACK_DEPTH) {
  927. p->depth--;
  928. PyErr_SetString(PyExc_ValueError, "recursion limit exceeded");
  929. return NULL;
  930. }
  931. flag = code & FLAG_REF;
  932. type = code & ~FLAG_REF;
  933. #define R_REF(O) do{\
  934. if (flag) \
  935. O = r_ref(O, flag, p);\
  936. } while (0)
  937. switch (type) {
  938. case TYPE_NULL:
  939. break;
  940. case TYPE_NONE:
  941. retval = Py_NewRef(Py_None);
  942. break;
  943. case TYPE_STOPITER:
  944. retval = Py_NewRef(PyExc_StopIteration);
  945. break;
  946. case TYPE_ELLIPSIS:
  947. retval = Py_NewRef(Py_Ellipsis);
  948. break;
  949. case TYPE_FALSE:
  950. retval = Py_NewRef(Py_False);
  951. break;
  952. case TYPE_TRUE:
  953. retval = Py_NewRef(Py_True);
  954. break;
  955. case TYPE_INT:
  956. n = r_long(p);
  957. if (n == -1 && PyErr_Occurred()) {
  958. break;
  959. }
  960. retval = PyLong_FromLong(n);
  961. R_REF(retval);
  962. break;
  963. case TYPE_INT64:
  964. retval = r_long64(p);
  965. R_REF(retval);
  966. break;
  967. case TYPE_LONG:
  968. retval = r_PyLong(p);
  969. R_REF(retval);
  970. break;
  971. case TYPE_FLOAT:
  972. {
  973. double x = r_float_str(p);
  974. if (x == -1.0 && PyErr_Occurred())
  975. break;
  976. retval = PyFloat_FromDouble(x);
  977. R_REF(retval);
  978. break;
  979. }
  980. case TYPE_BINARY_FLOAT:
  981. {
  982. double x = r_float_bin(p);
  983. if (x == -1.0 && PyErr_Occurred())
  984. break;
  985. retval = PyFloat_FromDouble(x);
  986. R_REF(retval);
  987. break;
  988. }
  989. case TYPE_COMPLEX:
  990. {
  991. Py_complex c;
  992. c.real = r_float_str(p);
  993. if (c.real == -1.0 && PyErr_Occurred())
  994. break;
  995. c.imag = r_float_str(p);
  996. if (c.imag == -1.0 && PyErr_Occurred())
  997. break;
  998. retval = PyComplex_FromCComplex(c);
  999. R_REF(retval);
  1000. break;
  1001. }
  1002. case TYPE_BINARY_COMPLEX:
  1003. {
  1004. Py_complex c;
  1005. c.real = r_float_bin(p);
  1006. if (c.real == -1.0 && PyErr_Occurred())
  1007. break;
  1008. c.imag = r_float_bin(p);
  1009. if (c.imag == -1.0 && PyErr_Occurred())
  1010. break;
  1011. retval = PyComplex_FromCComplex(c);
  1012. R_REF(retval);
  1013. break;
  1014. }
  1015. case TYPE_STRING:
  1016. {
  1017. const char *ptr;
  1018. n = r_long(p);
  1019. if (n < 0 || n > SIZE32_MAX) {
  1020. if (!PyErr_Occurred()) {
  1021. PyErr_SetString(PyExc_ValueError,
  1022. "bad marshal data (bytes object size out of range)");
  1023. }
  1024. break;
  1025. }
  1026. v = PyBytes_FromStringAndSize((char *)NULL, n);
  1027. if (v == NULL)
  1028. break;
  1029. ptr = r_string(n, p);
  1030. if (ptr == NULL) {
  1031. Py_DECREF(v);
  1032. break;
  1033. }
  1034. memcpy(PyBytes_AS_STRING(v), ptr, n);
  1035. retval = v;
  1036. R_REF(retval);
  1037. break;
  1038. }
  1039. case TYPE_ASCII_INTERNED:
  1040. is_interned = 1;
  1041. /* fall through */
  1042. case TYPE_ASCII:
  1043. n = r_long(p);
  1044. if (n < 0 || n > SIZE32_MAX) {
  1045. if (!PyErr_Occurred()) {
  1046. PyErr_SetString(PyExc_ValueError,
  1047. "bad marshal data (string size out of range)");
  1048. }
  1049. break;
  1050. }
  1051. goto _read_ascii;
  1052. case TYPE_SHORT_ASCII_INTERNED:
  1053. is_interned = 1;
  1054. /* fall through */
  1055. case TYPE_SHORT_ASCII:
  1056. n = r_byte(p);
  1057. if (n == EOF) {
  1058. break;
  1059. }
  1060. _read_ascii:
  1061. {
  1062. const char *ptr;
  1063. ptr = r_string(n, p);
  1064. if (ptr == NULL)
  1065. break;
  1066. v = PyUnicode_FromKindAndData(PyUnicode_1BYTE_KIND, ptr, n);
  1067. if (v == NULL)
  1068. break;
  1069. if (is_interned)
  1070. PyUnicode_InternInPlace(&v);
  1071. retval = v;
  1072. R_REF(retval);
  1073. break;
  1074. }
  1075. case TYPE_INTERNED:
  1076. is_interned = 1;
  1077. /* fall through */
  1078. case TYPE_UNICODE:
  1079. {
  1080. const char *buffer;
  1081. n = r_long(p);
  1082. if (n < 0 || n > SIZE32_MAX) {
  1083. if (!PyErr_Occurred()) {
  1084. PyErr_SetString(PyExc_ValueError,
  1085. "bad marshal data (string size out of range)");
  1086. }
  1087. break;
  1088. }
  1089. if (n != 0) {
  1090. buffer = r_string(n, p);
  1091. if (buffer == NULL)
  1092. break;
  1093. v = PyUnicode_DecodeUTF8(buffer, n, "surrogatepass");
  1094. }
  1095. else {
  1096. v = PyUnicode_New(0, 0);
  1097. }
  1098. if (v == NULL)
  1099. break;
  1100. if (is_interned)
  1101. PyUnicode_InternInPlace(&v);
  1102. retval = v;
  1103. R_REF(retval);
  1104. break;
  1105. }
  1106. case TYPE_SMALL_TUPLE:
  1107. n = r_byte(p);
  1108. if (n == EOF) {
  1109. break;
  1110. }
  1111. goto _read_tuple;
  1112. case TYPE_TUPLE:
  1113. n = r_long(p);
  1114. if (n < 0 || n > SIZE32_MAX) {
  1115. if (!PyErr_Occurred()) {
  1116. PyErr_SetString(PyExc_ValueError,
  1117. "bad marshal data (tuple size out of range)");
  1118. }
  1119. break;
  1120. }
  1121. _read_tuple:
  1122. v = PyTuple_New(n);
  1123. R_REF(v);
  1124. if (v == NULL)
  1125. break;
  1126. for (i = 0; i < n; i++) {
  1127. v2 = r_object(p);
  1128. if ( v2 == NULL ) {
  1129. if (!PyErr_Occurred())
  1130. PyErr_SetString(PyExc_TypeError,
  1131. "NULL object in marshal data for tuple");
  1132. Py_SETREF(v, NULL);
  1133. break;
  1134. }
  1135. PyTuple_SET_ITEM(v, i, v2);
  1136. }
  1137. retval = v;
  1138. break;
  1139. case TYPE_LIST:
  1140. n = r_long(p);
  1141. if (n < 0 || n > SIZE32_MAX) {
  1142. if (!PyErr_Occurred()) {
  1143. PyErr_SetString(PyExc_ValueError,
  1144. "bad marshal data (list size out of range)");
  1145. }
  1146. break;
  1147. }
  1148. v = PyList_New(n);
  1149. R_REF(v);
  1150. if (v == NULL)
  1151. break;
  1152. for (i = 0; i < n; i++) {
  1153. v2 = r_object(p);
  1154. if ( v2 == NULL ) {
  1155. if (!PyErr_Occurred())
  1156. PyErr_SetString(PyExc_TypeError,
  1157. "NULL object in marshal data for list");
  1158. Py_SETREF(v, NULL);
  1159. break;
  1160. }
  1161. PyList_SET_ITEM(v, i, v2);
  1162. }
  1163. retval = v;
  1164. break;
  1165. case TYPE_DICT:
  1166. v = PyDict_New();
  1167. R_REF(v);
  1168. if (v == NULL)
  1169. break;
  1170. for (;;) {
  1171. PyObject *key, *val;
  1172. key = r_object(p);
  1173. if (key == NULL)
  1174. break;
  1175. val = r_object(p);
  1176. if (val == NULL) {
  1177. Py_DECREF(key);
  1178. break;
  1179. }
  1180. if (PyDict_SetItem(v, key, val) < 0) {
  1181. Py_DECREF(key);
  1182. Py_DECREF(val);
  1183. break;
  1184. }
  1185. Py_DECREF(key);
  1186. Py_DECREF(val);
  1187. }
  1188. if (PyErr_Occurred()) {
  1189. Py_SETREF(v, NULL);
  1190. }
  1191. retval = v;
  1192. break;
  1193. case TYPE_SET:
  1194. case TYPE_FROZENSET:
  1195. n = r_long(p);
  1196. if (n < 0 || n > SIZE32_MAX) {
  1197. if (!PyErr_Occurred()) {
  1198. PyErr_SetString(PyExc_ValueError,
  1199. "bad marshal data (set size out of range)");
  1200. }
  1201. break;
  1202. }
  1203. if (n == 0 && type == TYPE_FROZENSET) {
  1204. /* call frozenset() to get the empty frozenset singleton */
  1205. v = _PyObject_CallNoArgs((PyObject*)&PyFrozenSet_Type);
  1206. if (v == NULL)
  1207. break;
  1208. R_REF(v);
  1209. retval = v;
  1210. }
  1211. else {
  1212. v = (type == TYPE_SET) ? PySet_New(NULL) : PyFrozenSet_New(NULL);
  1213. if (type == TYPE_SET) {
  1214. R_REF(v);
  1215. } else {
  1216. /* must use delayed registration of frozensets because they must
  1217. * be init with a refcount of 1
  1218. */
  1219. idx = r_ref_reserve(flag, p);
  1220. if (idx < 0)
  1221. Py_CLEAR(v); /* signal error */
  1222. }
  1223. if (v == NULL)
  1224. break;
  1225. for (i = 0; i < n; i++) {
  1226. v2 = r_object(p);
  1227. if ( v2 == NULL ) {
  1228. if (!PyErr_Occurred())
  1229. PyErr_SetString(PyExc_TypeError,
  1230. "NULL object in marshal data for set");
  1231. Py_SETREF(v, NULL);
  1232. break;
  1233. }
  1234. if (PySet_Add(v, v2) == -1) {
  1235. Py_DECREF(v);
  1236. Py_DECREF(v2);
  1237. v = NULL;
  1238. break;
  1239. }
  1240. Py_DECREF(v2);
  1241. }
  1242. if (type != TYPE_SET)
  1243. v = r_ref_insert(v, idx, flag, p);
  1244. retval = v;
  1245. }
  1246. break;
  1247. case TYPE_CODE:
  1248. {
  1249. int argcount;
  1250. int posonlyargcount;
  1251. int kwonlyargcount;
  1252. int stacksize;
  1253. int flags;
  1254. PyObject *code = NULL;
  1255. PyObject *consts = NULL;
  1256. PyObject *names = NULL;
  1257. PyObject *localsplusnames = NULL;
  1258. PyObject *localspluskinds = NULL;
  1259. PyObject *filename = NULL;
  1260. PyObject *name = NULL;
  1261. PyObject *qualname = NULL;
  1262. int firstlineno;
  1263. PyObject* linetable = NULL;
  1264. PyObject *exceptiontable = NULL;
  1265. idx = r_ref_reserve(flag, p);
  1266. if (idx < 0)
  1267. break;
  1268. v = NULL;
  1269. /* XXX ignore long->int overflows for now */
  1270. argcount = (int)r_long(p);
  1271. if (argcount == -1 && PyErr_Occurred())
  1272. goto code_error;
  1273. posonlyargcount = (int)r_long(p);
  1274. if (posonlyargcount == -1 && PyErr_Occurred()) {
  1275. goto code_error;
  1276. }
  1277. kwonlyargcount = (int)r_long(p);
  1278. if (kwonlyargcount == -1 && PyErr_Occurred())
  1279. goto code_error;
  1280. stacksize = (int)r_long(p);
  1281. if (stacksize == -1 && PyErr_Occurred())
  1282. goto code_error;
  1283. flags = (int)r_long(p);
  1284. if (flags == -1 && PyErr_Occurred())
  1285. goto code_error;
  1286. code = r_object(p);
  1287. if (code == NULL)
  1288. goto code_error;
  1289. consts = r_object(p);
  1290. if (consts == NULL)
  1291. goto code_error;
  1292. names = r_object(p);
  1293. if (names == NULL)
  1294. goto code_error;
  1295. localsplusnames = r_object(p);
  1296. if (localsplusnames == NULL)
  1297. goto code_error;
  1298. localspluskinds = r_object(p);
  1299. if (localspluskinds == NULL)
  1300. goto code_error;
  1301. filename = r_object(p);
  1302. if (filename == NULL)
  1303. goto code_error;
  1304. name = r_object(p);
  1305. if (name == NULL)
  1306. goto code_error;
  1307. qualname = r_object(p);
  1308. if (qualname == NULL)
  1309. goto code_error;
  1310. firstlineno = (int)r_long(p);
  1311. if (firstlineno == -1 && PyErr_Occurred())
  1312. break;
  1313. linetable = r_object(p);
  1314. if (linetable == NULL)
  1315. goto code_error;
  1316. exceptiontable = r_object(p);
  1317. if (exceptiontable == NULL)
  1318. goto code_error;
  1319. struct _PyCodeConstructor con = {
  1320. .filename = filename,
  1321. .name = name,
  1322. .qualname = qualname,
  1323. .flags = flags,
  1324. .code = code,
  1325. .firstlineno = firstlineno,
  1326. .linetable = linetable,
  1327. .consts = consts,
  1328. .names = names,
  1329. .localsplusnames = localsplusnames,
  1330. .localspluskinds = localspluskinds,
  1331. .argcount = argcount,
  1332. .posonlyargcount = posonlyargcount,
  1333. .kwonlyargcount = kwonlyargcount,
  1334. .stacksize = stacksize,
  1335. .exceptiontable = exceptiontable,
  1336. };
  1337. if (_PyCode_Validate(&con) < 0) {
  1338. goto code_error;
  1339. }
  1340. v = (PyObject *)_PyCode_New(&con);
  1341. if (v == NULL) {
  1342. goto code_error;
  1343. }
  1344. v = r_ref_insert(v, idx, flag, p);
  1345. code_error:
  1346. if (v == NULL && !PyErr_Occurred()) {
  1347. PyErr_SetString(PyExc_TypeError,
  1348. "NULL object in marshal data for code object");
  1349. }
  1350. Py_XDECREF(code);
  1351. Py_XDECREF(consts);
  1352. Py_XDECREF(names);
  1353. Py_XDECREF(localsplusnames);
  1354. Py_XDECREF(localspluskinds);
  1355. Py_XDECREF(filename);
  1356. Py_XDECREF(name);
  1357. Py_XDECREF(qualname);
  1358. Py_XDECREF(linetable);
  1359. Py_XDECREF(exceptiontable);
  1360. }
  1361. retval = v;
  1362. break;
  1363. case TYPE_REF:
  1364. n = r_long(p);
  1365. if (n < 0 || n >= PyList_GET_SIZE(p->refs)) {
  1366. if (!PyErr_Occurred()) {
  1367. PyErr_SetString(PyExc_ValueError,
  1368. "bad marshal data (invalid reference)");
  1369. }
  1370. break;
  1371. }
  1372. v = PyList_GET_ITEM(p->refs, n);
  1373. if (v == Py_None) {
  1374. PyErr_SetString(PyExc_ValueError, "bad marshal data (invalid reference)");
  1375. break;
  1376. }
  1377. retval = Py_NewRef(v);
  1378. break;
  1379. default:
  1380. /* Bogus data got written, which isn't ideal.
  1381. This will let you keep working and recover. */
  1382. PyErr_SetString(PyExc_ValueError, "bad marshal data (unknown type code)");
  1383. break;
  1384. }
  1385. p->depth--;
  1386. return retval;
  1387. }
  1388. static PyObject *
  1389. read_object(RFILE *p)
  1390. {
  1391. PyObject *v;
  1392. if (PyErr_Occurred()) {
  1393. fprintf(stderr, "XXX readobject called with exception set\n");
  1394. return NULL;
  1395. }
  1396. if (p->ptr && p->end) {
  1397. if (PySys_Audit("marshal.loads", "y#", p->ptr, (Py_ssize_t)(p->end - p->ptr)) < 0) {
  1398. return NULL;
  1399. }
  1400. } else if (p->fp || p->readable) {
  1401. if (PySys_Audit("marshal.load", NULL) < 0) {
  1402. return NULL;
  1403. }
  1404. }
  1405. v = r_object(p);
  1406. if (v == NULL && !PyErr_Occurred())
  1407. PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for object");
  1408. return v;
  1409. }
  1410. int
  1411. PyMarshal_ReadShortFromFile(FILE *fp)
  1412. {
  1413. RFILE rf;
  1414. int res;
  1415. assert(fp);
  1416. rf.readable = NULL;
  1417. rf.fp = fp;
  1418. rf.end = rf.ptr = NULL;
  1419. rf.buf = NULL;
  1420. res = r_short(&rf);
  1421. if (rf.buf != NULL)
  1422. PyMem_Free(rf.buf);
  1423. return res;
  1424. }
  1425. long
  1426. PyMarshal_ReadLongFromFile(FILE *fp)
  1427. {
  1428. RFILE rf;
  1429. long res;
  1430. rf.fp = fp;
  1431. rf.readable = NULL;
  1432. rf.ptr = rf.end = NULL;
  1433. rf.buf = NULL;
  1434. res = r_long(&rf);
  1435. if (rf.buf != NULL)
  1436. PyMem_Free(rf.buf);
  1437. return res;
  1438. }
  1439. /* Return size of file in bytes; < 0 if unknown or INT_MAX if too big */
  1440. static off_t
  1441. getfilesize(FILE *fp)
  1442. {
  1443. struct _Py_stat_struct st;
  1444. if (_Py_fstat_noraise(fileno(fp), &st) != 0)
  1445. return -1;
  1446. #if SIZEOF_OFF_T == 4
  1447. else if (st.st_size >= INT_MAX)
  1448. return (off_t)INT_MAX;
  1449. #endif
  1450. else
  1451. return (off_t)st.st_size;
  1452. }
  1453. /* If we can get the size of the file up-front, and it's reasonably small,
  1454. * read it in one gulp and delegate to ...FromString() instead. Much quicker
  1455. * than reading a byte at a time from file; speeds .pyc imports.
  1456. * CAUTION: since this may read the entire remainder of the file, don't
  1457. * call it unless you know you're done with the file.
  1458. */
  1459. PyObject *
  1460. PyMarshal_ReadLastObjectFromFile(FILE *fp)
  1461. {
  1462. /* REASONABLE_FILE_LIMIT is by defn something big enough for Tkinter.pyc. */
  1463. #define REASONABLE_FILE_LIMIT (1L << 18)
  1464. off_t filesize;
  1465. filesize = getfilesize(fp);
  1466. if (filesize > 0 && filesize <= REASONABLE_FILE_LIMIT) {
  1467. char* pBuf = (char *)PyMem_Malloc(filesize);
  1468. if (pBuf != NULL) {
  1469. size_t n = fread(pBuf, 1, (size_t)filesize, fp);
  1470. PyObject* v = PyMarshal_ReadObjectFromString(pBuf, n);
  1471. PyMem_Free(pBuf);
  1472. return v;
  1473. }
  1474. }
  1475. /* We don't have fstat, or we do but the file is larger than
  1476. * REASONABLE_FILE_LIMIT or malloc failed -- read a byte at a time.
  1477. */
  1478. return PyMarshal_ReadObjectFromFile(fp);
  1479. #undef REASONABLE_FILE_LIMIT
  1480. }
  1481. PyObject *
  1482. PyMarshal_ReadObjectFromFile(FILE *fp)
  1483. {
  1484. RFILE rf;
  1485. PyObject *result;
  1486. rf.fp = fp;
  1487. rf.readable = NULL;
  1488. rf.depth = 0;
  1489. rf.ptr = rf.end = NULL;
  1490. rf.buf = NULL;
  1491. rf.refs = PyList_New(0);
  1492. if (rf.refs == NULL)
  1493. return NULL;
  1494. result = read_object(&rf);
  1495. Py_DECREF(rf.refs);
  1496. if (rf.buf != NULL)
  1497. PyMem_Free(rf.buf);
  1498. return result;
  1499. }
  1500. PyObject *
  1501. PyMarshal_ReadObjectFromString(const char *str, Py_ssize_t len)
  1502. {
  1503. RFILE rf;
  1504. PyObject *result;
  1505. rf.fp = NULL;
  1506. rf.readable = NULL;
  1507. rf.ptr = str;
  1508. rf.end = str + len;
  1509. rf.buf = NULL;
  1510. rf.depth = 0;
  1511. rf.refs = PyList_New(0);
  1512. if (rf.refs == NULL)
  1513. return NULL;
  1514. result = read_object(&rf);
  1515. Py_DECREF(rf.refs);
  1516. if (rf.buf != NULL)
  1517. PyMem_Free(rf.buf);
  1518. return result;
  1519. }
  1520. PyObject *
  1521. PyMarshal_WriteObjectToString(PyObject *x, int version)
  1522. {
  1523. WFILE wf;
  1524. if (PySys_Audit("marshal.dumps", "Oi", x, version) < 0) {
  1525. return NULL;
  1526. }
  1527. memset(&wf, 0, sizeof(wf));
  1528. wf.str = PyBytes_FromStringAndSize((char *)NULL, 50);
  1529. if (wf.str == NULL)
  1530. return NULL;
  1531. wf.ptr = wf.buf = PyBytes_AS_STRING(wf.str);
  1532. wf.end = wf.ptr + PyBytes_GET_SIZE(wf.str);
  1533. wf.error = WFERR_OK;
  1534. wf.version = version;
  1535. if (w_init_refs(&wf, version)) {
  1536. Py_DECREF(wf.str);
  1537. return NULL;
  1538. }
  1539. w_object(x, &wf);
  1540. w_clear_refs(&wf);
  1541. if (wf.str != NULL) {
  1542. const char *base = PyBytes_AS_STRING(wf.str);
  1543. if (_PyBytes_Resize(&wf.str, (Py_ssize_t)(wf.ptr - base)) < 0)
  1544. return NULL;
  1545. }
  1546. if (wf.error != WFERR_OK) {
  1547. Py_XDECREF(wf.str);
  1548. if (wf.error == WFERR_NOMEMORY)
  1549. PyErr_NoMemory();
  1550. else
  1551. PyErr_SetString(PyExc_ValueError,
  1552. (wf.error==WFERR_UNMARSHALLABLE)?"unmarshallable object"
  1553. :"object too deeply nested to marshal");
  1554. return NULL;
  1555. }
  1556. return wf.str;
  1557. }
  1558. /* And an interface for Python programs... */
  1559. /*[clinic input]
  1560. marshal.dump
  1561. value: object
  1562. Must be a supported type.
  1563. file: object
  1564. Must be a writeable binary file.
  1565. version: int(c_default="Py_MARSHAL_VERSION") = version
  1566. Indicates the data format that dump should use.
  1567. /
  1568. Write the value on the open file.
  1569. If the value has (or contains an object that has) an unsupported type, a
  1570. ValueError exception is raised - but garbage data will also be written
  1571. to the file. The object will not be properly read back by load().
  1572. [clinic start generated code]*/
  1573. static PyObject *
  1574. marshal_dump_impl(PyObject *module, PyObject *value, PyObject *file,
  1575. int version)
  1576. /*[clinic end generated code: output=aaee62c7028a7cb2 input=6c7a3c23c6fef556]*/
  1577. {
  1578. /* XXX Quick hack -- need to do this differently */
  1579. PyObject *s;
  1580. PyObject *res;
  1581. s = PyMarshal_WriteObjectToString(value, version);
  1582. if (s == NULL)
  1583. return NULL;
  1584. res = _PyObject_CallMethodOneArg(file, &_Py_ID(write), s);
  1585. Py_DECREF(s);
  1586. return res;
  1587. }
  1588. /*[clinic input]
  1589. marshal.load
  1590. file: object
  1591. Must be readable binary file.
  1592. /
  1593. Read one value from the open file and return it.
  1594. If no valid value is read (e.g. because the data has a different Python
  1595. version's incompatible marshal format), raise EOFError, ValueError or
  1596. TypeError.
  1597. Note: If an object containing an unsupported type was marshalled with
  1598. dump(), load() will substitute None for the unmarshallable type.
  1599. [clinic start generated code]*/
  1600. static PyObject *
  1601. marshal_load(PyObject *module, PyObject *file)
  1602. /*[clinic end generated code: output=f8e5c33233566344 input=c85c2b594cd8124a]*/
  1603. {
  1604. PyObject *data, *result;
  1605. RFILE rf;
  1606. /*
  1607. * Make a call to the read method, but read zero bytes.
  1608. * This is to ensure that the object passed in at least
  1609. * has a read method which returns bytes.
  1610. * This can be removed if we guarantee good error handling
  1611. * for r_string()
  1612. */
  1613. data = _PyObject_CallMethod(file, &_Py_ID(read), "i", 0);
  1614. if (data == NULL)
  1615. return NULL;
  1616. if (!PyBytes_Check(data)) {
  1617. PyErr_Format(PyExc_TypeError,
  1618. "file.read() returned not bytes but %.100s",
  1619. Py_TYPE(data)->tp_name);
  1620. result = NULL;
  1621. }
  1622. else {
  1623. rf.depth = 0;
  1624. rf.fp = NULL;
  1625. rf.readable = file;
  1626. rf.ptr = rf.end = NULL;
  1627. rf.buf = NULL;
  1628. if ((rf.refs = PyList_New(0)) != NULL) {
  1629. result = read_object(&rf);
  1630. Py_DECREF(rf.refs);
  1631. if (rf.buf != NULL)
  1632. PyMem_Free(rf.buf);
  1633. } else
  1634. result = NULL;
  1635. }
  1636. Py_DECREF(data);
  1637. return result;
  1638. }
  1639. /*[clinic input]
  1640. marshal.dumps
  1641. value: object
  1642. Must be a supported type.
  1643. version: int(c_default="Py_MARSHAL_VERSION") = version
  1644. Indicates the data format that dumps should use.
  1645. /
  1646. Return the bytes object that would be written to a file by dump(value, file).
  1647. Raise a ValueError exception if value has (or contains an object that has) an
  1648. unsupported type.
  1649. [clinic start generated code]*/
  1650. static PyObject *
  1651. marshal_dumps_impl(PyObject *module, PyObject *value, int version)
  1652. /*[clinic end generated code: output=9c200f98d7256cad input=a2139ea8608e9b27]*/
  1653. {
  1654. return PyMarshal_WriteObjectToString(value, version);
  1655. }
  1656. /*[clinic input]
  1657. marshal.loads
  1658. bytes: Py_buffer
  1659. /
  1660. Convert the bytes-like object to a value.
  1661. If no valid value is found, raise EOFError, ValueError or TypeError. Extra
  1662. bytes in the input are ignored.
  1663. [clinic start generated code]*/
  1664. static PyObject *
  1665. marshal_loads_impl(PyObject *module, Py_buffer *bytes)
  1666. /*[clinic end generated code: output=9fc65985c93d1bb1 input=6f426518459c8495]*/
  1667. {
  1668. RFILE rf;
  1669. char *s = bytes->buf;
  1670. Py_ssize_t n = bytes->len;
  1671. PyObject* result;
  1672. rf.fp = NULL;
  1673. rf.readable = NULL;
  1674. rf.ptr = s;
  1675. rf.end = s + n;
  1676. rf.depth = 0;
  1677. if ((rf.refs = PyList_New(0)) == NULL)
  1678. return NULL;
  1679. result = read_object(&rf);
  1680. Py_DECREF(rf.refs);
  1681. return result;
  1682. }
  1683. static PyMethodDef marshal_methods[] = {
  1684. MARSHAL_DUMP_METHODDEF
  1685. MARSHAL_LOAD_METHODDEF
  1686. MARSHAL_DUMPS_METHODDEF
  1687. MARSHAL_LOADS_METHODDEF
  1688. {NULL, NULL} /* sentinel */
  1689. };
  1690. PyDoc_STRVAR(module_doc,
  1691. "This module contains functions that can read and write Python values in\n\
  1692. a binary format. The format is specific to Python, but independent of\n\
  1693. machine architecture issues.\n\
  1694. \n\
  1695. Not all Python object types are supported; in general, only objects\n\
  1696. whose value is independent from a particular invocation of Python can be\n\
  1697. written and read by this module. The following types are supported:\n\
  1698. None, integers, floating-point numbers, strings, bytes, bytearrays,\n\
  1699. tuples, lists, sets, dictionaries, and code objects, where it\n\
  1700. should be understood that tuples, lists and dictionaries are only\n\
  1701. supported as long as the values contained therein are themselves\n\
  1702. supported; and recursive lists and dictionaries should not be written\n\
  1703. (they will cause infinite loops).\n\
  1704. \n\
  1705. Variables:\n\
  1706. \n\
  1707. version -- indicates the format that the module uses. Version 0 is the\n\
  1708. historical format, version 1 shares interned strings and version 2\n\
  1709. uses a binary format for floating-point numbers.\n\
  1710. Version 3 shares common object references (New in version 3.4).\n\
  1711. \n\
  1712. Functions:\n\
  1713. \n\
  1714. dump() -- write value to a file\n\
  1715. load() -- read value from a file\n\
  1716. dumps() -- marshal value as a bytes object\n\
  1717. loads() -- read value from a bytes-like object");
  1718. static int
  1719. marshal_module_exec(PyObject *mod)
  1720. {
  1721. if (PyModule_AddIntConstant(mod, "version", Py_MARSHAL_VERSION) < 0) {
  1722. return -1;
  1723. }
  1724. return 0;
  1725. }
  1726. static PyModuleDef_Slot marshalmodule_slots[] = {
  1727. {Py_mod_exec, marshal_module_exec},
  1728. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  1729. {0, NULL}
  1730. };
  1731. static struct PyModuleDef marshalmodule = {
  1732. PyModuleDef_HEAD_INIT,
  1733. .m_name = "marshal",
  1734. .m_doc = module_doc,
  1735. .m_methods = marshal_methods,
  1736. .m_slots = marshalmodule_slots,
  1737. };
  1738. PyMODINIT_FUNC
  1739. PyMarshal_Init(void)
  1740. {
  1741. return PyModuleDef_Init(&marshalmodule);
  1742. }