pkpy.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. #include "pocketpy/interpreter/objectpool.h"
  2. #include "pocketpy/objects/base.h"
  3. #include "pocketpy/pocketpy.h"
  4. #include "pocketpy/common/utils.h"
  5. #include "pocketpy/common/sstream.h"
  6. #include "pocketpy/interpreter/vm.h"
  7. #include "pocketpy/common/threads.h"
  8. #include <time.h>
  9. #define DEF_TVALUE_METHODS(T, Field) \
  10. static bool TValue_##T##__new__(int argc, py_Ref argv) { \
  11. PY_CHECK_ARGC(2); \
  12. PY_CHECK_ARG_TYPE(0, tp_type); \
  13. PY_CHECK_ARG_TYPE(1, tp_##T); \
  14. *py_retval() = (py_TValue){ \
  15. .type = py_totype(&argv[0]), \
  16. .is_ptr = false, \
  17. .Field = py_to##T(&argv[1]), \
  18. }; \
  19. return true; \
  20. } \
  21. static bool TValue_##T##_value(int argc, py_Ref argv) { \
  22. PY_CHECK_ARGC(1); \
  23. py_new##T(py_retval(), argv->Field); \
  24. return true; \
  25. } \
  26. static bool TValue_##T##__repr__(int argc, py_Ref argv) { \
  27. PY_CHECK_ARGC(1); \
  28. py_newstr(py_retval(), "<TValue_" #T " object>"); \
  29. return true; \
  30. }
  31. DEF_TVALUE_METHODS(int, _i64)
  32. DEF_TVALUE_METHODS(float, _f64)
  33. DEF_TVALUE_METHODS(vec2, _vec2)
  34. DEF_TVALUE_METHODS(vec2i, _vec2i)
  35. static bool pkpy_memory_usage(int argc, py_Ref argv) {
  36. PY_CHECK_ARGC(0);
  37. ManagedHeap* heap = &pk_current_vm->heap;
  38. c11_string* small_objects_usage = MultiPool__summary(&heap->small_objects);
  39. int large_object_count = heap->large_objects.length;
  40. c11_sbuf buf;
  41. c11_sbuf__ctor(&buf);
  42. c11_sbuf__write_cstr(&buf, "== heap.small_objects ==\n");
  43. c11_sbuf__write_cstr(&buf, small_objects_usage->data);
  44. c11_sbuf__write_cstr(&buf, "== heap.large_objects ==\n");
  45. pk_sprintf(&buf, "len(large_objects)=%d\n", large_object_count);
  46. c11_sbuf__write_cstr(&buf, "== heap.gc ==\n");
  47. pk_sprintf(&buf, "gc_counter=%d\n", heap->gc_counter);
  48. pk_sprintf(&buf, "gc_threshold=%d", heap->gc_threshold);
  49. // c11_sbuf__write_cstr(&buf, "== vm.pool_frame ==\n");
  50. c11_sbuf__py_submit(&buf, py_retval());
  51. c11_string__delete(small_objects_usage);
  52. return true;
  53. }
  54. static bool pkpy_is_user_defined_type(int argc, py_Ref argv) {
  55. PY_CHECK_ARGC(1);
  56. PY_CHECK_ARG_TYPE(0, tp_type);
  57. py_TypeInfo* ti = pk__type_info(py_totype(argv));
  58. py_newbool(py_retval(), ti->is_python);
  59. return true;
  60. }
  61. static bool pkpy_enable_full_buffering_mode(int argc, py_Ref argv) {
  62. PY_CHECK_ARGC(0);
  63. static char buf[1024 * 128];
  64. setvbuf(stdout, buf, _IOFBF, sizeof(buf));
  65. py_newnone(py_retval());
  66. return true;
  67. }
  68. static bool pkpy_currentvm(int argc, py_Ref argv) {
  69. PY_CHECK_ARGC(0);
  70. py_newint(py_retval(), py_currentvm());
  71. return true;
  72. }
  73. #if PK_ENABLE_WATCHDOG
  74. void py_watchdog_begin(py_i64 timeout) {
  75. WatchdogInfo* info = &pk_current_vm->watchdog_info;
  76. info->max_reset_time = clock() + (timeout * (CLOCKS_PER_SEC / 1000));
  77. }
  78. void py_watchdog_end() {
  79. WatchdogInfo* info = &pk_current_vm->watchdog_info;
  80. info->max_reset_time = 0;
  81. }
  82. static bool pkpy_watchdog_begin(int argc, py_Ref argv) {
  83. PY_CHECK_ARGC(1);
  84. PY_CHECK_ARG_TYPE(0, tp_int);
  85. py_watchdog_begin(py_toint(argv));
  86. py_newnone(py_retval());
  87. return true;
  88. }
  89. static bool pkpy_watchdog_end(int argc, py_Ref argv) {
  90. PY_CHECK_ARGC(0);
  91. py_watchdog_end();
  92. py_newnone(py_retval());
  93. return true;
  94. }
  95. #endif
  96. typedef struct c11_ComputeThread c11_ComputeThread;
  97. typedef struct {
  98. c11_ComputeThread* self;
  99. char* eval_src;
  100. unsigned char* args_data;
  101. int args_size;
  102. unsigned char* kwargs_data;
  103. int kwargs_size;
  104. } ComputeThreadJobCall;
  105. typedef struct {
  106. c11_ComputeThread* self;
  107. char* source;
  108. enum py_CompileMode mode;
  109. } ComputeThreadJobExec;
  110. static void ComputeThreadJobCall__dtor(void* arg) {
  111. ComputeThreadJobCall* self = arg;
  112. PK_FREE(self->eval_src);
  113. PK_FREE(self->args_data);
  114. PK_FREE(self->kwargs_data);
  115. }
  116. static void ComputeThreadJobExec__dtor(void* arg) {
  117. ComputeThreadJobExec* self = arg;
  118. PK_FREE(self->source);
  119. }
  120. typedef struct c11_ComputeThread {
  121. int vm_index;
  122. atomic_bool is_done;
  123. unsigned char* last_retval_data;
  124. int last_retval_size;
  125. char* last_error;
  126. c11_thrd_t thread;
  127. void* job;
  128. void (*job_dtor)(void*);
  129. } c11_ComputeThread;
  130. static void
  131. c11_ComputeThread__reset_job(c11_ComputeThread* self, void* job, void (*job_dtor)(void*)) {
  132. if(self->job) {
  133. self->job_dtor(self->job);
  134. PK_FREE(self->job);
  135. }
  136. self->job = job;
  137. self->job_dtor = job_dtor;
  138. }
  139. static bool _pk_compute_thread_flags[16];
  140. static void c11_ComputeThread__dtor(c11_ComputeThread* self) {
  141. if(!self->is_done) {
  142. c11__abort("ComputeThread(%d) is not done yet!! But the object was deleted.",
  143. self->vm_index);
  144. }
  145. if(self->last_retval_data) PK_FREE(self->last_retval_data);
  146. if(self->last_error) PK_FREE(self->last_error);
  147. c11_ComputeThread__reset_job(self, NULL, NULL);
  148. _pk_compute_thread_flags[self->vm_index] = false;
  149. }
  150. static void c11_ComputeThread__on_job_begin(c11_ComputeThread* self) {
  151. if(self->last_retval_data) {
  152. PK_FREE(self->last_retval_data);
  153. self->last_retval_data = NULL;
  154. self->last_retval_size = 0;
  155. }
  156. if(self->last_error) {
  157. PK_FREE(self->last_error);
  158. self->last_error = NULL;
  159. }
  160. py_switchvm(self->vm_index);
  161. }
  162. static bool ComputeThread__new__(int argc, py_Ref argv) {
  163. c11_ComputeThread* self =
  164. py_newobject(py_retval(), py_totype(argv), 0, sizeof(c11_ComputeThread));
  165. self->vm_index = 0;
  166. self->is_done = true;
  167. self->last_retval_data = NULL;
  168. self->last_retval_size = 0;
  169. self->last_error = NULL;
  170. self->job = NULL;
  171. self->job_dtor = NULL;
  172. return true;
  173. }
  174. static bool ComputeThread__init__(int argc, py_Ref argv) {
  175. PY_CHECK_ARGC(2);
  176. PY_CHECK_ARG_TYPE(1, tp_int);
  177. c11_ComputeThread* self = py_touserdata(py_arg(0));
  178. int index = py_toint(py_arg(1));
  179. if(index >= 1 && index < 16) {
  180. if(_pk_compute_thread_flags[index]) {
  181. return ValueError("vm_index %d is already in use", index);
  182. }
  183. _pk_compute_thread_flags[index] = true;
  184. self->vm_index = index;
  185. } else {
  186. return ValueError("vm_index %d is out of range", index);
  187. }
  188. py_newnone(py_retval());
  189. return true;
  190. }
  191. static bool ComputeThread_is_done(int argc, py_Ref argv) {
  192. PY_CHECK_ARGC(1);
  193. c11_ComputeThread* self = py_touserdata(argv);
  194. py_newbool(py_retval(), self->is_done);
  195. return true;
  196. }
  197. static bool ComputeThread_wait_for_done(int argc, py_Ref argv) {
  198. PY_CHECK_ARGC(1);
  199. c11_ComputeThread* self = py_touserdata(argv);
  200. while(!self->is_done)
  201. c11_thrd_yield();
  202. py_newnone(py_retval());
  203. return true;
  204. }
  205. static bool ComputeThread_last_error(int argc, py_Ref argv) {
  206. PY_CHECK_ARGC(1);
  207. c11_ComputeThread* self = py_touserdata(argv);
  208. if(!self->is_done) return OSError("thread is not done yet");
  209. if(self->last_error) {
  210. py_newstr(py_retval(), self->last_error);
  211. } else {
  212. py_newnone(py_retval());
  213. }
  214. return true;
  215. }
  216. static bool ComputeThread_last_retval(int argc, py_Ref argv) {
  217. PY_CHECK_ARGC(1);
  218. c11_ComputeThread* self = py_touserdata(argv);
  219. if(!self->is_done) return OSError("thread is not done yet");
  220. if(self->last_retval_data == NULL) return ValueError("no retval available");
  221. return py_pickle_loads(self->last_retval_data, self->last_retval_size);
  222. }
  223. static c11_thrd_retval_t ComputeThreadJob_call(void* arg) {
  224. ComputeThreadJobCall* job = arg;
  225. c11_ComputeThread* self = job->self;
  226. c11_ComputeThread__on_job_begin(self);
  227. py_StackRef p0 = py_peek(0);
  228. if(!py_pusheval(job->eval_src, NULL)) goto __ERROR;
  229. // [callable]
  230. if(!py_pickle_loads(job->args_data, job->args_size)) goto __ERROR;
  231. py_push(py_retval());
  232. // [callable, args]
  233. if(!py_pickle_loads(job->kwargs_data, job->kwargs_size)) goto __ERROR;
  234. py_push(py_retval());
  235. // [callable, args, kwargs]
  236. if(!py_smarteval("_0(*_1, **_2)", NULL, py_peek(-3), py_peek(-2), py_peek(-1))) goto __ERROR;
  237. py_shrink(3);
  238. if(!py_pickle_dumps(py_retval())) goto __ERROR;
  239. int retval_size;
  240. unsigned char* retval_data = py_tobytes(py_retval(), &retval_size);
  241. self->last_retval_data = c11_memdup(retval_data, retval_size);
  242. self->last_retval_size = retval_size;
  243. self->is_done = true;
  244. return (c11_thrd_retval_t)0;
  245. __ERROR:
  246. self->last_error = py_formatexc();
  247. self->is_done = true;
  248. py_clearexc(p0);
  249. py_newnone(py_retval());
  250. return (c11_thrd_retval_t)0;
  251. }
  252. static c11_thrd_retval_t ComputeThreadJob_exec(void* arg) {
  253. ComputeThreadJobExec* job = arg;
  254. c11_ComputeThread* self = job->self;
  255. c11_ComputeThread__on_job_begin(self);
  256. py_StackRef p0 = py_peek(0);
  257. if(!py_exec(job->source, "<job>", job->mode, NULL)) goto __ERROR;
  258. if(!py_pickle_dumps(py_retval())) goto __ERROR;
  259. int retval_size;
  260. unsigned char* retval_data = py_tobytes(py_retval(), &retval_size);
  261. self->last_retval_data = c11_memdup(retval_data, retval_size);
  262. self->last_retval_size = retval_size;
  263. self->is_done = true;
  264. return (c11_thrd_retval_t)0;
  265. __ERROR:
  266. self->last_error = py_formatexc();
  267. self->is_done = true;
  268. py_clearexc(p0);
  269. return (c11_thrd_retval_t)0;
  270. }
  271. static bool ComputeThread_submit_exec(int argc, py_Ref argv) {
  272. PY_CHECK_ARGC(2);
  273. c11_ComputeThread* self = py_touserdata(py_arg(0));
  274. if(!self->is_done) return OSError("thread is not done yet");
  275. PY_CHECK_ARG_TYPE(1, tp_str);
  276. const char* source = py_tostr(py_arg(1));
  277. /**************************/
  278. ComputeThreadJobExec* job = PK_MALLOC(sizeof(ComputeThreadJobExec));
  279. job->self = self;
  280. job->source = c11_strdup(source);
  281. job->mode = EXEC_MODE;
  282. c11_ComputeThread__reset_job(self, job, ComputeThreadJobExec__dtor);
  283. /**************************/
  284. self->is_done = false;
  285. bool ok = c11_thrd_create(&self->thread, ComputeThreadJob_exec, job);
  286. if(!ok) {
  287. self->is_done = true;
  288. return OSError("thrd_create() failed");
  289. }
  290. py_newnone(py_retval());
  291. return true;
  292. }
  293. static bool ComputeThread_submit_eval(int argc, py_Ref argv) {
  294. PY_CHECK_ARGC(2);
  295. c11_ComputeThread* self = py_touserdata(py_arg(0));
  296. if(!self->is_done) return OSError("thread is not done yet");
  297. PY_CHECK_ARG_TYPE(1, tp_str);
  298. const char* source = py_tostr(py_arg(1));
  299. /**************************/
  300. ComputeThreadJobExec* job = PK_MALLOC(sizeof(ComputeThreadJobExec));
  301. job->self = self;
  302. job->source = c11_strdup(source);
  303. job->mode = EVAL_MODE;
  304. c11_ComputeThread__reset_job(self, job, ComputeThreadJobExec__dtor);
  305. /**************************/
  306. self->is_done = false;
  307. bool ok = c11_thrd_create(&self->thread, ComputeThreadJob_exec, job);
  308. if(!ok) {
  309. self->is_done = true;
  310. return OSError("thrd_create() failed");
  311. }
  312. py_newnone(py_retval());
  313. return true;
  314. }
  315. static bool ComputeThread_submit_call(int argc, py_Ref argv) {
  316. PY_CHECK_ARGC(4);
  317. c11_ComputeThread* self = py_touserdata(py_arg(0));
  318. if(!self->is_done) return OSError("thread is not done yet");
  319. PY_CHECK_ARG_TYPE(1, tp_str);
  320. PY_CHECK_ARG_TYPE(2, tp_tuple);
  321. PY_CHECK_ARG_TYPE(3, tp_dict);
  322. // eval_src
  323. const char* eval_src = py_tostr(py_arg(1));
  324. // *args
  325. if(!py_pickle_dumps(py_arg(2))) return false;
  326. int args_size;
  327. unsigned char* args_data = py_tobytes(py_retval(), &args_size);
  328. // *kwargs
  329. if(!py_pickle_dumps(py_arg(3))) return false;
  330. int kwargs_size;
  331. unsigned char* kwargs_data = py_tobytes(py_retval(), &kwargs_size);
  332. /**************************/
  333. ComputeThreadJobCall* job = PK_MALLOC(sizeof(ComputeThreadJobCall));
  334. job->self = self;
  335. job->eval_src = c11_strdup(eval_src);
  336. job->args_data = c11_memdup(args_data, args_size);
  337. job->args_size = args_size;
  338. job->kwargs_data = c11_memdup(kwargs_data, kwargs_size);
  339. job->kwargs_size = kwargs_size;
  340. c11_ComputeThread__reset_job(self, job, ComputeThreadJobCall__dtor);
  341. /**************************/
  342. self->is_done = false;
  343. bool ok = c11_thrd_create(&self->thread, ComputeThreadJob_call, job);
  344. if(!ok) {
  345. self->is_done = true;
  346. return OSError("thrd_create() failed");
  347. }
  348. py_newnone(py_retval());
  349. return true;
  350. }
  351. static bool c11_ComputeThread__exec_blocked(c11_ComputeThread* self,
  352. const char* source,
  353. enum py_CompileMode mode) {
  354. if(!self->is_done) return OSError("thread is not done yet");
  355. self->is_done = false;
  356. char* err = NULL;
  357. int old_vm_index = py_currentvm();
  358. py_switchvm(self->vm_index);
  359. py_StackRef p0 = py_peek(0);
  360. if(!py_exec(source, "<job_blocked>", mode, NULL)) goto __ERROR;
  361. if(!py_pickle_dumps(py_retval())) goto __ERROR;
  362. int retval_size;
  363. unsigned char* retval_data = py_tobytes(py_retval(), &retval_size);
  364. py_switchvm(old_vm_index);
  365. bool ok = py_pickle_loads(retval_data, retval_size);
  366. self->is_done = true;
  367. return ok;
  368. __ERROR:
  369. err = py_formatexc();
  370. py_clearexc(p0);
  371. py_switchvm(old_vm_index);
  372. self->is_done = true;
  373. RuntimeError("c11_ComputeThread__exec_blocked() failed:\n%s", err);
  374. PK_FREE(err);
  375. return false;
  376. }
  377. static bool ComputeThread_exec(int argc, py_Ref argv) {
  378. PY_CHECK_ARGC(2);
  379. c11_ComputeThread* self = py_touserdata(py_arg(0));
  380. PY_CHECK_ARG_TYPE(1, tp_str);
  381. const char* source = py_tostr(py_arg(1));
  382. return c11_ComputeThread__exec_blocked(self, source, EXEC_MODE);
  383. }
  384. static bool ComputeThread_eval(int argc, py_Ref argv) {
  385. PY_CHECK_ARGC(2);
  386. c11_ComputeThread* self = py_touserdata(py_arg(0));
  387. PY_CHECK_ARG_TYPE(1, tp_str);
  388. const char* source = py_tostr(py_arg(1));
  389. return c11_ComputeThread__exec_blocked(self, source, EVAL_MODE);
  390. }
  391. static void pk_ComputeThread__register(py_Ref mod) {
  392. py_Type type = py_newtype("ComputeThread", tp_object, mod, (py_Dtor)c11_ComputeThread__dtor);
  393. py_bindmagic(type, __new__, ComputeThread__new__);
  394. py_bindmagic(type, __init__, ComputeThread__init__);
  395. py_bindproperty(type, "is_done", ComputeThread_is_done, NULL);
  396. py_bindmethod(type, "wait_for_done", ComputeThread_wait_for_done);
  397. py_bindmethod(type, "last_error", ComputeThread_last_error);
  398. py_bindmethod(type, "last_retval", ComputeThread_last_retval);
  399. py_bindmethod(type, "submit_exec", ComputeThread_submit_exec);
  400. py_bindmethod(type, "submit_eval", ComputeThread_submit_eval);
  401. py_bind(py_tpobject(type),
  402. "submit_call(self, eval_src, *args, **kwargs)",
  403. ComputeThread_submit_call);
  404. py_bindmethod(type, "exec", ComputeThread_exec);
  405. py_bindmethod(type, "eval", ComputeThread_eval);
  406. }
  407. static void pkpy_configmacros_add(py_Ref dict, const char* key, int val){
  408. assert(dict->type == tp_dict);
  409. py_TValue tmp;
  410. py_newint(&tmp, val);
  411. py_dict_setitem_by_str(dict, key, &tmp);
  412. }
  413. void pk__add_module_pkpy() {
  414. py_Ref mod = py_newmodule("pkpy");
  415. py_Type ttype;
  416. py_Ref TValue_dict = py_pushtmp();
  417. py_newdict(TValue_dict);
  418. ttype = pk_newtype("TValue_int", tp_object, mod, NULL, false, false);
  419. py_bindmagic(ttype, __new__, TValue_int__new__);
  420. py_bindmagic(ttype, __repr__, TValue_int__repr__);
  421. py_bindproperty(ttype, "value", TValue_int_value, NULL);
  422. py_dict_setitem(TValue_dict, py_tpobject(tp_int), py_tpobject(ttype));
  423. ttype = pk_newtype("TValue_float", tp_object, mod, NULL, false, false);
  424. py_bindmagic(ttype, __new__, TValue_float__new__);
  425. py_bindmagic(ttype, __repr__, TValue_float__repr__);
  426. py_bindproperty(ttype, "value", TValue_float_value, NULL);
  427. py_dict_setitem(TValue_dict, py_tpobject(tp_float), py_tpobject(ttype));
  428. ttype = pk_newtype("TValue_vec2", tp_object, mod, NULL, false, false);
  429. py_bindmagic(ttype, __new__, TValue_vec2__new__);
  430. py_bindmagic(ttype, __repr__, TValue_vec2__repr__);
  431. py_bindproperty(ttype, "value", TValue_vec2_value, NULL);
  432. py_dict_setitem(TValue_dict, py_tpobject(tp_vec2), py_tpobject(ttype));
  433. ttype = pk_newtype("TValue_vec2i", tp_object, mod, NULL, false, false);
  434. py_bindmagic(ttype, __new__, TValue_vec2i__new__);
  435. py_bindmagic(ttype, __repr__, TValue_vec2i__repr__);
  436. py_bindproperty(ttype, "value", TValue_vec2i_value, NULL);
  437. py_dict_setitem(TValue_dict, py_tpobject(tp_vec2i), py_tpobject(ttype));
  438. py_setdict(mod, py_name("TValue"), TValue_dict);
  439. py_pop();
  440. py_bindfunc(mod, "memory_usage", pkpy_memory_usage);
  441. py_bindfunc(mod, "is_user_defined_type", pkpy_is_user_defined_type);
  442. py_bindfunc(mod, "enable_full_buffering_mode", pkpy_enable_full_buffering_mode);
  443. py_bindfunc(mod, "currentvm", pkpy_currentvm);
  444. #if PK_ENABLE_WATCHDOG
  445. py_bindfunc(mod, "watchdog_begin", pkpy_watchdog_begin);
  446. py_bindfunc(mod, "watchdog_end", pkpy_watchdog_end);
  447. #endif
  448. pk_ComputeThread__register(mod);
  449. py_Ref configmacros = py_emplacedict(mod, py_name("configmacros"));
  450. py_newdict(configmacros);
  451. pkpy_configmacros_add(configmacros, "PK_ENABLE_OS", PK_ENABLE_OS);
  452. pkpy_configmacros_add(configmacros, "PK_ENABLE_DETERMINISM", PK_ENABLE_DETERMINISM);
  453. pkpy_configmacros_add(configmacros, "PK_ENABLE_WATCHDOG", PK_ENABLE_WATCHDOG);
  454. pkpy_configmacros_add(configmacros, "PK_GC_MIN_THRESHOLD", PK_GC_MIN_THRESHOLD);
  455. pkpy_configmacros_add(configmacros, "PK_VM_STACK_SIZE", PK_VM_STACK_SIZE);
  456. }
  457. #undef DEF_TVALUE_METHODS