pkpy.c 18 KB

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