marshal.c 52 KB

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