_asynciomodule.c 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833
  1. #ifndef Py_BUILD_CORE_BUILTIN
  2. # define Py_BUILD_CORE_MODULE 1
  3. #endif
  4. #include "Python.h"
  5. #include "pycore_pyerrors.h" // _PyErr_ClearExcState()
  6. #include "pycore_pystate.h" // _PyThreadState_GET()
  7. #include "pycore_runtime_init.h" // _Py_ID()
  8. #include "pycore_moduleobject.h" // _PyModule_GetState()
  9. #include "structmember.h" // PyMemberDef
  10. #include <stddef.h> // offsetof()
  11. /*[clinic input]
  12. module _asyncio
  13. [clinic start generated code]*/
  14. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=8fd17862aa989c69]*/
  15. #define FI_FREELIST_MAXLEN 255
  16. typedef struct futureiterobject futureiterobject;
  17. /* State of the _asyncio module */
  18. typedef struct {
  19. PyTypeObject *FutureIterType;
  20. PyTypeObject *TaskStepMethWrapper_Type;
  21. PyTypeObject *FutureType;
  22. PyTypeObject *TaskType;
  23. PyObject *asyncio_mod;
  24. PyObject *context_kwname;
  25. /* Dictionary containing tasks that are currently active in
  26. all running event loops. {EventLoop: Task} */
  27. PyObject *current_tasks;
  28. /* WeakSet containing all tasks scheduled to run on event loops. */
  29. PyObject *scheduled_tasks;
  30. /* Set containing all eagerly executing tasks. */
  31. PyObject *eager_tasks;
  32. /* An isinstance type cache for the 'is_coroutine()' function. */
  33. PyObject *iscoroutine_typecache;
  34. /* Imports from asyncio.events. */
  35. PyObject *asyncio_get_event_loop_policy;
  36. /* Imports from asyncio.base_futures. */
  37. PyObject *asyncio_future_repr_func;
  38. /* Imports from asyncio.exceptions. */
  39. PyObject *asyncio_CancelledError;
  40. PyObject *asyncio_InvalidStateError;
  41. /* Imports from asyncio.base_tasks. */
  42. PyObject *asyncio_task_get_stack_func;
  43. PyObject *asyncio_task_print_stack_func;
  44. PyObject *asyncio_task_repr_func;
  45. /* Imports from asyncio.coroutines. */
  46. PyObject *asyncio_iscoroutine_func;
  47. /* Imports from traceback. */
  48. PyObject *traceback_extract_stack;
  49. PyObject *cached_running_loop; // Borrowed reference
  50. volatile uint64_t cached_running_loop_tsid;
  51. /* Counter for autogenerated Task names */
  52. uint64_t task_name_counter;
  53. futureiterobject *fi_freelist;
  54. Py_ssize_t fi_freelist_len;
  55. } asyncio_state;
  56. static inline asyncio_state *
  57. get_asyncio_state(PyObject *mod)
  58. {
  59. asyncio_state *state = _PyModule_GetState(mod);
  60. assert(state != NULL);
  61. return state;
  62. }
  63. static inline asyncio_state *
  64. get_asyncio_state_by_cls(PyTypeObject *cls)
  65. {
  66. asyncio_state *state = (asyncio_state *)_PyType_GetModuleState(cls);
  67. assert(state != NULL);
  68. return state;
  69. }
  70. static struct PyModuleDef _asynciomodule;
  71. static inline asyncio_state *
  72. get_asyncio_state_by_def(PyObject *self)
  73. {
  74. PyTypeObject *tp = Py_TYPE(self);
  75. PyObject *mod = PyType_GetModuleByDef(tp, &_asynciomodule);
  76. assert(mod != NULL);
  77. return get_asyncio_state(mod);
  78. }
  79. typedef enum {
  80. STATE_PENDING,
  81. STATE_CANCELLED,
  82. STATE_FINISHED
  83. } fut_state;
  84. #define FutureObj_HEAD(prefix) \
  85. PyObject_HEAD \
  86. PyObject *prefix##_loop; \
  87. PyObject *prefix##_callback0; \
  88. PyObject *prefix##_context0; \
  89. PyObject *prefix##_callbacks; \
  90. PyObject *prefix##_exception; \
  91. PyObject *prefix##_exception_tb; \
  92. PyObject *prefix##_result; \
  93. PyObject *prefix##_source_tb; \
  94. PyObject *prefix##_cancel_msg; \
  95. fut_state prefix##_state; \
  96. int prefix##_log_tb; \
  97. int prefix##_blocking; \
  98. PyObject *dict; \
  99. PyObject *prefix##_weakreflist; \
  100. PyObject *prefix##_cancelled_exc;
  101. typedef struct {
  102. FutureObj_HEAD(fut)
  103. } FutureObj;
  104. typedef struct {
  105. FutureObj_HEAD(task)
  106. PyObject *task_fut_waiter;
  107. PyObject *task_coro;
  108. PyObject *task_name;
  109. PyObject *task_context;
  110. int task_must_cancel;
  111. int task_log_destroy_pending;
  112. int task_num_cancels_requested;
  113. } TaskObj;
  114. typedef struct {
  115. PyObject_HEAD
  116. TaskObj *sw_task;
  117. PyObject *sw_arg;
  118. } TaskStepMethWrapper;
  119. #define Future_CheckExact(state, obj) Py_IS_TYPE(obj, state->FutureType)
  120. #define Task_CheckExact(state, obj) Py_IS_TYPE(obj, state->TaskType)
  121. #define Future_Check(state, obj) PyObject_TypeCheck(obj, state->FutureType)
  122. #define Task_Check(state, obj) PyObject_TypeCheck(obj, state->TaskType)
  123. #include "clinic/_asynciomodule.c.h"
  124. /*[clinic input]
  125. class _asyncio.Future "FutureObj *" "&Future_Type"
  126. [clinic start generated code]*/
  127. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=00d3e4abca711e0f]*/
  128. /* Get FutureIter from Future */
  129. static PyObject * future_new_iter(PyObject *);
  130. static PyObject *
  131. task_step_handle_result_impl(asyncio_state *state, TaskObj *task, PyObject *result);
  132. static int
  133. _is_coroutine(asyncio_state *state, PyObject *coro)
  134. {
  135. /* 'coro' is not a native coroutine, call asyncio.iscoroutine()
  136. to check if it's another coroutine flavour.
  137. Do this check after 'future_init()'; in case we need to raise
  138. an error, __del__ needs a properly initialized object.
  139. */
  140. PyObject *res = PyObject_CallOneArg(state->asyncio_iscoroutine_func, coro);
  141. if (res == NULL) {
  142. return -1;
  143. }
  144. int is_res_true = PyObject_IsTrue(res);
  145. Py_DECREF(res);
  146. if (is_res_true <= 0) {
  147. return is_res_true;
  148. }
  149. if (PySet_GET_SIZE(state->iscoroutine_typecache) < 100) {
  150. /* Just in case we don't want to cache more than 100
  151. positive types. That shouldn't ever happen, unless
  152. someone stressing the system on purpose.
  153. */
  154. if (PySet_Add(state->iscoroutine_typecache, (PyObject*) Py_TYPE(coro))) {
  155. return -1;
  156. }
  157. }
  158. return 1;
  159. }
  160. static inline int
  161. is_coroutine(asyncio_state *state, PyObject *coro)
  162. {
  163. if (PyCoro_CheckExact(coro)) {
  164. return 1;
  165. }
  166. /* Check if `type(coro)` is in the cache.
  167. Caching makes is_coroutine() function almost as fast as
  168. PyCoro_CheckExact() for non-native coroutine-like objects
  169. (like coroutines compiled with Cython).
  170. asyncio.iscoroutine() has its own type caching mechanism.
  171. This cache allows us to avoid the cost of even calling
  172. a pure-Python function in 99.9% cases.
  173. */
  174. int has_it = PySet_Contains(
  175. state->iscoroutine_typecache, (PyObject*) Py_TYPE(coro));
  176. if (has_it == 0) {
  177. /* type(coro) is not in iscoroutine_typecache */
  178. return _is_coroutine(state, coro);
  179. }
  180. /* either an error has occurred or
  181. type(coro) is in iscoroutine_typecache
  182. */
  183. return has_it;
  184. }
  185. static PyObject *
  186. get_future_loop(asyncio_state *state, PyObject *fut)
  187. {
  188. /* Implementation of `asyncio.futures._get_loop` */
  189. PyObject *getloop;
  190. if (Future_CheckExact(state, fut) || Task_CheckExact(state, fut)) {
  191. PyObject *loop = ((FutureObj *)fut)->fut_loop;
  192. return Py_NewRef(loop);
  193. }
  194. if (_PyObject_LookupAttr(fut, &_Py_ID(get_loop), &getloop) < 0) {
  195. return NULL;
  196. }
  197. if (getloop != NULL) {
  198. PyObject *res = PyObject_CallNoArgs(getloop);
  199. Py_DECREF(getloop);
  200. return res;
  201. }
  202. return PyObject_GetAttr(fut, &_Py_ID(_loop));
  203. }
  204. static int
  205. get_running_loop(asyncio_state *state, PyObject **loop)
  206. {
  207. PyObject *rl;
  208. PyThreadState *ts = _PyThreadState_GET();
  209. uint64_t ts_id = PyThreadState_GetID(ts);
  210. if (state->cached_running_loop_tsid == ts_id &&
  211. state->cached_running_loop != NULL)
  212. {
  213. // Fast path, check the cache.
  214. rl = state->cached_running_loop;
  215. }
  216. else {
  217. PyObject *ts_dict = _PyThreadState_GetDict(ts); // borrowed
  218. if (ts_dict == NULL) {
  219. goto not_found;
  220. }
  221. rl = PyDict_GetItemWithError(
  222. ts_dict, &_Py_ID(__asyncio_running_event_loop__)); // borrowed
  223. if (rl == NULL) {
  224. if (PyErr_Occurred()) {
  225. goto error;
  226. }
  227. else {
  228. goto not_found;
  229. }
  230. }
  231. state->cached_running_loop = rl;
  232. state->cached_running_loop_tsid = ts_id;
  233. }
  234. if (rl == Py_None) {
  235. goto not_found;
  236. }
  237. *loop = Py_NewRef(rl);
  238. return 0;
  239. not_found:
  240. *loop = NULL;
  241. return 0;
  242. error:
  243. *loop = NULL;
  244. return -1;
  245. }
  246. static int
  247. set_running_loop(asyncio_state *state, PyObject *loop)
  248. {
  249. PyObject *ts_dict = NULL;
  250. PyThreadState *tstate = _PyThreadState_GET();
  251. if (tstate != NULL) {
  252. ts_dict = _PyThreadState_GetDict(tstate); // borrowed
  253. }
  254. if (ts_dict == NULL) {
  255. PyErr_SetString(
  256. PyExc_RuntimeError, "thread-local storage is not available");
  257. return -1;
  258. }
  259. if (PyDict_SetItem(
  260. ts_dict, &_Py_ID(__asyncio_running_event_loop__), loop) < 0)
  261. {
  262. return -1;
  263. }
  264. state->cached_running_loop = loop; // borrowed, kept alive by ts_dict
  265. state->cached_running_loop_tsid = PyThreadState_GetID(tstate);
  266. return 0;
  267. }
  268. static PyObject *
  269. get_event_loop(asyncio_state *state)
  270. {
  271. PyObject *loop;
  272. PyObject *policy;
  273. if (get_running_loop(state, &loop)) {
  274. return NULL;
  275. }
  276. if (loop != NULL) {
  277. return loop;
  278. }
  279. policy = PyObject_CallNoArgs(state->asyncio_get_event_loop_policy);
  280. if (policy == NULL) {
  281. return NULL;
  282. }
  283. loop = PyObject_CallMethodNoArgs(policy, &_Py_ID(get_event_loop));
  284. Py_DECREF(policy);
  285. return loop;
  286. }
  287. static int
  288. call_soon(asyncio_state *state, PyObject *loop, PyObject *func, PyObject *arg,
  289. PyObject *ctx)
  290. {
  291. PyObject *handle;
  292. if (ctx == NULL) {
  293. PyObject *stack[] = {loop, func, arg};
  294. size_t nargsf = 3 | PY_VECTORCALL_ARGUMENTS_OFFSET;
  295. handle = PyObject_VectorcallMethod(&_Py_ID(call_soon), stack, nargsf, NULL);
  296. }
  297. else {
  298. /* All refs in 'stack' are borrowed. */
  299. PyObject *stack[4];
  300. size_t nargs = 2;
  301. stack[0] = loop;
  302. stack[1] = func;
  303. if (arg != NULL) {
  304. stack[2] = arg;
  305. nargs++;
  306. }
  307. stack[nargs] = (PyObject *)ctx;
  308. size_t nargsf = nargs | PY_VECTORCALL_ARGUMENTS_OFFSET;
  309. handle = PyObject_VectorcallMethod(&_Py_ID(call_soon), stack, nargsf,
  310. state->context_kwname);
  311. }
  312. if (handle == NULL) {
  313. return -1;
  314. }
  315. Py_DECREF(handle);
  316. return 0;
  317. }
  318. static inline int
  319. future_is_alive(FutureObj *fut)
  320. {
  321. return fut->fut_loop != NULL;
  322. }
  323. static inline int
  324. future_ensure_alive(FutureObj *fut)
  325. {
  326. if (!future_is_alive(fut)) {
  327. PyErr_SetString(PyExc_RuntimeError,
  328. "Future object is not initialized.");
  329. return -1;
  330. }
  331. return 0;
  332. }
  333. #define ENSURE_FUTURE_ALIVE(state, fut) \
  334. do { \
  335. assert(Future_Check(state, fut) || Task_Check(state, fut)); \
  336. (void)state; \
  337. if (future_ensure_alive((FutureObj*)fut)) { \
  338. return NULL; \
  339. } \
  340. } while(0);
  341. static int
  342. future_schedule_callbacks(asyncio_state *state, FutureObj *fut)
  343. {
  344. Py_ssize_t len;
  345. Py_ssize_t i;
  346. if (fut->fut_callback0 != NULL) {
  347. /* There's a 1st callback */
  348. int ret = call_soon(state,
  349. fut->fut_loop, fut->fut_callback0,
  350. (PyObject *)fut, fut->fut_context0);
  351. Py_CLEAR(fut->fut_callback0);
  352. Py_CLEAR(fut->fut_context0);
  353. if (ret) {
  354. /* If an error occurs in pure-Python implementation,
  355. all callbacks are cleared. */
  356. Py_CLEAR(fut->fut_callbacks);
  357. return ret;
  358. }
  359. /* we called the first callback, now try calling
  360. callbacks from the 'fut_callbacks' list. */
  361. }
  362. if (fut->fut_callbacks == NULL) {
  363. /* No more callbacks, return. */
  364. return 0;
  365. }
  366. len = PyList_GET_SIZE(fut->fut_callbacks);
  367. if (len == 0) {
  368. /* The list of callbacks was empty; clear it and return. */
  369. Py_CLEAR(fut->fut_callbacks);
  370. return 0;
  371. }
  372. for (i = 0; i < len; i++) {
  373. PyObject *cb_tup = PyList_GET_ITEM(fut->fut_callbacks, i);
  374. PyObject *cb = PyTuple_GET_ITEM(cb_tup, 0);
  375. PyObject *ctx = PyTuple_GET_ITEM(cb_tup, 1);
  376. if (call_soon(state, fut->fut_loop, cb, (PyObject *)fut, ctx)) {
  377. /* If an error occurs in pure-Python implementation,
  378. all callbacks are cleared. */
  379. Py_CLEAR(fut->fut_callbacks);
  380. return -1;
  381. }
  382. }
  383. Py_CLEAR(fut->fut_callbacks);
  384. return 0;
  385. }
  386. static int
  387. future_init(FutureObj *fut, PyObject *loop)
  388. {
  389. PyObject *res;
  390. int is_true;
  391. // Same to FutureObj_clear() but not clearing fut->dict
  392. Py_CLEAR(fut->fut_loop);
  393. Py_CLEAR(fut->fut_callback0);
  394. Py_CLEAR(fut->fut_context0);
  395. Py_CLEAR(fut->fut_callbacks);
  396. Py_CLEAR(fut->fut_result);
  397. Py_CLEAR(fut->fut_exception);
  398. Py_CLEAR(fut->fut_exception_tb);
  399. Py_CLEAR(fut->fut_source_tb);
  400. Py_CLEAR(fut->fut_cancel_msg);
  401. Py_CLEAR(fut->fut_cancelled_exc);
  402. fut->fut_state = STATE_PENDING;
  403. fut->fut_log_tb = 0;
  404. fut->fut_blocking = 0;
  405. if (loop == Py_None) {
  406. asyncio_state *state = get_asyncio_state_by_def((PyObject *)fut);
  407. loop = get_event_loop(state);
  408. if (loop == NULL) {
  409. return -1;
  410. }
  411. }
  412. else {
  413. Py_INCREF(loop);
  414. }
  415. fut->fut_loop = loop;
  416. res = PyObject_CallMethodNoArgs(fut->fut_loop, &_Py_ID(get_debug));
  417. if (res == NULL) {
  418. return -1;
  419. }
  420. is_true = PyObject_IsTrue(res);
  421. Py_DECREF(res);
  422. if (is_true < 0) {
  423. return -1;
  424. }
  425. if (is_true && !_Py_IsInterpreterFinalizing(PyInterpreterState_Get())) {
  426. /* Only try to capture the traceback if the interpreter is not being
  427. finalized. The original motivation to add a `_Py_IsFinalizing()`
  428. call was to prevent SIGSEGV when a Future is created in a __del__
  429. method, which is called during the interpreter shutdown and the
  430. traceback module is already unloaded.
  431. */
  432. asyncio_state *state = get_asyncio_state_by_def((PyObject *)fut);
  433. fut->fut_source_tb = PyObject_CallNoArgs(state->traceback_extract_stack);
  434. if (fut->fut_source_tb == NULL) {
  435. return -1;
  436. }
  437. }
  438. return 0;
  439. }
  440. static PyObject *
  441. future_set_result(asyncio_state *state, FutureObj *fut, PyObject *res)
  442. {
  443. if (future_ensure_alive(fut)) {
  444. return NULL;
  445. }
  446. if (fut->fut_state != STATE_PENDING) {
  447. PyErr_SetString(state->asyncio_InvalidStateError, "invalid state");
  448. return NULL;
  449. }
  450. assert(!fut->fut_result);
  451. fut->fut_result = Py_NewRef(res);
  452. fut->fut_state = STATE_FINISHED;
  453. if (future_schedule_callbacks(state, fut) == -1) {
  454. return NULL;
  455. }
  456. Py_RETURN_NONE;
  457. }
  458. static PyObject *
  459. future_set_exception(asyncio_state *state, FutureObj *fut, PyObject *exc)
  460. {
  461. PyObject *exc_val = NULL;
  462. if (fut->fut_state != STATE_PENDING) {
  463. PyErr_SetString(state->asyncio_InvalidStateError, "invalid state");
  464. return NULL;
  465. }
  466. if (PyExceptionClass_Check(exc)) {
  467. exc_val = PyObject_CallNoArgs(exc);
  468. if (exc_val == NULL) {
  469. return NULL;
  470. }
  471. if (fut->fut_state != STATE_PENDING) {
  472. Py_DECREF(exc_val);
  473. PyErr_SetString(state->asyncio_InvalidStateError, "invalid state");
  474. return NULL;
  475. }
  476. }
  477. else {
  478. exc_val = Py_NewRef(exc);
  479. }
  480. if (!PyExceptionInstance_Check(exc_val)) {
  481. Py_DECREF(exc_val);
  482. PyErr_SetString(PyExc_TypeError, "invalid exception object");
  483. return NULL;
  484. }
  485. if (Py_IS_TYPE(exc_val, (PyTypeObject *)PyExc_StopIteration)) {
  486. Py_DECREF(exc_val);
  487. PyErr_SetString(PyExc_TypeError,
  488. "StopIteration interacts badly with generators "
  489. "and cannot be raised into a Future");
  490. return NULL;
  491. }
  492. assert(!fut->fut_exception);
  493. assert(!fut->fut_exception_tb);
  494. fut->fut_exception = exc_val;
  495. fut->fut_exception_tb = PyException_GetTraceback(exc_val);
  496. fut->fut_state = STATE_FINISHED;
  497. if (future_schedule_callbacks(state, fut) == -1) {
  498. return NULL;
  499. }
  500. fut->fut_log_tb = 1;
  501. Py_RETURN_NONE;
  502. }
  503. static PyObject *
  504. create_cancelled_error(asyncio_state *state, FutureObj *fut)
  505. {
  506. PyObject *exc;
  507. if (fut->fut_cancelled_exc != NULL) {
  508. /* transfer ownership */
  509. exc = fut->fut_cancelled_exc;
  510. fut->fut_cancelled_exc = NULL;
  511. return exc;
  512. }
  513. PyObject *msg = fut->fut_cancel_msg;
  514. if (msg == NULL || msg == Py_None) {
  515. exc = PyObject_CallNoArgs(state->asyncio_CancelledError);
  516. } else {
  517. exc = PyObject_CallOneArg(state->asyncio_CancelledError, msg);
  518. }
  519. return exc;
  520. }
  521. static void
  522. future_set_cancelled_error(asyncio_state *state, FutureObj *fut)
  523. {
  524. PyObject *exc = create_cancelled_error(state, fut);
  525. if (exc == NULL) {
  526. return;
  527. }
  528. PyErr_SetObject(state->asyncio_CancelledError, exc);
  529. Py_DECREF(exc);
  530. }
  531. static int
  532. future_get_result(asyncio_state *state, FutureObj *fut, PyObject **result)
  533. {
  534. if (fut->fut_state == STATE_CANCELLED) {
  535. future_set_cancelled_error(state, fut);
  536. return -1;
  537. }
  538. if (fut->fut_state != STATE_FINISHED) {
  539. PyErr_SetString(state->asyncio_InvalidStateError,
  540. "Result is not set.");
  541. return -1;
  542. }
  543. fut->fut_log_tb = 0;
  544. if (fut->fut_exception != NULL) {
  545. PyObject *tb = fut->fut_exception_tb;
  546. if (tb == NULL) {
  547. tb = Py_None;
  548. }
  549. if (PyException_SetTraceback(fut->fut_exception, tb) < 0) {
  550. return -1;
  551. }
  552. *result = Py_NewRef(fut->fut_exception);
  553. Py_CLEAR(fut->fut_exception_tb);
  554. return 1;
  555. }
  556. *result = Py_NewRef(fut->fut_result);
  557. return 0;
  558. }
  559. static PyObject *
  560. future_add_done_callback(asyncio_state *state, FutureObj *fut, PyObject *arg,
  561. PyObject *ctx)
  562. {
  563. if (!future_is_alive(fut)) {
  564. PyErr_SetString(PyExc_RuntimeError, "uninitialized Future object");
  565. return NULL;
  566. }
  567. if (fut->fut_state != STATE_PENDING) {
  568. /* The future is done/cancelled, so schedule the callback
  569. right away. */
  570. if (call_soon(state, fut->fut_loop, arg, (PyObject*) fut, ctx)) {
  571. return NULL;
  572. }
  573. }
  574. else {
  575. /* The future is pending, add a callback.
  576. Callbacks in the future object are stored as follows:
  577. callback0 -- a pointer to the first callback
  578. callbacks -- a list of 2nd, 3rd, ... callbacks
  579. Invariants:
  580. * callbacks != NULL:
  581. There are some callbacks in in the list. Just
  582. add the new callback to it.
  583. * callbacks == NULL and callback0 == NULL:
  584. This is the first callback. Set it to callback0.
  585. * callbacks == NULL and callback0 != NULL:
  586. This is a second callback. Initialize callbacks
  587. with a new list and add the new callback to it.
  588. */
  589. if (fut->fut_callbacks == NULL && fut->fut_callback0 == NULL) {
  590. fut->fut_callback0 = Py_NewRef(arg);
  591. fut->fut_context0 = Py_NewRef(ctx);
  592. }
  593. else {
  594. PyObject *tup = PyTuple_New(2);
  595. if (tup == NULL) {
  596. return NULL;
  597. }
  598. Py_INCREF(arg);
  599. PyTuple_SET_ITEM(tup, 0, arg);
  600. Py_INCREF(ctx);
  601. PyTuple_SET_ITEM(tup, 1, (PyObject *)ctx);
  602. if (fut->fut_callbacks != NULL) {
  603. int err = PyList_Append(fut->fut_callbacks, tup);
  604. if (err) {
  605. Py_DECREF(tup);
  606. return NULL;
  607. }
  608. Py_DECREF(tup);
  609. }
  610. else {
  611. fut->fut_callbacks = PyList_New(1);
  612. if (fut->fut_callbacks == NULL) {
  613. Py_DECREF(tup);
  614. return NULL;
  615. }
  616. PyList_SET_ITEM(fut->fut_callbacks, 0, tup); /* borrow */
  617. }
  618. }
  619. }
  620. Py_RETURN_NONE;
  621. }
  622. static PyObject *
  623. future_cancel(asyncio_state *state, FutureObj *fut, PyObject *msg)
  624. {
  625. fut->fut_log_tb = 0;
  626. if (fut->fut_state != STATE_PENDING) {
  627. Py_RETURN_FALSE;
  628. }
  629. fut->fut_state = STATE_CANCELLED;
  630. Py_XINCREF(msg);
  631. Py_XSETREF(fut->fut_cancel_msg, msg);
  632. if (future_schedule_callbacks(state, fut) == -1) {
  633. return NULL;
  634. }
  635. Py_RETURN_TRUE;
  636. }
  637. /*[clinic input]
  638. _asyncio.Future.__init__
  639. *
  640. loop: object = None
  641. This class is *almost* compatible with concurrent.futures.Future.
  642. Differences:
  643. - result() and exception() do not take a timeout argument and
  644. raise an exception when the future isn't done yet.
  645. - Callbacks registered with add_done_callback() are always called
  646. via the event loop's call_soon_threadsafe().
  647. - This class is not compatible with the wait() and as_completed()
  648. methods in the concurrent.futures package.
  649. [clinic start generated code]*/
  650. static int
  651. _asyncio_Future___init___impl(FutureObj *self, PyObject *loop)
  652. /*[clinic end generated code: output=9ed75799eaccb5d6 input=89af317082bc0bf8]*/
  653. {
  654. return future_init(self, loop);
  655. }
  656. static int
  657. FutureObj_clear(FutureObj *fut)
  658. {
  659. Py_CLEAR(fut->fut_loop);
  660. Py_CLEAR(fut->fut_callback0);
  661. Py_CLEAR(fut->fut_context0);
  662. Py_CLEAR(fut->fut_callbacks);
  663. Py_CLEAR(fut->fut_result);
  664. Py_CLEAR(fut->fut_exception);
  665. Py_CLEAR(fut->fut_exception_tb);
  666. Py_CLEAR(fut->fut_source_tb);
  667. Py_CLEAR(fut->fut_cancel_msg);
  668. Py_CLEAR(fut->fut_cancelled_exc);
  669. Py_CLEAR(fut->dict);
  670. return 0;
  671. }
  672. static int
  673. FutureObj_traverse(FutureObj *fut, visitproc visit, void *arg)
  674. {
  675. Py_VISIT(Py_TYPE(fut));
  676. Py_VISIT(fut->fut_loop);
  677. Py_VISIT(fut->fut_callback0);
  678. Py_VISIT(fut->fut_context0);
  679. Py_VISIT(fut->fut_callbacks);
  680. Py_VISIT(fut->fut_result);
  681. Py_VISIT(fut->fut_exception);
  682. Py_VISIT(fut->fut_exception_tb);
  683. Py_VISIT(fut->fut_source_tb);
  684. Py_VISIT(fut->fut_cancel_msg);
  685. Py_VISIT(fut->fut_cancelled_exc);
  686. Py_VISIT(fut->dict);
  687. return 0;
  688. }
  689. /*[clinic input]
  690. _asyncio.Future.result
  691. Return the result this future represents.
  692. If the future has been cancelled, raises CancelledError. If the
  693. future's result isn't yet available, raises InvalidStateError. If
  694. the future is done and has an exception set, this exception is raised.
  695. [clinic start generated code]*/
  696. static PyObject *
  697. _asyncio_Future_result_impl(FutureObj *self)
  698. /*[clinic end generated code: output=f35f940936a4b1e5 input=49ecf9cf5ec50dc5]*/
  699. {
  700. asyncio_state *state = get_asyncio_state_by_def((PyObject *)self);
  701. PyObject *result;
  702. if (!future_is_alive(self)) {
  703. PyErr_SetString(state->asyncio_InvalidStateError,
  704. "Future object is not initialized.");
  705. return NULL;
  706. }
  707. int res = future_get_result(state, self, &result);
  708. if (res == -1) {
  709. return NULL;
  710. }
  711. if (res == 0) {
  712. return result;
  713. }
  714. assert(res == 1);
  715. PyErr_SetObject(PyExceptionInstance_Class(result), result);
  716. Py_DECREF(result);
  717. return NULL;
  718. }
  719. /*[clinic input]
  720. _asyncio.Future.exception
  721. cls: defining_class
  722. /
  723. Return the exception that was set on this future.
  724. The exception (or None if no exception was set) is returned only if
  725. the future is done. If the future has been cancelled, raises
  726. CancelledError. If the future isn't done yet, raises
  727. InvalidStateError.
  728. [clinic start generated code]*/
  729. static PyObject *
  730. _asyncio_Future_exception_impl(FutureObj *self, PyTypeObject *cls)
  731. /*[clinic end generated code: output=ce75576b187c905b input=3faf15c22acdb60d]*/
  732. {
  733. if (!future_is_alive(self)) {
  734. asyncio_state *state = get_asyncio_state_by_cls(cls);
  735. PyErr_SetString(state->asyncio_InvalidStateError,
  736. "Future object is not initialized.");
  737. return NULL;
  738. }
  739. if (self->fut_state == STATE_CANCELLED) {
  740. asyncio_state *state = get_asyncio_state_by_cls(cls);
  741. future_set_cancelled_error(state, self);
  742. return NULL;
  743. }
  744. if (self->fut_state != STATE_FINISHED) {
  745. asyncio_state *state = get_asyncio_state_by_cls(cls);
  746. PyErr_SetString(state->asyncio_InvalidStateError,
  747. "Exception is not set.");
  748. return NULL;
  749. }
  750. if (self->fut_exception != NULL) {
  751. self->fut_log_tb = 0;
  752. return Py_NewRef(self->fut_exception);
  753. }
  754. Py_RETURN_NONE;
  755. }
  756. /*[clinic input]
  757. _asyncio.Future.set_result
  758. cls: defining_class
  759. result: object
  760. /
  761. Mark the future done and set its result.
  762. If the future is already done when this method is called, raises
  763. InvalidStateError.
  764. [clinic start generated code]*/
  765. static PyObject *
  766. _asyncio_Future_set_result_impl(FutureObj *self, PyTypeObject *cls,
  767. PyObject *result)
  768. /*[clinic end generated code: output=99afbbe78f99c32d input=d5a41c1e353acc2e]*/
  769. {
  770. asyncio_state *state = get_asyncio_state_by_cls(cls);
  771. ENSURE_FUTURE_ALIVE(state, self)
  772. return future_set_result(state, self, result);
  773. }
  774. /*[clinic input]
  775. _asyncio.Future.set_exception
  776. cls: defining_class
  777. exception: object
  778. /
  779. Mark the future done and set an exception.
  780. If the future is already done when this method is called, raises
  781. InvalidStateError.
  782. [clinic start generated code]*/
  783. static PyObject *
  784. _asyncio_Future_set_exception_impl(FutureObj *self, PyTypeObject *cls,
  785. PyObject *exception)
  786. /*[clinic end generated code: output=0a5e8b5a52f058d6 input=a245cd49d3df939b]*/
  787. {
  788. asyncio_state *state = get_asyncio_state_by_cls(cls);
  789. ENSURE_FUTURE_ALIVE(state, self)
  790. return future_set_exception(state, self, exception);
  791. }
  792. /*[clinic input]
  793. _asyncio.Future.add_done_callback
  794. cls: defining_class
  795. fn: object
  796. /
  797. *
  798. context: object = NULL
  799. Add a callback to be run when the future becomes done.
  800. The callback is called with a single argument - the future object. If
  801. the future is already done when this is called, the callback is
  802. scheduled with call_soon.
  803. [clinic start generated code]*/
  804. static PyObject *
  805. _asyncio_Future_add_done_callback_impl(FutureObj *self, PyTypeObject *cls,
  806. PyObject *fn, PyObject *context)
  807. /*[clinic end generated code: output=922e9a4cbd601167 input=599261c521458cc2]*/
  808. {
  809. asyncio_state *state = get_asyncio_state_by_cls(cls);
  810. if (context == NULL) {
  811. context = PyContext_CopyCurrent();
  812. if (context == NULL) {
  813. return NULL;
  814. }
  815. PyObject *res = future_add_done_callback(state, self, fn, context);
  816. Py_DECREF(context);
  817. return res;
  818. }
  819. return future_add_done_callback(state, self, fn, context);
  820. }
  821. /*[clinic input]
  822. _asyncio.Future.remove_done_callback
  823. cls: defining_class
  824. fn: object
  825. /
  826. Remove all instances of a callback from the "call when done" list.
  827. Returns the number of callbacks removed.
  828. [clinic start generated code]*/
  829. static PyObject *
  830. _asyncio_Future_remove_done_callback_impl(FutureObj *self, PyTypeObject *cls,
  831. PyObject *fn)
  832. /*[clinic end generated code: output=2da35ccabfe41b98 input=c7518709b86fc747]*/
  833. {
  834. PyObject *newlist;
  835. Py_ssize_t len, i, j=0;
  836. Py_ssize_t cleared_callback0 = 0;
  837. asyncio_state *state = get_asyncio_state_by_cls(cls);
  838. ENSURE_FUTURE_ALIVE(state, self)
  839. if (self->fut_callback0 != NULL) {
  840. int cmp = PyObject_RichCompareBool(self->fut_callback0, fn, Py_EQ);
  841. if (cmp == -1) {
  842. return NULL;
  843. }
  844. if (cmp == 1) {
  845. /* callback0 == fn */
  846. Py_CLEAR(self->fut_callback0);
  847. Py_CLEAR(self->fut_context0);
  848. cleared_callback0 = 1;
  849. }
  850. }
  851. if (self->fut_callbacks == NULL) {
  852. return PyLong_FromSsize_t(cleared_callback0);
  853. }
  854. len = PyList_GET_SIZE(self->fut_callbacks);
  855. if (len == 0) {
  856. Py_CLEAR(self->fut_callbacks);
  857. return PyLong_FromSsize_t(cleared_callback0);
  858. }
  859. if (len == 1) {
  860. PyObject *cb_tup = PyList_GET_ITEM(self->fut_callbacks, 0);
  861. int cmp = PyObject_RichCompareBool(
  862. PyTuple_GET_ITEM(cb_tup, 0), fn, Py_EQ);
  863. if (cmp == -1) {
  864. return NULL;
  865. }
  866. if (cmp == 1) {
  867. /* callbacks[0] == fn */
  868. Py_CLEAR(self->fut_callbacks);
  869. return PyLong_FromSsize_t(1 + cleared_callback0);
  870. }
  871. /* callbacks[0] != fn and len(callbacks) == 1 */
  872. return PyLong_FromSsize_t(cleared_callback0);
  873. }
  874. newlist = PyList_New(len);
  875. if (newlist == NULL) {
  876. return NULL;
  877. }
  878. // Beware: PyObject_RichCompareBool below may change fut_callbacks.
  879. // See GH-97592.
  880. for (i = 0;
  881. self->fut_callbacks != NULL && i < PyList_GET_SIZE(self->fut_callbacks);
  882. i++) {
  883. int ret;
  884. PyObject *item = PyList_GET_ITEM(self->fut_callbacks, i);
  885. Py_INCREF(item);
  886. ret = PyObject_RichCompareBool(PyTuple_GET_ITEM(item, 0), fn, Py_EQ);
  887. if (ret == 0) {
  888. if (j < len) {
  889. PyList_SET_ITEM(newlist, j, item);
  890. j++;
  891. continue;
  892. }
  893. ret = PyList_Append(newlist, item);
  894. }
  895. Py_DECREF(item);
  896. if (ret < 0) {
  897. goto fail;
  898. }
  899. }
  900. // Note: fut_callbacks may have been cleared.
  901. if (j == 0 || self->fut_callbacks == NULL) {
  902. Py_CLEAR(self->fut_callbacks);
  903. Py_DECREF(newlist);
  904. return PyLong_FromSsize_t(len + cleared_callback0);
  905. }
  906. if (j < len) {
  907. Py_SET_SIZE(newlist, j);
  908. }
  909. j = PyList_GET_SIZE(newlist);
  910. len = PyList_GET_SIZE(self->fut_callbacks);
  911. if (j != len) {
  912. if (PyList_SetSlice(self->fut_callbacks, 0, len, newlist) < 0) {
  913. goto fail;
  914. }
  915. }
  916. Py_DECREF(newlist);
  917. return PyLong_FromSsize_t(len - j + cleared_callback0);
  918. fail:
  919. Py_DECREF(newlist);
  920. return NULL;
  921. }
  922. /*[clinic input]
  923. _asyncio.Future.cancel
  924. cls: defining_class
  925. /
  926. msg: object = None
  927. Cancel the future and schedule callbacks.
  928. If the future is already done or cancelled, return False. Otherwise,
  929. change the future's state to cancelled, schedule the callbacks and
  930. return True.
  931. [clinic start generated code]*/
  932. static PyObject *
  933. _asyncio_Future_cancel_impl(FutureObj *self, PyTypeObject *cls,
  934. PyObject *msg)
  935. /*[clinic end generated code: output=074956f35904b034 input=bba8f8b786941a94]*/
  936. {
  937. asyncio_state *state = get_asyncio_state_by_cls(cls);
  938. ENSURE_FUTURE_ALIVE(state, self)
  939. return future_cancel(state, self, msg);
  940. }
  941. /*[clinic input]
  942. _asyncio.Future.cancelled
  943. Return True if the future was cancelled.
  944. [clinic start generated code]*/
  945. static PyObject *
  946. _asyncio_Future_cancelled_impl(FutureObj *self)
  947. /*[clinic end generated code: output=145197ced586357d input=943ab8b7b7b17e45]*/
  948. {
  949. if (future_is_alive(self) && self->fut_state == STATE_CANCELLED) {
  950. Py_RETURN_TRUE;
  951. }
  952. else {
  953. Py_RETURN_FALSE;
  954. }
  955. }
  956. /*[clinic input]
  957. _asyncio.Future.done
  958. Return True if the future is done.
  959. Done means either that a result / exception are available, or that the
  960. future was cancelled.
  961. [clinic start generated code]*/
  962. static PyObject *
  963. _asyncio_Future_done_impl(FutureObj *self)
  964. /*[clinic end generated code: output=244c5ac351145096 input=28d7b23fdb65d2ac]*/
  965. {
  966. if (!future_is_alive(self) || self->fut_state == STATE_PENDING) {
  967. Py_RETURN_FALSE;
  968. }
  969. else {
  970. Py_RETURN_TRUE;
  971. }
  972. }
  973. /*[clinic input]
  974. _asyncio.Future.get_loop
  975. cls: defining_class
  976. /
  977. Return the event loop the Future is bound to.
  978. [clinic start generated code]*/
  979. static PyObject *
  980. _asyncio_Future_get_loop_impl(FutureObj *self, PyTypeObject *cls)
  981. /*[clinic end generated code: output=f50ea6c374d9ee97 input=163c2c498b45a1f0]*/
  982. {
  983. asyncio_state *state = get_asyncio_state_by_cls(cls);
  984. ENSURE_FUTURE_ALIVE(state, self)
  985. return Py_NewRef(self->fut_loop);
  986. }
  987. static PyObject *
  988. FutureObj_get_blocking(FutureObj *fut, void *Py_UNUSED(ignored))
  989. {
  990. if (future_is_alive(fut) && fut->fut_blocking) {
  991. Py_RETURN_TRUE;
  992. }
  993. else {
  994. Py_RETURN_FALSE;
  995. }
  996. }
  997. static int
  998. FutureObj_set_blocking(FutureObj *fut, PyObject *val, void *Py_UNUSED(ignored))
  999. {
  1000. if (future_ensure_alive(fut)) {
  1001. return -1;
  1002. }
  1003. if (val == NULL) {
  1004. PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
  1005. return -1;
  1006. }
  1007. int is_true = PyObject_IsTrue(val);
  1008. if (is_true < 0) {
  1009. return -1;
  1010. }
  1011. fut->fut_blocking = is_true;
  1012. return 0;
  1013. }
  1014. static PyObject *
  1015. FutureObj_get_log_traceback(FutureObj *fut, void *Py_UNUSED(ignored))
  1016. {
  1017. asyncio_state *state = get_asyncio_state_by_def((PyObject *)fut);
  1018. ENSURE_FUTURE_ALIVE(state, fut)
  1019. if (fut->fut_log_tb) {
  1020. Py_RETURN_TRUE;
  1021. }
  1022. else {
  1023. Py_RETURN_FALSE;
  1024. }
  1025. }
  1026. static int
  1027. FutureObj_set_log_traceback(FutureObj *fut, PyObject *val, void *Py_UNUSED(ignored))
  1028. {
  1029. if (val == NULL) {
  1030. PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
  1031. return -1;
  1032. }
  1033. int is_true = PyObject_IsTrue(val);
  1034. if (is_true < 0) {
  1035. return -1;
  1036. }
  1037. if (is_true) {
  1038. PyErr_SetString(PyExc_ValueError,
  1039. "_log_traceback can only be set to False");
  1040. return -1;
  1041. }
  1042. fut->fut_log_tb = is_true;
  1043. return 0;
  1044. }
  1045. static PyObject *
  1046. FutureObj_get_loop(FutureObj *fut, void *Py_UNUSED(ignored))
  1047. {
  1048. if (!future_is_alive(fut)) {
  1049. Py_RETURN_NONE;
  1050. }
  1051. return Py_NewRef(fut->fut_loop);
  1052. }
  1053. static PyObject *
  1054. FutureObj_get_callbacks(FutureObj *fut, void *Py_UNUSED(ignored))
  1055. {
  1056. asyncio_state *state = get_asyncio_state_by_def((PyObject *)fut);
  1057. Py_ssize_t i;
  1058. ENSURE_FUTURE_ALIVE(state, fut)
  1059. if (fut->fut_callback0 == NULL) {
  1060. if (fut->fut_callbacks == NULL) {
  1061. Py_RETURN_NONE;
  1062. }
  1063. return Py_NewRef(fut->fut_callbacks);
  1064. }
  1065. Py_ssize_t len = 1;
  1066. if (fut->fut_callbacks != NULL) {
  1067. len += PyList_GET_SIZE(fut->fut_callbacks);
  1068. }
  1069. PyObject *new_list = PyList_New(len);
  1070. if (new_list == NULL) {
  1071. return NULL;
  1072. }
  1073. PyObject *tup0 = PyTuple_New(2);
  1074. if (tup0 == NULL) {
  1075. Py_DECREF(new_list);
  1076. return NULL;
  1077. }
  1078. Py_INCREF(fut->fut_callback0);
  1079. PyTuple_SET_ITEM(tup0, 0, fut->fut_callback0);
  1080. assert(fut->fut_context0 != NULL);
  1081. Py_INCREF(fut->fut_context0);
  1082. PyTuple_SET_ITEM(tup0, 1, (PyObject *)fut->fut_context0);
  1083. PyList_SET_ITEM(new_list, 0, tup0);
  1084. if (fut->fut_callbacks != NULL) {
  1085. for (i = 0; i < PyList_GET_SIZE(fut->fut_callbacks); i++) {
  1086. PyObject *cb = PyList_GET_ITEM(fut->fut_callbacks, i);
  1087. Py_INCREF(cb);
  1088. PyList_SET_ITEM(new_list, i + 1, cb);
  1089. }
  1090. }
  1091. return new_list;
  1092. }
  1093. static PyObject *
  1094. FutureObj_get_result(FutureObj *fut, void *Py_UNUSED(ignored))
  1095. {
  1096. asyncio_state *state = get_asyncio_state_by_def((PyObject *)fut);
  1097. ENSURE_FUTURE_ALIVE(state, fut)
  1098. if (fut->fut_result == NULL) {
  1099. Py_RETURN_NONE;
  1100. }
  1101. return Py_NewRef(fut->fut_result);
  1102. }
  1103. static PyObject *
  1104. FutureObj_get_exception(FutureObj *fut, void *Py_UNUSED(ignored))
  1105. {
  1106. asyncio_state *state = get_asyncio_state_by_def((PyObject *)fut);
  1107. ENSURE_FUTURE_ALIVE(state, fut)
  1108. if (fut->fut_exception == NULL) {
  1109. Py_RETURN_NONE;
  1110. }
  1111. return Py_NewRef(fut->fut_exception);
  1112. }
  1113. static PyObject *
  1114. FutureObj_get_source_traceback(FutureObj *fut, void *Py_UNUSED(ignored))
  1115. {
  1116. if (!future_is_alive(fut) || fut->fut_source_tb == NULL) {
  1117. Py_RETURN_NONE;
  1118. }
  1119. return Py_NewRef(fut->fut_source_tb);
  1120. }
  1121. static PyObject *
  1122. FutureObj_get_cancel_message(FutureObj *fut, void *Py_UNUSED(ignored))
  1123. {
  1124. if (fut->fut_cancel_msg == NULL) {
  1125. Py_RETURN_NONE;
  1126. }
  1127. return Py_NewRef(fut->fut_cancel_msg);
  1128. }
  1129. static int
  1130. FutureObj_set_cancel_message(FutureObj *fut, PyObject *msg,
  1131. void *Py_UNUSED(ignored))
  1132. {
  1133. if (msg == NULL) {
  1134. PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
  1135. return -1;
  1136. }
  1137. Py_INCREF(msg);
  1138. Py_XSETREF(fut->fut_cancel_msg, msg);
  1139. return 0;
  1140. }
  1141. static PyObject *
  1142. FutureObj_get_state(FutureObj *fut, void *Py_UNUSED(ignored))
  1143. {
  1144. asyncio_state *state = get_asyncio_state_by_def((PyObject *)fut);
  1145. PyObject *ret = NULL;
  1146. ENSURE_FUTURE_ALIVE(state, fut)
  1147. switch (fut->fut_state) {
  1148. case STATE_PENDING:
  1149. ret = &_Py_ID(PENDING);
  1150. break;
  1151. case STATE_CANCELLED:
  1152. ret = &_Py_ID(CANCELLED);
  1153. break;
  1154. case STATE_FINISHED:
  1155. ret = &_Py_ID(FINISHED);
  1156. break;
  1157. default:
  1158. assert (0);
  1159. }
  1160. return Py_XNewRef(ret);
  1161. }
  1162. static PyObject *
  1163. FutureObj_repr(FutureObj *fut)
  1164. {
  1165. asyncio_state *state = get_asyncio_state_by_def((PyObject *)fut);
  1166. ENSURE_FUTURE_ALIVE(state, fut)
  1167. return PyObject_CallOneArg(state->asyncio_future_repr_func, (PyObject *)fut);
  1168. }
  1169. /*[clinic input]
  1170. _asyncio.Future._make_cancelled_error
  1171. Create the CancelledError to raise if the Future is cancelled.
  1172. This should only be called once when handling a cancellation since
  1173. it erases the context exception value.
  1174. [clinic start generated code]*/
  1175. static PyObject *
  1176. _asyncio_Future__make_cancelled_error_impl(FutureObj *self)
  1177. /*[clinic end generated code: output=a5df276f6c1213de input=ac6effe4ba795ecc]*/
  1178. {
  1179. asyncio_state *state = get_asyncio_state_by_def((PyObject *)self);
  1180. return create_cancelled_error(state, self);
  1181. }
  1182. static void
  1183. FutureObj_finalize(FutureObj *fut)
  1184. {
  1185. PyObject *context;
  1186. PyObject *message = NULL;
  1187. PyObject *func;
  1188. if (!fut->fut_log_tb) {
  1189. return;
  1190. }
  1191. assert(fut->fut_exception != NULL);
  1192. fut->fut_log_tb = 0;
  1193. /* Save the current exception, if any. */
  1194. PyObject *exc = PyErr_GetRaisedException();
  1195. context = PyDict_New();
  1196. if (context == NULL) {
  1197. goto finally;
  1198. }
  1199. message = PyUnicode_FromFormat(
  1200. "%s exception was never retrieved", _PyType_Name(Py_TYPE(fut)));
  1201. if (message == NULL) {
  1202. goto finally;
  1203. }
  1204. if (PyDict_SetItem(context, &_Py_ID(message), message) < 0 ||
  1205. PyDict_SetItem(context, &_Py_ID(exception), fut->fut_exception) < 0 ||
  1206. PyDict_SetItem(context, &_Py_ID(future), (PyObject*)fut) < 0) {
  1207. goto finally;
  1208. }
  1209. if (fut->fut_source_tb != NULL) {
  1210. if (PyDict_SetItem(context, &_Py_ID(source_traceback),
  1211. fut->fut_source_tb) < 0) {
  1212. goto finally;
  1213. }
  1214. }
  1215. func = PyObject_GetAttr(fut->fut_loop, &_Py_ID(call_exception_handler));
  1216. if (func != NULL) {
  1217. PyObject *res = PyObject_CallOneArg(func, context);
  1218. if (res == NULL) {
  1219. PyErr_WriteUnraisable(func);
  1220. }
  1221. else {
  1222. Py_DECREF(res);
  1223. }
  1224. Py_DECREF(func);
  1225. }
  1226. finally:
  1227. Py_XDECREF(context);
  1228. Py_XDECREF(message);
  1229. /* Restore the saved exception. */
  1230. PyErr_SetRaisedException(exc);
  1231. }
  1232. static PyMethodDef FutureType_methods[] = {
  1233. _ASYNCIO_FUTURE_RESULT_METHODDEF
  1234. _ASYNCIO_FUTURE_EXCEPTION_METHODDEF
  1235. _ASYNCIO_FUTURE_SET_RESULT_METHODDEF
  1236. _ASYNCIO_FUTURE_SET_EXCEPTION_METHODDEF
  1237. _ASYNCIO_FUTURE_ADD_DONE_CALLBACK_METHODDEF
  1238. _ASYNCIO_FUTURE_REMOVE_DONE_CALLBACK_METHODDEF
  1239. _ASYNCIO_FUTURE_CANCEL_METHODDEF
  1240. _ASYNCIO_FUTURE_CANCELLED_METHODDEF
  1241. _ASYNCIO_FUTURE_DONE_METHODDEF
  1242. _ASYNCIO_FUTURE_GET_LOOP_METHODDEF
  1243. _ASYNCIO_FUTURE__MAKE_CANCELLED_ERROR_METHODDEF
  1244. {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
  1245. {NULL, NULL} /* Sentinel */
  1246. };
  1247. static PyMemberDef FutureType_members[] = {
  1248. {"__weaklistoffset__", T_PYSSIZET, offsetof(FutureObj, fut_weakreflist), READONLY},
  1249. {"__dictoffset__", T_PYSSIZET, offsetof(FutureObj, dict), READONLY},
  1250. {NULL},
  1251. };
  1252. #define FUTURE_COMMON_GETSETLIST \
  1253. {"_state", (getter)FutureObj_get_state, NULL, NULL}, \
  1254. {"_asyncio_future_blocking", (getter)FutureObj_get_blocking, \
  1255. (setter)FutureObj_set_blocking, NULL}, \
  1256. {"_loop", (getter)FutureObj_get_loop, NULL, NULL}, \
  1257. {"_callbacks", (getter)FutureObj_get_callbacks, NULL, NULL}, \
  1258. {"_result", (getter)FutureObj_get_result, NULL, NULL}, \
  1259. {"_exception", (getter)FutureObj_get_exception, NULL, NULL}, \
  1260. {"_log_traceback", (getter)FutureObj_get_log_traceback, \
  1261. (setter)FutureObj_set_log_traceback, NULL}, \
  1262. {"_source_traceback", (getter)FutureObj_get_source_traceback, \
  1263. NULL, NULL}, \
  1264. {"_cancel_message", (getter)FutureObj_get_cancel_message, \
  1265. (setter)FutureObj_set_cancel_message, NULL},
  1266. static PyGetSetDef FutureType_getsetlist[] = {
  1267. FUTURE_COMMON_GETSETLIST
  1268. {NULL} /* Sentinel */
  1269. };
  1270. static void FutureObj_dealloc(PyObject *self);
  1271. static PyType_Slot Future_slots[] = {
  1272. {Py_tp_dealloc, FutureObj_dealloc},
  1273. {Py_tp_repr, (reprfunc)FutureObj_repr},
  1274. {Py_tp_doc, (void *)_asyncio_Future___init____doc__},
  1275. {Py_tp_traverse, (traverseproc)FutureObj_traverse},
  1276. {Py_tp_clear, (inquiry)FutureObj_clear},
  1277. {Py_tp_iter, (getiterfunc)future_new_iter},
  1278. {Py_tp_methods, FutureType_methods},
  1279. {Py_tp_members, FutureType_members},
  1280. {Py_tp_getset, FutureType_getsetlist},
  1281. {Py_tp_init, (initproc)_asyncio_Future___init__},
  1282. {Py_tp_new, PyType_GenericNew},
  1283. {Py_tp_finalize, (destructor)FutureObj_finalize},
  1284. // async slots
  1285. {Py_am_await, (unaryfunc)future_new_iter},
  1286. {0, NULL},
  1287. };
  1288. static PyType_Spec Future_spec = {
  1289. .name = "_asyncio.Future",
  1290. .basicsize = sizeof(FutureObj),
  1291. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE |
  1292. Py_TPFLAGS_IMMUTABLETYPE),
  1293. .slots = Future_slots,
  1294. };
  1295. static void
  1296. FutureObj_dealloc(PyObject *self)
  1297. {
  1298. FutureObj *fut = (FutureObj *)self;
  1299. if (PyObject_CallFinalizerFromDealloc(self) < 0) {
  1300. // resurrected.
  1301. return;
  1302. }
  1303. PyTypeObject *tp = Py_TYPE(fut);
  1304. PyObject_GC_UnTrack(self);
  1305. if (fut->fut_weakreflist != NULL) {
  1306. PyObject_ClearWeakRefs(self);
  1307. }
  1308. (void)FutureObj_clear(fut);
  1309. tp->tp_free(fut);
  1310. Py_DECREF(tp);
  1311. }
  1312. /*********************** Future Iterator **************************/
  1313. typedef struct futureiterobject {
  1314. PyObject_HEAD
  1315. FutureObj *future;
  1316. } futureiterobject;
  1317. static void
  1318. FutureIter_dealloc(futureiterobject *it)
  1319. {
  1320. PyTypeObject *tp = Py_TYPE(it);
  1321. // FutureIter is a heap type so any subclass must also be a heap type.
  1322. assert(_PyType_HasFeature(tp, Py_TPFLAGS_HEAPTYPE));
  1323. PyObject *module = ((PyHeapTypeObject*)tp)->ht_module;
  1324. asyncio_state *state = NULL;
  1325. PyObject_GC_UnTrack(it);
  1326. tp->tp_clear((PyObject *)it);
  1327. // GH-115874: We can't use PyType_GetModuleByDef here as the type might have
  1328. // already been cleared, which is also why we must check if ht_module != NULL.
  1329. // Due to this restriction, subclasses that belong to a different module
  1330. // will not be able to use the free list.
  1331. if (module && _PyModule_GetDef(module) == &_asynciomodule) {
  1332. state = get_asyncio_state(module);
  1333. }
  1334. if (state && state->fi_freelist_len < FI_FREELIST_MAXLEN) {
  1335. state->fi_freelist_len++;
  1336. it->future = (FutureObj*) state->fi_freelist;
  1337. state->fi_freelist = it;
  1338. }
  1339. else {
  1340. PyObject_GC_Del(it);
  1341. Py_DECREF(tp);
  1342. }
  1343. }
  1344. static PySendResult
  1345. FutureIter_am_send(futureiterobject *it,
  1346. PyObject *Py_UNUSED(arg),
  1347. PyObject **result)
  1348. {
  1349. /* arg is unused, see the comment on FutureIter_send for clarification */
  1350. PyObject *res;
  1351. FutureObj *fut = it->future;
  1352. *result = NULL;
  1353. if (fut == NULL) {
  1354. return PYGEN_ERROR;
  1355. }
  1356. if (fut->fut_state == STATE_PENDING) {
  1357. if (!fut->fut_blocking) {
  1358. fut->fut_blocking = 1;
  1359. *result = Py_NewRef(fut);
  1360. return PYGEN_NEXT;
  1361. }
  1362. PyErr_SetString(PyExc_RuntimeError,
  1363. "await wasn't used with future");
  1364. return PYGEN_ERROR;
  1365. }
  1366. it->future = NULL;
  1367. res = _asyncio_Future_result_impl(fut);
  1368. if (res != NULL) {
  1369. Py_DECREF(fut);
  1370. *result = res;
  1371. return PYGEN_RETURN;
  1372. }
  1373. Py_DECREF(fut);
  1374. return PYGEN_ERROR;
  1375. }
  1376. static PyObject *
  1377. FutureIter_iternext(futureiterobject *it)
  1378. {
  1379. PyObject *result;
  1380. switch (FutureIter_am_send(it, Py_None, &result)) {
  1381. case PYGEN_RETURN:
  1382. (void)_PyGen_SetStopIterationValue(result);
  1383. Py_DECREF(result);
  1384. return NULL;
  1385. case PYGEN_NEXT:
  1386. return result;
  1387. case PYGEN_ERROR:
  1388. return NULL;
  1389. default:
  1390. Py_UNREACHABLE();
  1391. }
  1392. }
  1393. static PyObject *
  1394. FutureIter_send(futureiterobject *self, PyObject *unused)
  1395. {
  1396. /* Future.__iter__ doesn't care about values that are pushed to the
  1397. * generator, it just returns self.result().
  1398. */
  1399. return FutureIter_iternext(self);
  1400. }
  1401. static PyObject *
  1402. FutureIter_throw(futureiterobject *self, PyObject *const *args, Py_ssize_t nargs)
  1403. {
  1404. PyObject *type, *val = NULL, *tb = NULL;
  1405. if (!_PyArg_CheckPositional("throw", nargs, 1, 3)) {
  1406. return NULL;
  1407. }
  1408. if (nargs > 1) {
  1409. if (PyErr_WarnEx(PyExc_DeprecationWarning,
  1410. "the (type, exc, tb) signature of throw() is deprecated, "
  1411. "use the single-arg signature instead.",
  1412. 1) < 0) {
  1413. return NULL;
  1414. }
  1415. }
  1416. type = args[0];
  1417. if (nargs == 3) {
  1418. val = args[1];
  1419. tb = args[2];
  1420. }
  1421. else if (nargs == 2) {
  1422. val = args[1];
  1423. }
  1424. if (val == Py_None) {
  1425. val = NULL;
  1426. }
  1427. if (tb == Py_None ) {
  1428. tb = NULL;
  1429. } else if (tb != NULL && !PyTraceBack_Check(tb)) {
  1430. PyErr_SetString(PyExc_TypeError, "throw() third argument must be a traceback");
  1431. return NULL;
  1432. }
  1433. Py_INCREF(type);
  1434. Py_XINCREF(val);
  1435. Py_XINCREF(tb);
  1436. if (PyExceptionClass_Check(type)) {
  1437. PyErr_NormalizeException(&type, &val, &tb);
  1438. /* No need to call PyException_SetTraceback since we'll be calling
  1439. PyErr_Restore for `type`, `val`, and `tb`. */
  1440. } else if (PyExceptionInstance_Check(type)) {
  1441. if (val) {
  1442. PyErr_SetString(PyExc_TypeError,
  1443. "instance exception may not have a separate value");
  1444. goto fail;
  1445. }
  1446. val = type;
  1447. type = PyExceptionInstance_Class(type);
  1448. Py_INCREF(type);
  1449. if (tb == NULL)
  1450. tb = PyException_GetTraceback(val);
  1451. } else {
  1452. PyErr_SetString(PyExc_TypeError,
  1453. "exceptions must be classes deriving BaseException or "
  1454. "instances of such a class");
  1455. goto fail;
  1456. }
  1457. Py_CLEAR(self->future);
  1458. PyErr_Restore(type, val, tb);
  1459. return NULL;
  1460. fail:
  1461. Py_DECREF(type);
  1462. Py_XDECREF(val);
  1463. Py_XDECREF(tb);
  1464. return NULL;
  1465. }
  1466. static int
  1467. FutureIter_clear(futureiterobject *it)
  1468. {
  1469. Py_CLEAR(it->future);
  1470. return 0;
  1471. }
  1472. static PyObject *
  1473. FutureIter_close(futureiterobject *self, PyObject *arg)
  1474. {
  1475. (void)FutureIter_clear(self);
  1476. Py_RETURN_NONE;
  1477. }
  1478. static int
  1479. FutureIter_traverse(futureiterobject *it, visitproc visit, void *arg)
  1480. {
  1481. Py_VISIT(Py_TYPE(it));
  1482. Py_VISIT(it->future);
  1483. return 0;
  1484. }
  1485. static PyMethodDef FutureIter_methods[] = {
  1486. {"send", (PyCFunction)FutureIter_send, METH_O, NULL},
  1487. {"throw", _PyCFunction_CAST(FutureIter_throw), METH_FASTCALL, NULL},
  1488. {"close", (PyCFunction)FutureIter_close, METH_NOARGS, NULL},
  1489. {NULL, NULL} /* Sentinel */
  1490. };
  1491. static PyType_Slot FutureIter_slots[] = {
  1492. {Py_tp_dealloc, (destructor)FutureIter_dealloc},
  1493. {Py_tp_getattro, PyObject_GenericGetAttr},
  1494. {Py_tp_traverse, (traverseproc)FutureIter_traverse},
  1495. {Py_tp_clear, FutureIter_clear},
  1496. {Py_tp_iter, PyObject_SelfIter},
  1497. {Py_tp_iternext, (iternextfunc)FutureIter_iternext},
  1498. {Py_tp_methods, FutureIter_methods},
  1499. // async methods
  1500. {Py_am_send, (sendfunc)FutureIter_am_send},
  1501. {0, NULL},
  1502. };
  1503. static PyType_Spec FutureIter_spec = {
  1504. .name = "_asyncio.FutureIter",
  1505. .basicsize = sizeof(futureiterobject),
  1506. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  1507. Py_TPFLAGS_IMMUTABLETYPE),
  1508. .slots = FutureIter_slots,
  1509. };
  1510. static PyObject *
  1511. future_new_iter(PyObject *fut)
  1512. {
  1513. futureiterobject *it;
  1514. asyncio_state *state = get_asyncio_state_by_def((PyObject *)fut);
  1515. ENSURE_FUTURE_ALIVE(state, fut)
  1516. if (state->fi_freelist_len) {
  1517. state->fi_freelist_len--;
  1518. it = state->fi_freelist;
  1519. state->fi_freelist = (futureiterobject*) it->future;
  1520. it->future = NULL;
  1521. _Py_NewReference((PyObject*) it);
  1522. }
  1523. else {
  1524. it = PyObject_GC_New(futureiterobject, state->FutureIterType);
  1525. if (it == NULL) {
  1526. return NULL;
  1527. }
  1528. }
  1529. it->future = (FutureObj*)Py_NewRef(fut);
  1530. PyObject_GC_Track(it);
  1531. return (PyObject*)it;
  1532. }
  1533. /*********************** Task **************************/
  1534. /*[clinic input]
  1535. class _asyncio.Task "TaskObj *" "&Task_Type"
  1536. [clinic start generated code]*/
  1537. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=719dcef0fcc03b37]*/
  1538. static int task_call_step_soon(asyncio_state *state, TaskObj *, PyObject *);
  1539. static PyObject * task_wakeup(TaskObj *, PyObject *);
  1540. static PyObject * task_step(asyncio_state *, TaskObj *, PyObject *);
  1541. static int task_eager_start(asyncio_state *state, TaskObj *task);
  1542. /* ----- Task._step wrapper */
  1543. static int
  1544. TaskStepMethWrapper_clear(TaskStepMethWrapper *o)
  1545. {
  1546. Py_CLEAR(o->sw_task);
  1547. Py_CLEAR(o->sw_arg);
  1548. return 0;
  1549. }
  1550. static void
  1551. TaskStepMethWrapper_dealloc(TaskStepMethWrapper *o)
  1552. {
  1553. PyTypeObject *tp = Py_TYPE(o);
  1554. PyObject_GC_UnTrack(o);
  1555. (void)TaskStepMethWrapper_clear(o);
  1556. Py_TYPE(o)->tp_free(o);
  1557. Py_DECREF(tp);
  1558. }
  1559. static PyObject *
  1560. TaskStepMethWrapper_call(TaskStepMethWrapper *o,
  1561. PyObject *args, PyObject *kwds)
  1562. {
  1563. if (kwds != NULL && PyDict_GET_SIZE(kwds) != 0) {
  1564. PyErr_SetString(PyExc_TypeError, "function takes no keyword arguments");
  1565. return NULL;
  1566. }
  1567. if (args != NULL && PyTuple_GET_SIZE(args) != 0) {
  1568. PyErr_SetString(PyExc_TypeError, "function takes no positional arguments");
  1569. return NULL;
  1570. }
  1571. asyncio_state *state = get_asyncio_state_by_def((PyObject *)o);
  1572. return task_step(state, o->sw_task, o->sw_arg);
  1573. }
  1574. static int
  1575. TaskStepMethWrapper_traverse(TaskStepMethWrapper *o,
  1576. visitproc visit, void *arg)
  1577. {
  1578. Py_VISIT(Py_TYPE(o));
  1579. Py_VISIT(o->sw_task);
  1580. Py_VISIT(o->sw_arg);
  1581. return 0;
  1582. }
  1583. static PyObject *
  1584. TaskStepMethWrapper_get___self__(TaskStepMethWrapper *o, void *Py_UNUSED(ignored))
  1585. {
  1586. if (o->sw_task) {
  1587. return Py_NewRef(o->sw_task);
  1588. }
  1589. Py_RETURN_NONE;
  1590. }
  1591. static PyGetSetDef TaskStepMethWrapper_getsetlist[] = {
  1592. {"__self__", (getter)TaskStepMethWrapper_get___self__, NULL, NULL},
  1593. {NULL} /* Sentinel */
  1594. };
  1595. static PyType_Slot TaskStepMethWrapper_slots[] = {
  1596. {Py_tp_getset, TaskStepMethWrapper_getsetlist},
  1597. {Py_tp_dealloc, (destructor)TaskStepMethWrapper_dealloc},
  1598. {Py_tp_call, (ternaryfunc)TaskStepMethWrapper_call},
  1599. {Py_tp_getattro, PyObject_GenericGetAttr},
  1600. {Py_tp_traverse, (traverseproc)TaskStepMethWrapper_traverse},
  1601. {Py_tp_clear, (inquiry)TaskStepMethWrapper_clear},
  1602. {0, NULL},
  1603. };
  1604. static PyType_Spec TaskStepMethWrapper_spec = {
  1605. .name = "_asyncio.TaskStepMethWrapper",
  1606. .basicsize = sizeof(TaskStepMethWrapper),
  1607. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  1608. Py_TPFLAGS_IMMUTABLETYPE),
  1609. .slots = TaskStepMethWrapper_slots,
  1610. };
  1611. static PyObject *
  1612. TaskStepMethWrapper_new(TaskObj *task, PyObject *arg)
  1613. {
  1614. asyncio_state *state = get_asyncio_state_by_def((PyObject *)task);
  1615. TaskStepMethWrapper *o;
  1616. o = PyObject_GC_New(TaskStepMethWrapper, state->TaskStepMethWrapper_Type);
  1617. if (o == NULL) {
  1618. return NULL;
  1619. }
  1620. o->sw_task = (TaskObj*)Py_NewRef(task);
  1621. o->sw_arg = Py_XNewRef(arg);
  1622. PyObject_GC_Track(o);
  1623. return (PyObject*) o;
  1624. }
  1625. /* ----- Task._wakeup implementation */
  1626. static PyMethodDef TaskWakeupDef = {
  1627. "task_wakeup",
  1628. (PyCFunction)task_wakeup,
  1629. METH_O,
  1630. NULL
  1631. };
  1632. /* ----- Task introspection helpers */
  1633. static int
  1634. register_task(asyncio_state *state, PyObject *task)
  1635. {
  1636. PyObject *res = PyObject_CallMethodOneArg(state->scheduled_tasks,
  1637. &_Py_ID(add), task);
  1638. if (res == NULL) {
  1639. return -1;
  1640. }
  1641. Py_DECREF(res);
  1642. return 0;
  1643. }
  1644. static int
  1645. register_eager_task(asyncio_state *state, PyObject *task)
  1646. {
  1647. return PySet_Add(state->eager_tasks, task);
  1648. }
  1649. static int
  1650. unregister_task(asyncio_state *state, PyObject *task)
  1651. {
  1652. PyObject *res = PyObject_CallMethodOneArg(state->scheduled_tasks,
  1653. &_Py_ID(discard), task);
  1654. if (res == NULL) {
  1655. return -1;
  1656. }
  1657. Py_DECREF(res);
  1658. return 0;
  1659. }
  1660. static int
  1661. unregister_eager_task(asyncio_state *state, PyObject *task)
  1662. {
  1663. return PySet_Discard(state->eager_tasks, task);
  1664. }
  1665. static int
  1666. enter_task(asyncio_state *state, PyObject *loop, PyObject *task)
  1667. {
  1668. PyObject *item;
  1669. Py_hash_t hash;
  1670. hash = PyObject_Hash(loop);
  1671. if (hash == -1) {
  1672. return -1;
  1673. }
  1674. item = _PyDict_GetItem_KnownHash(state->current_tasks, loop, hash);
  1675. if (item != NULL) {
  1676. Py_INCREF(item);
  1677. PyErr_Format(
  1678. PyExc_RuntimeError,
  1679. "Cannot enter into task %R while another " \
  1680. "task %R is being executed.",
  1681. task, item, NULL);
  1682. Py_DECREF(item);
  1683. return -1;
  1684. }
  1685. if (PyErr_Occurred()) {
  1686. return -1;
  1687. }
  1688. return _PyDict_SetItem_KnownHash(state->current_tasks, loop, task, hash);
  1689. }
  1690. static int
  1691. leave_task(asyncio_state *state, PyObject *loop, PyObject *task)
  1692. /*[clinic end generated code: output=0ebf6db4b858fb41 input=51296a46313d1ad8]*/
  1693. {
  1694. PyObject *item;
  1695. Py_hash_t hash;
  1696. hash = PyObject_Hash(loop);
  1697. if (hash == -1) {
  1698. return -1;
  1699. }
  1700. item = _PyDict_GetItem_KnownHash(state->current_tasks, loop, hash);
  1701. if (item != task) {
  1702. if (item == NULL) {
  1703. /* Not entered, replace with None */
  1704. item = Py_None;
  1705. }
  1706. PyErr_Format(
  1707. PyExc_RuntimeError,
  1708. "Leaving task %R does not match the current task %R.",
  1709. task, item, NULL);
  1710. return -1;
  1711. }
  1712. return _PyDict_DelItem_KnownHash(state->current_tasks, loop, hash);
  1713. }
  1714. static PyObject *
  1715. swap_current_task(asyncio_state *state, PyObject *loop, PyObject *task)
  1716. {
  1717. PyObject *prev_task;
  1718. Py_hash_t hash;
  1719. hash = PyObject_Hash(loop);
  1720. if (hash == -1) {
  1721. return NULL;
  1722. }
  1723. prev_task = _PyDict_GetItem_KnownHash(state->current_tasks, loop, hash);
  1724. if (prev_task == NULL) {
  1725. if (PyErr_Occurred()) {
  1726. return NULL;
  1727. }
  1728. prev_task = Py_None;
  1729. }
  1730. Py_INCREF(prev_task);
  1731. if (task == Py_None) {
  1732. if (_PyDict_DelItem_KnownHash(state->current_tasks, loop, hash) == -1) {
  1733. goto error;
  1734. }
  1735. } else {
  1736. if (_PyDict_SetItem_KnownHash(state->current_tasks, loop, task, hash) == -1) {
  1737. goto error;
  1738. }
  1739. }
  1740. return prev_task;
  1741. error:
  1742. Py_DECREF(prev_task);
  1743. return NULL;
  1744. }
  1745. /* ----- Task */
  1746. /*[clinic input]
  1747. _asyncio.Task.__init__
  1748. coro: object
  1749. *
  1750. loop: object = None
  1751. name: object = None
  1752. context: object = None
  1753. eager_start: bool = False
  1754. A coroutine wrapped in a Future.
  1755. [clinic start generated code]*/
  1756. static int
  1757. _asyncio_Task___init___impl(TaskObj *self, PyObject *coro, PyObject *loop,
  1758. PyObject *name, PyObject *context,
  1759. int eager_start)
  1760. /*[clinic end generated code: output=7aced2d27836f1a1 input=18e3f113a51b829d]*/
  1761. {
  1762. if (future_init((FutureObj*)self, loop)) {
  1763. return -1;
  1764. }
  1765. asyncio_state *state = get_asyncio_state_by_def((PyObject *)self);
  1766. int is_coro = is_coroutine(state, coro);
  1767. if (is_coro == -1) {
  1768. return -1;
  1769. }
  1770. if (is_coro == 0) {
  1771. self->task_log_destroy_pending = 0;
  1772. PyErr_Format(PyExc_TypeError,
  1773. "a coroutine was expected, got %R",
  1774. coro, NULL);
  1775. return -1;
  1776. }
  1777. if (context == Py_None) {
  1778. Py_XSETREF(self->task_context, PyContext_CopyCurrent());
  1779. if (self->task_context == NULL) {
  1780. return -1;
  1781. }
  1782. } else {
  1783. self->task_context = Py_NewRef(context);
  1784. }
  1785. Py_CLEAR(self->task_fut_waiter);
  1786. self->task_must_cancel = 0;
  1787. self->task_log_destroy_pending = 1;
  1788. self->task_num_cancels_requested = 0;
  1789. Py_INCREF(coro);
  1790. Py_XSETREF(self->task_coro, coro);
  1791. if (name == Py_None) {
  1792. // optimization: defer task name formatting
  1793. // store the task counter as PyLong in the name
  1794. // for deferred formatting in get_name
  1795. name = PyLong_FromUnsignedLongLong(++state->task_name_counter);
  1796. } else if (!PyUnicode_CheckExact(name)) {
  1797. name = PyObject_Str(name);
  1798. } else {
  1799. Py_INCREF(name);
  1800. }
  1801. Py_XSETREF(self->task_name, name);
  1802. if (self->task_name == NULL) {
  1803. return -1;
  1804. }
  1805. if (eager_start) {
  1806. PyObject *res = PyObject_CallMethodNoArgs(loop, &_Py_ID(is_running));
  1807. if (res == NULL) {
  1808. return -1;
  1809. }
  1810. int is_loop_running = Py_IsTrue(res);
  1811. Py_DECREF(res);
  1812. if (is_loop_running) {
  1813. if (task_eager_start(state, self)) {
  1814. return -1;
  1815. }
  1816. return 0;
  1817. }
  1818. }
  1819. if (task_call_step_soon(state, self, NULL)) {
  1820. return -1;
  1821. }
  1822. return register_task(state, (PyObject*)self);
  1823. }
  1824. static int
  1825. TaskObj_clear(TaskObj *task)
  1826. {
  1827. (void)FutureObj_clear((FutureObj*) task);
  1828. Py_CLEAR(task->task_context);
  1829. Py_CLEAR(task->task_coro);
  1830. Py_CLEAR(task->task_name);
  1831. Py_CLEAR(task->task_fut_waiter);
  1832. return 0;
  1833. }
  1834. static int
  1835. TaskObj_traverse(TaskObj *task, visitproc visit, void *arg)
  1836. {
  1837. Py_VISIT(Py_TYPE(task));
  1838. Py_VISIT(task->task_context);
  1839. Py_VISIT(task->task_coro);
  1840. Py_VISIT(task->task_name);
  1841. Py_VISIT(task->task_fut_waiter);
  1842. FutureObj *fut = (FutureObj *)task;
  1843. Py_VISIT(fut->fut_loop);
  1844. Py_VISIT(fut->fut_callback0);
  1845. Py_VISIT(fut->fut_context0);
  1846. Py_VISIT(fut->fut_callbacks);
  1847. Py_VISIT(fut->fut_result);
  1848. Py_VISIT(fut->fut_exception);
  1849. Py_VISIT(fut->fut_exception_tb);
  1850. Py_VISIT(fut->fut_source_tb);
  1851. Py_VISIT(fut->fut_cancel_msg);
  1852. Py_VISIT(fut->fut_cancelled_exc);
  1853. Py_VISIT(fut->dict);
  1854. return 0;
  1855. }
  1856. static PyObject *
  1857. TaskObj_get_log_destroy_pending(TaskObj *task, void *Py_UNUSED(ignored))
  1858. {
  1859. if (task->task_log_destroy_pending) {
  1860. Py_RETURN_TRUE;
  1861. }
  1862. else {
  1863. Py_RETURN_FALSE;
  1864. }
  1865. }
  1866. static int
  1867. TaskObj_set_log_destroy_pending(TaskObj *task, PyObject *val, void *Py_UNUSED(ignored))
  1868. {
  1869. if (val == NULL) {
  1870. PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
  1871. return -1;
  1872. }
  1873. int is_true = PyObject_IsTrue(val);
  1874. if (is_true < 0) {
  1875. return -1;
  1876. }
  1877. task->task_log_destroy_pending = is_true;
  1878. return 0;
  1879. }
  1880. static PyObject *
  1881. TaskObj_get_must_cancel(TaskObj *task, void *Py_UNUSED(ignored))
  1882. {
  1883. if (task->task_must_cancel) {
  1884. Py_RETURN_TRUE;
  1885. }
  1886. else {
  1887. Py_RETURN_FALSE;
  1888. }
  1889. }
  1890. static PyObject *
  1891. TaskObj_get_coro(TaskObj *task, void *Py_UNUSED(ignored))
  1892. {
  1893. if (task->task_coro) {
  1894. return Py_NewRef(task->task_coro);
  1895. }
  1896. Py_RETURN_NONE;
  1897. }
  1898. static PyObject *
  1899. TaskObj_get_fut_waiter(TaskObj *task, void *Py_UNUSED(ignored))
  1900. {
  1901. if (task->task_fut_waiter) {
  1902. return Py_NewRef(task->task_fut_waiter);
  1903. }
  1904. Py_RETURN_NONE;
  1905. }
  1906. static PyObject *
  1907. TaskObj_repr(TaskObj *task)
  1908. {
  1909. asyncio_state *state = get_asyncio_state_by_def((PyObject *)task);
  1910. return PyObject_CallOneArg(state->asyncio_task_repr_func,
  1911. (PyObject *)task);
  1912. }
  1913. /*[clinic input]
  1914. _asyncio.Task._make_cancelled_error
  1915. Create the CancelledError to raise if the Task is cancelled.
  1916. This should only be called once when handling a cancellation since
  1917. it erases the context exception value.
  1918. [clinic start generated code]*/
  1919. static PyObject *
  1920. _asyncio_Task__make_cancelled_error_impl(TaskObj *self)
  1921. /*[clinic end generated code: output=55a819e8b4276fab input=52c0e32de8e2f840]*/
  1922. {
  1923. FutureObj *fut = (FutureObj*)self;
  1924. return _asyncio_Future__make_cancelled_error_impl(fut);
  1925. }
  1926. /*[clinic input]
  1927. _asyncio.Task.cancel
  1928. msg: object = None
  1929. Request that this task cancel itself.
  1930. This arranges for a CancelledError to be thrown into the
  1931. wrapped coroutine on the next cycle through the event loop.
  1932. The coroutine then has a chance to clean up or even deny
  1933. the request using try/except/finally.
  1934. Unlike Future.cancel, this does not guarantee that the
  1935. task will be cancelled: the exception might be caught and
  1936. acted upon, delaying cancellation of the task or preventing
  1937. cancellation completely. The task may also return a value or
  1938. raise a different exception.
  1939. Immediately after this method is called, Task.cancelled() will
  1940. not return True (unless the task was already cancelled). A
  1941. task will be marked as cancelled when the wrapped coroutine
  1942. terminates with a CancelledError exception (even if cancel()
  1943. was not called).
  1944. This also increases the task's count of cancellation requests.
  1945. [clinic start generated code]*/
  1946. static PyObject *
  1947. _asyncio_Task_cancel_impl(TaskObj *self, PyObject *msg)
  1948. /*[clinic end generated code: output=c66b60d41c74f9f1 input=7bb51bf25974c783]*/
  1949. {
  1950. self->task_log_tb = 0;
  1951. if (self->task_state != STATE_PENDING) {
  1952. Py_RETURN_FALSE;
  1953. }
  1954. self->task_num_cancels_requested += 1;
  1955. // These three lines are controversial. See discussion starting at
  1956. // https://github.com/python/cpython/pull/31394#issuecomment-1053545331
  1957. // and corresponding code in tasks.py.
  1958. // if (self->task_num_cancels_requested > 1) {
  1959. // Py_RETURN_FALSE;
  1960. // }
  1961. if (self->task_fut_waiter) {
  1962. PyObject *res;
  1963. int is_true;
  1964. res = PyObject_CallMethodOneArg(self->task_fut_waiter,
  1965. &_Py_ID(cancel), msg);
  1966. if (res == NULL) {
  1967. return NULL;
  1968. }
  1969. is_true = PyObject_IsTrue(res);
  1970. Py_DECREF(res);
  1971. if (is_true < 0) {
  1972. return NULL;
  1973. }
  1974. if (is_true) {
  1975. Py_RETURN_TRUE;
  1976. }
  1977. }
  1978. self->task_must_cancel = 1;
  1979. Py_XINCREF(msg);
  1980. Py_XSETREF(self->task_cancel_msg, msg);
  1981. Py_RETURN_TRUE;
  1982. }
  1983. /*[clinic input]
  1984. _asyncio.Task.cancelling
  1985. Return the count of the task's cancellation requests.
  1986. This count is incremented when .cancel() is called
  1987. and may be decremented using .uncancel().
  1988. [clinic start generated code]*/
  1989. static PyObject *
  1990. _asyncio_Task_cancelling_impl(TaskObj *self)
  1991. /*[clinic end generated code: output=803b3af96f917d7e input=b625224d310cbb17]*/
  1992. /*[clinic end generated code]*/
  1993. {
  1994. return PyLong_FromLong(self->task_num_cancels_requested);
  1995. }
  1996. /*[clinic input]
  1997. _asyncio.Task.uncancel
  1998. Decrement the task's count of cancellation requests.
  1999. This should be used by tasks that catch CancelledError
  2000. and wish to continue indefinitely until they are cancelled again.
  2001. Returns the remaining number of cancellation requests.
  2002. [clinic start generated code]*/
  2003. static PyObject *
  2004. _asyncio_Task_uncancel_impl(TaskObj *self)
  2005. /*[clinic end generated code: output=58184d236a817d3c input=68f81a4b90b46be2]*/
  2006. /*[clinic end generated code]*/
  2007. {
  2008. if (self->task_num_cancels_requested > 0) {
  2009. self->task_num_cancels_requested -= 1;
  2010. }
  2011. return PyLong_FromLong(self->task_num_cancels_requested);
  2012. }
  2013. /*[clinic input]
  2014. _asyncio.Task.get_stack
  2015. cls: defining_class
  2016. /
  2017. *
  2018. limit: object = None
  2019. Return the list of stack frames for this task's coroutine.
  2020. If the coroutine is not done, this returns the stack where it is
  2021. suspended. If the coroutine has completed successfully or was
  2022. cancelled, this returns an empty list. If the coroutine was
  2023. terminated by an exception, this returns the list of traceback
  2024. frames.
  2025. The frames are always ordered from oldest to newest.
  2026. The optional limit gives the maximum number of frames to
  2027. return; by default all available frames are returned. Its
  2028. meaning differs depending on whether a stack or a traceback is
  2029. returned: the newest frames of a stack are returned, but the
  2030. oldest frames of a traceback are returned. (This matches the
  2031. behavior of the traceback module.)
  2032. For reasons beyond our control, only one stack frame is
  2033. returned for a suspended coroutine.
  2034. [clinic start generated code]*/
  2035. static PyObject *
  2036. _asyncio_Task_get_stack_impl(TaskObj *self, PyTypeObject *cls,
  2037. PyObject *limit)
  2038. /*[clinic end generated code: output=6774dfc10d3857fa input=8e01c9b2618ae953]*/
  2039. {
  2040. asyncio_state *state = get_asyncio_state_by_cls(cls);
  2041. PyObject *stack[] = {(PyObject *)self, limit};
  2042. return PyObject_Vectorcall(state->asyncio_task_get_stack_func,
  2043. stack, 2, NULL);
  2044. }
  2045. /*[clinic input]
  2046. _asyncio.Task.print_stack
  2047. cls: defining_class
  2048. /
  2049. *
  2050. limit: object = None
  2051. file: object = None
  2052. Print the stack or traceback for this task's coroutine.
  2053. This produces output similar to that of the traceback module,
  2054. for the frames retrieved by get_stack(). The limit argument
  2055. is passed to get_stack(). The file argument is an I/O stream
  2056. to which the output is written; by default output is written
  2057. to sys.stderr.
  2058. [clinic start generated code]*/
  2059. static PyObject *
  2060. _asyncio_Task_print_stack_impl(TaskObj *self, PyTypeObject *cls,
  2061. PyObject *limit, PyObject *file)
  2062. /*[clinic end generated code: output=b38affe9289ec826 input=150b35ba2d3a7dee]*/
  2063. {
  2064. asyncio_state *state = get_asyncio_state_by_cls(cls);
  2065. PyObject *stack[] = {(PyObject *)self, limit, file};
  2066. return PyObject_Vectorcall(state->asyncio_task_print_stack_func,
  2067. stack, 3, NULL);
  2068. }
  2069. /*[clinic input]
  2070. _asyncio.Task.set_result
  2071. result: object
  2072. /
  2073. [clinic start generated code]*/
  2074. static PyObject *
  2075. _asyncio_Task_set_result(TaskObj *self, PyObject *result)
  2076. /*[clinic end generated code: output=1dcae308bfcba318 input=9d1a00c07be41bab]*/
  2077. {
  2078. PyErr_SetString(PyExc_RuntimeError,
  2079. "Task does not support set_result operation");
  2080. return NULL;
  2081. }
  2082. /*[clinic input]
  2083. _asyncio.Task.set_exception
  2084. exception: object
  2085. /
  2086. [clinic start generated code]*/
  2087. static PyObject *
  2088. _asyncio_Task_set_exception(TaskObj *self, PyObject *exception)
  2089. /*[clinic end generated code: output=bc377fc28067303d input=9a8f65c83dcf893a]*/
  2090. {
  2091. PyErr_SetString(PyExc_RuntimeError,
  2092. "Task does not support set_exception operation");
  2093. return NULL;
  2094. }
  2095. /*[clinic input]
  2096. _asyncio.Task.get_coro
  2097. [clinic start generated code]*/
  2098. static PyObject *
  2099. _asyncio_Task_get_coro_impl(TaskObj *self)
  2100. /*[clinic end generated code: output=bcac27c8cc6c8073 input=d2e8606c42a7b403]*/
  2101. {
  2102. if (self->task_coro) {
  2103. return Py_NewRef(self->task_coro);
  2104. }
  2105. Py_RETURN_NONE;
  2106. }
  2107. /*[clinic input]
  2108. _asyncio.Task.get_context
  2109. [clinic start generated code]*/
  2110. static PyObject *
  2111. _asyncio_Task_get_context_impl(TaskObj *self)
  2112. /*[clinic end generated code: output=6996f53d3dc01aef input=87c0b209b8fceeeb]*/
  2113. {
  2114. return Py_NewRef(self->task_context);
  2115. }
  2116. /*[clinic input]
  2117. _asyncio.Task.get_name
  2118. [clinic start generated code]*/
  2119. static PyObject *
  2120. _asyncio_Task_get_name_impl(TaskObj *self)
  2121. /*[clinic end generated code: output=0ecf1570c3b37a8f input=a4a6595d12f4f0f8]*/
  2122. {
  2123. if (self->task_name) {
  2124. if (PyLong_CheckExact(self->task_name)) {
  2125. PyObject *name = PyUnicode_FromFormat("Task-%S", self->task_name);
  2126. if (name == NULL) {
  2127. return NULL;
  2128. }
  2129. Py_SETREF(self->task_name, name);
  2130. }
  2131. return Py_NewRef(self->task_name);
  2132. }
  2133. Py_RETURN_NONE;
  2134. }
  2135. /*[clinic input]
  2136. _asyncio.Task.set_name
  2137. value: object
  2138. /
  2139. [clinic start generated code]*/
  2140. static PyObject *
  2141. _asyncio_Task_set_name(TaskObj *self, PyObject *value)
  2142. /*[clinic end generated code: output=138a8d51e32057d6 input=a8359b6e65f8fd31]*/
  2143. {
  2144. if (!PyUnicode_CheckExact(value)) {
  2145. value = PyObject_Str(value);
  2146. if (value == NULL) {
  2147. return NULL;
  2148. }
  2149. } else {
  2150. Py_INCREF(value);
  2151. }
  2152. Py_XSETREF(self->task_name, value);
  2153. Py_RETURN_NONE;
  2154. }
  2155. static void
  2156. TaskObj_finalize(TaskObj *task)
  2157. {
  2158. PyObject *context;
  2159. PyObject *message = NULL;
  2160. PyObject *func;
  2161. if (task->task_state != STATE_PENDING || !task->task_log_destroy_pending) {
  2162. goto done;
  2163. }
  2164. /* Save the current exception, if any. */
  2165. PyObject *exc = PyErr_GetRaisedException();
  2166. context = PyDict_New();
  2167. if (context == NULL) {
  2168. goto finally;
  2169. }
  2170. message = PyUnicode_FromString("Task was destroyed but it is pending!");
  2171. if (message == NULL) {
  2172. goto finally;
  2173. }
  2174. if (PyDict_SetItem(context, &_Py_ID(message), message) < 0 ||
  2175. PyDict_SetItem(context, &_Py_ID(task), (PyObject*)task) < 0)
  2176. {
  2177. goto finally;
  2178. }
  2179. if (task->task_source_tb != NULL) {
  2180. if (PyDict_SetItem(context, &_Py_ID(source_traceback),
  2181. task->task_source_tb) < 0)
  2182. {
  2183. goto finally;
  2184. }
  2185. }
  2186. func = PyObject_GetAttr(task->task_loop, &_Py_ID(call_exception_handler));
  2187. if (func != NULL) {
  2188. PyObject *res = PyObject_CallOneArg(func, context);
  2189. if (res == NULL) {
  2190. PyErr_WriteUnraisable(func);
  2191. }
  2192. else {
  2193. Py_DECREF(res);
  2194. }
  2195. Py_DECREF(func);
  2196. }
  2197. finally:
  2198. Py_XDECREF(context);
  2199. Py_XDECREF(message);
  2200. /* Restore the saved exception. */
  2201. PyErr_SetRaisedException(exc);
  2202. done:
  2203. FutureObj_finalize((FutureObj*)task);
  2204. }
  2205. static void TaskObj_dealloc(PyObject *); /* Needs Task_CheckExact */
  2206. static PyMethodDef TaskType_methods[] = {
  2207. _ASYNCIO_FUTURE_RESULT_METHODDEF
  2208. _ASYNCIO_FUTURE_EXCEPTION_METHODDEF
  2209. _ASYNCIO_FUTURE_ADD_DONE_CALLBACK_METHODDEF
  2210. _ASYNCIO_FUTURE_REMOVE_DONE_CALLBACK_METHODDEF
  2211. _ASYNCIO_FUTURE_CANCELLED_METHODDEF
  2212. _ASYNCIO_FUTURE_DONE_METHODDEF
  2213. _ASYNCIO_TASK_SET_RESULT_METHODDEF
  2214. _ASYNCIO_TASK_SET_EXCEPTION_METHODDEF
  2215. _ASYNCIO_TASK_CANCEL_METHODDEF
  2216. _ASYNCIO_TASK_CANCELLING_METHODDEF
  2217. _ASYNCIO_TASK_UNCANCEL_METHODDEF
  2218. _ASYNCIO_TASK_GET_STACK_METHODDEF
  2219. _ASYNCIO_TASK_PRINT_STACK_METHODDEF
  2220. _ASYNCIO_TASK__MAKE_CANCELLED_ERROR_METHODDEF
  2221. _ASYNCIO_TASK_GET_NAME_METHODDEF
  2222. _ASYNCIO_TASK_SET_NAME_METHODDEF
  2223. _ASYNCIO_TASK_GET_CORO_METHODDEF
  2224. _ASYNCIO_TASK_GET_CONTEXT_METHODDEF
  2225. {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
  2226. {NULL, NULL} /* Sentinel */
  2227. };
  2228. static PyMemberDef TaskType_members[] = {
  2229. {"__weaklistoffset__", T_PYSSIZET, offsetof(TaskObj, task_weakreflist), READONLY},
  2230. {"__dictoffset__", T_PYSSIZET, offsetof(TaskObj, dict), READONLY},
  2231. {NULL},
  2232. };
  2233. static PyGetSetDef TaskType_getsetlist[] = {
  2234. FUTURE_COMMON_GETSETLIST
  2235. {"_log_destroy_pending", (getter)TaskObj_get_log_destroy_pending,
  2236. (setter)TaskObj_set_log_destroy_pending, NULL},
  2237. {"_must_cancel", (getter)TaskObj_get_must_cancel, NULL, NULL},
  2238. {"_coro", (getter)TaskObj_get_coro, NULL, NULL},
  2239. {"_fut_waiter", (getter)TaskObj_get_fut_waiter, NULL, NULL},
  2240. {NULL} /* Sentinel */
  2241. };
  2242. static PyType_Slot Task_slots[] = {
  2243. {Py_tp_dealloc, TaskObj_dealloc},
  2244. {Py_tp_repr, (reprfunc)TaskObj_repr},
  2245. {Py_tp_doc, (void *)_asyncio_Task___init____doc__},
  2246. {Py_tp_traverse, (traverseproc)TaskObj_traverse},
  2247. {Py_tp_clear, (inquiry)TaskObj_clear},
  2248. {Py_tp_iter, (getiterfunc)future_new_iter},
  2249. {Py_tp_methods, TaskType_methods},
  2250. {Py_tp_members, TaskType_members},
  2251. {Py_tp_getset, TaskType_getsetlist},
  2252. {Py_tp_init, (initproc)_asyncio_Task___init__},
  2253. {Py_tp_new, PyType_GenericNew},
  2254. {Py_tp_finalize, (destructor)TaskObj_finalize},
  2255. // async slots
  2256. {Py_am_await, (unaryfunc)future_new_iter},
  2257. {0, NULL},
  2258. };
  2259. static PyType_Spec Task_spec = {
  2260. .name = "_asyncio.Task",
  2261. .basicsize = sizeof(TaskObj),
  2262. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE |
  2263. Py_TPFLAGS_IMMUTABLETYPE),
  2264. .slots = Task_slots,
  2265. };
  2266. static void
  2267. TaskObj_dealloc(PyObject *self)
  2268. {
  2269. TaskObj *task = (TaskObj *)self;
  2270. if (PyObject_CallFinalizerFromDealloc(self) < 0) {
  2271. // resurrected.
  2272. return;
  2273. }
  2274. PyTypeObject *tp = Py_TYPE(task);
  2275. PyObject_GC_UnTrack(self);
  2276. if (task->task_weakreflist != NULL) {
  2277. PyObject_ClearWeakRefs(self);
  2278. }
  2279. (void)TaskObj_clear(task);
  2280. tp->tp_free(task);
  2281. Py_DECREF(tp);
  2282. }
  2283. static int
  2284. task_call_step_soon(asyncio_state *state, TaskObj *task, PyObject *arg)
  2285. {
  2286. PyObject *cb = TaskStepMethWrapper_new(task, arg);
  2287. if (cb == NULL) {
  2288. return -1;
  2289. }
  2290. int ret = call_soon(state, task->task_loop, cb, NULL, task->task_context);
  2291. Py_DECREF(cb);
  2292. return ret;
  2293. }
  2294. static PyObject *
  2295. task_set_error_soon(asyncio_state *state, TaskObj *task, PyObject *et,
  2296. const char *format, ...)
  2297. {
  2298. PyObject* msg;
  2299. va_list vargs;
  2300. va_start(vargs, format);
  2301. msg = PyUnicode_FromFormatV(format, vargs);
  2302. va_end(vargs);
  2303. if (msg == NULL) {
  2304. return NULL;
  2305. }
  2306. PyObject *e = PyObject_CallOneArg(et, msg);
  2307. Py_DECREF(msg);
  2308. if (e == NULL) {
  2309. return NULL;
  2310. }
  2311. if (task_call_step_soon(state, task, e) == -1) {
  2312. Py_DECREF(e);
  2313. return NULL;
  2314. }
  2315. Py_DECREF(e);
  2316. Py_RETURN_NONE;
  2317. }
  2318. static inline int
  2319. gen_status_from_result(PyObject **result)
  2320. {
  2321. if (*result != NULL) {
  2322. return PYGEN_NEXT;
  2323. }
  2324. if (_PyGen_FetchStopIterationValue(result) == 0) {
  2325. return PYGEN_RETURN;
  2326. }
  2327. assert(PyErr_Occurred());
  2328. return PYGEN_ERROR;
  2329. }
  2330. static PyObject *
  2331. task_step_impl(asyncio_state *state, TaskObj *task, PyObject *exc)
  2332. {
  2333. int res;
  2334. int clear_exc = 0;
  2335. PyObject *result = NULL;
  2336. PyObject *coro;
  2337. PyObject *o;
  2338. if (task->task_state != STATE_PENDING) {
  2339. PyErr_Format(state->asyncio_InvalidStateError,
  2340. "_step(): already done: %R %R",
  2341. task,
  2342. exc ? exc : Py_None);
  2343. goto fail;
  2344. }
  2345. if (task->task_must_cancel) {
  2346. assert(exc != Py_None);
  2347. if (exc) {
  2348. /* Check if exc is a CancelledError */
  2349. res = PyObject_IsInstance(exc, state->asyncio_CancelledError);
  2350. if (res == -1) {
  2351. /* An error occurred, abort */
  2352. goto fail;
  2353. }
  2354. if (res == 0) {
  2355. /* exc is not CancelledError; reset it to NULL */
  2356. exc = NULL;
  2357. }
  2358. }
  2359. if (!exc) {
  2360. /* exc was not a CancelledError */
  2361. exc = create_cancelled_error(state, (FutureObj*)task);
  2362. if (!exc) {
  2363. goto fail;
  2364. }
  2365. clear_exc = 1;
  2366. }
  2367. task->task_must_cancel = 0;
  2368. }
  2369. Py_CLEAR(task->task_fut_waiter);
  2370. coro = task->task_coro;
  2371. if (coro == NULL) {
  2372. PyErr_SetString(PyExc_RuntimeError, "uninitialized Task object");
  2373. if (clear_exc) {
  2374. /* We created 'exc' during this call */
  2375. Py_DECREF(exc);
  2376. }
  2377. return NULL;
  2378. }
  2379. int gen_status = PYGEN_ERROR;
  2380. if (exc == NULL) {
  2381. gen_status = PyIter_Send(coro, Py_None, &result);
  2382. }
  2383. else {
  2384. result = PyObject_CallMethodOneArg(coro, &_Py_ID(throw), exc);
  2385. gen_status = gen_status_from_result(&result);
  2386. if (clear_exc) {
  2387. /* We created 'exc' during this call */
  2388. Py_DECREF(exc);
  2389. }
  2390. }
  2391. if (gen_status == PYGEN_RETURN || gen_status == PYGEN_ERROR) {
  2392. if (result != NULL) {
  2393. /* The error is StopIteration and that means that
  2394. the underlying coroutine has resolved */
  2395. PyObject *tmp;
  2396. if (task->task_must_cancel) {
  2397. // Task is cancelled right before coro stops.
  2398. task->task_must_cancel = 0;
  2399. tmp = future_cancel(state, (FutureObj*)task,
  2400. task->task_cancel_msg);
  2401. }
  2402. else {
  2403. tmp = future_set_result(state, (FutureObj*)task, result);
  2404. }
  2405. Py_DECREF(result);
  2406. if (tmp == NULL) {
  2407. return NULL;
  2408. }
  2409. Py_DECREF(tmp);
  2410. Py_RETURN_NONE;
  2411. }
  2412. if (PyErr_ExceptionMatches(state->asyncio_CancelledError)) {
  2413. /* CancelledError */
  2414. PyObject *exc = PyErr_GetRaisedException();
  2415. assert(exc);
  2416. FutureObj *fut = (FutureObj*)task;
  2417. /* transfer ownership */
  2418. fut->fut_cancelled_exc = exc;
  2419. return future_cancel(state, fut, NULL);
  2420. }
  2421. /* Some other exception; pop it and call Task.set_exception() */
  2422. PyObject *exc = PyErr_GetRaisedException();
  2423. assert(exc);
  2424. o = future_set_exception(state, (FutureObj*)task, exc);
  2425. if (!o) {
  2426. /* An exception in Task.set_exception() */
  2427. Py_DECREF(exc);
  2428. goto fail;
  2429. }
  2430. assert(o == Py_None);
  2431. Py_DECREF(o);
  2432. if (PyErr_GivenExceptionMatches(exc, PyExc_KeyboardInterrupt) ||
  2433. PyErr_GivenExceptionMatches(exc, PyExc_SystemExit))
  2434. {
  2435. /* We've got a KeyboardInterrupt or a SystemError; re-raise it */
  2436. PyErr_SetRaisedException(exc);
  2437. goto fail;
  2438. }
  2439. Py_DECREF(exc);
  2440. Py_RETURN_NONE;
  2441. }
  2442. PyObject *ret = task_step_handle_result_impl(state, task, result);
  2443. return ret;
  2444. fail:
  2445. return NULL;
  2446. }
  2447. static PyObject *
  2448. task_step_handle_result_impl(asyncio_state *state, TaskObj *task, PyObject *result)
  2449. {
  2450. int res;
  2451. PyObject *o;
  2452. if (result == (PyObject*)task) {
  2453. /* We have a task that wants to await on itself */
  2454. goto self_await;
  2455. }
  2456. /* Check if `result` is FutureObj or TaskObj (and not a subclass) */
  2457. if (Future_CheckExact(state, result) || Task_CheckExact(state, result)) {
  2458. PyObject *wrapper;
  2459. PyObject *tmp;
  2460. FutureObj *fut = (FutureObj*)result;
  2461. /* Check if `result` future is attached to a different loop */
  2462. if (fut->fut_loop != task->task_loop) {
  2463. goto different_loop;
  2464. }
  2465. if (!fut->fut_blocking) {
  2466. goto yield_insteadof_yf;
  2467. }
  2468. fut->fut_blocking = 0;
  2469. /* result.add_done_callback(task._wakeup) */
  2470. wrapper = PyCFunction_New(&TaskWakeupDef, (PyObject *)task);
  2471. if (wrapper == NULL) {
  2472. goto fail;
  2473. }
  2474. tmp = future_add_done_callback(state,
  2475. (FutureObj*)result, wrapper, task->task_context);
  2476. Py_DECREF(wrapper);
  2477. if (tmp == NULL) {
  2478. goto fail;
  2479. }
  2480. Py_DECREF(tmp);
  2481. /* task._fut_waiter = result */
  2482. task->task_fut_waiter = result; /* no incref is necessary */
  2483. if (task->task_must_cancel) {
  2484. PyObject *r;
  2485. int is_true;
  2486. r = PyObject_CallMethodOneArg(result, &_Py_ID(cancel),
  2487. task->task_cancel_msg);
  2488. if (r == NULL) {
  2489. return NULL;
  2490. }
  2491. is_true = PyObject_IsTrue(r);
  2492. Py_DECREF(r);
  2493. if (is_true < 0) {
  2494. return NULL;
  2495. }
  2496. else if (is_true) {
  2497. task->task_must_cancel = 0;
  2498. }
  2499. }
  2500. Py_RETURN_NONE;
  2501. }
  2502. /* Check if `result` is None */
  2503. if (result == Py_None) {
  2504. /* Bare yield relinquishes control for one event loop iteration. */
  2505. if (task_call_step_soon(state, task, NULL)) {
  2506. goto fail;
  2507. }
  2508. return result;
  2509. }
  2510. /* Check if `result` is a Future-compatible object */
  2511. if (_PyObject_LookupAttr(result, &_Py_ID(_asyncio_future_blocking), &o) < 0) {
  2512. goto fail;
  2513. }
  2514. if (o != NULL && o != Py_None) {
  2515. /* `result` is a Future-compatible object */
  2516. PyObject *wrapper;
  2517. PyObject *tmp;
  2518. int blocking = PyObject_IsTrue(o);
  2519. Py_DECREF(o);
  2520. if (blocking < 0) {
  2521. goto fail;
  2522. }
  2523. /* Check if `result` future is attached to a different loop */
  2524. PyObject *oloop = get_future_loop(state, result);
  2525. if (oloop == NULL) {
  2526. goto fail;
  2527. }
  2528. if (oloop != task->task_loop) {
  2529. Py_DECREF(oloop);
  2530. goto different_loop;
  2531. }
  2532. Py_DECREF(oloop);
  2533. if (!blocking) {
  2534. goto yield_insteadof_yf;
  2535. }
  2536. /* result._asyncio_future_blocking = False */
  2537. if (PyObject_SetAttr(
  2538. result, &_Py_ID(_asyncio_future_blocking), Py_False) == -1) {
  2539. goto fail;
  2540. }
  2541. wrapper = PyCFunction_New(&TaskWakeupDef, (PyObject *)task);
  2542. if (wrapper == NULL) {
  2543. goto fail;
  2544. }
  2545. /* result.add_done_callback(task._wakeup) */
  2546. PyObject *add_cb = PyObject_GetAttr(
  2547. result, &_Py_ID(add_done_callback));
  2548. if (add_cb == NULL) {
  2549. Py_DECREF(wrapper);
  2550. goto fail;
  2551. }
  2552. PyObject *stack[2];
  2553. stack[0] = wrapper;
  2554. stack[1] = (PyObject *)task->task_context;
  2555. EVAL_CALL_STAT_INC_IF_FUNCTION(EVAL_CALL_API, add_cb);
  2556. tmp = PyObject_Vectorcall(add_cb, stack, 1, state->context_kwname);
  2557. Py_DECREF(add_cb);
  2558. Py_DECREF(wrapper);
  2559. if (tmp == NULL) {
  2560. goto fail;
  2561. }
  2562. Py_DECREF(tmp);
  2563. /* task._fut_waiter = result */
  2564. task->task_fut_waiter = result; /* no incref is necessary */
  2565. if (task->task_must_cancel) {
  2566. PyObject *r;
  2567. int is_true;
  2568. r = PyObject_CallMethodOneArg(result, &_Py_ID(cancel),
  2569. task->task_cancel_msg);
  2570. if (r == NULL) {
  2571. return NULL;
  2572. }
  2573. is_true = PyObject_IsTrue(r);
  2574. Py_DECREF(r);
  2575. if (is_true < 0) {
  2576. return NULL;
  2577. }
  2578. else if (is_true) {
  2579. task->task_must_cancel = 0;
  2580. }
  2581. }
  2582. Py_RETURN_NONE;
  2583. }
  2584. Py_XDECREF(o);
  2585. /* Check if `result` is a generator */
  2586. res = PyObject_IsInstance(result, (PyObject*)&PyGen_Type);
  2587. if (res < 0) {
  2588. goto fail;
  2589. }
  2590. if (res) {
  2591. /* `result` is a generator */
  2592. o = task_set_error_soon(
  2593. state, task, PyExc_RuntimeError,
  2594. "yield was used instead of yield from for "
  2595. "generator in task %R with %R", task, result);
  2596. Py_DECREF(result);
  2597. return o;
  2598. }
  2599. /* The `result` is none of the above */
  2600. o = task_set_error_soon(
  2601. state, task, PyExc_RuntimeError, "Task got bad yield: %R", result);
  2602. Py_DECREF(result);
  2603. return o;
  2604. self_await:
  2605. o = task_set_error_soon(
  2606. state, task, PyExc_RuntimeError,
  2607. "Task cannot await on itself: %R", task);
  2608. Py_DECREF(result);
  2609. return o;
  2610. yield_insteadof_yf:
  2611. o = task_set_error_soon(
  2612. state, task, PyExc_RuntimeError,
  2613. "yield was used instead of yield from "
  2614. "in task %R with %R",
  2615. task, result);
  2616. Py_DECREF(result);
  2617. return o;
  2618. different_loop:
  2619. o = task_set_error_soon(
  2620. state, task, PyExc_RuntimeError,
  2621. "Task %R got Future %R attached to a different loop",
  2622. task, result);
  2623. Py_DECREF(result);
  2624. return o;
  2625. fail:
  2626. Py_XDECREF(result);
  2627. return NULL;
  2628. }
  2629. static PyObject *
  2630. task_step(asyncio_state *state, TaskObj *task, PyObject *exc)
  2631. {
  2632. PyObject *res;
  2633. if (enter_task(state, task->task_loop, (PyObject*)task) < 0) {
  2634. return NULL;
  2635. }
  2636. res = task_step_impl(state, task, exc);
  2637. if (res == NULL) {
  2638. PyObject *exc = PyErr_GetRaisedException();
  2639. leave_task(state, task->task_loop, (PyObject*)task);
  2640. _PyErr_ChainExceptions1(exc);
  2641. return NULL;
  2642. }
  2643. else {
  2644. if (leave_task(state, task->task_loop, (PyObject*)task) < 0) {
  2645. Py_DECREF(res);
  2646. return NULL;
  2647. }
  2648. else {
  2649. return res;
  2650. }
  2651. }
  2652. }
  2653. static int
  2654. task_eager_start(asyncio_state *state, TaskObj *task)
  2655. {
  2656. assert(task != NULL);
  2657. PyObject *prevtask = swap_current_task(state, task->task_loop, (PyObject *)task);
  2658. if (prevtask == NULL) {
  2659. return -1;
  2660. }
  2661. if (register_eager_task(state, (PyObject *)task) == -1) {
  2662. Py_DECREF(prevtask);
  2663. return -1;
  2664. }
  2665. if (PyContext_Enter(task->task_context) == -1) {
  2666. Py_DECREF(prevtask);
  2667. return -1;
  2668. }
  2669. int retval = 0;
  2670. PyObject *stepres = task_step_impl(state, task, NULL);
  2671. if (stepres == NULL) {
  2672. PyObject *exc = PyErr_GetRaisedException();
  2673. _PyErr_ChainExceptions1(exc);
  2674. retval = -1;
  2675. } else {
  2676. Py_DECREF(stepres);
  2677. }
  2678. PyObject *curtask = swap_current_task(state, task->task_loop, prevtask);
  2679. Py_DECREF(prevtask);
  2680. if (curtask == NULL) {
  2681. retval = -1;
  2682. } else {
  2683. assert(curtask == (PyObject *)task);
  2684. Py_DECREF(curtask);
  2685. }
  2686. if (unregister_eager_task(state, (PyObject *)task) == -1) {
  2687. retval = -1;
  2688. }
  2689. if (PyContext_Exit(task->task_context) == -1) {
  2690. retval = -1;
  2691. }
  2692. if (task->task_state == STATE_PENDING) {
  2693. if (register_task(state, (PyObject *)task) == -1) {
  2694. retval = -1;
  2695. }
  2696. } else {
  2697. // This seems to really help performance on pyperformance benchmarks
  2698. Py_CLEAR(task->task_coro);
  2699. }
  2700. return retval;
  2701. }
  2702. static PyObject *
  2703. task_wakeup(TaskObj *task, PyObject *o)
  2704. {
  2705. PyObject *result;
  2706. assert(o);
  2707. asyncio_state *state = get_asyncio_state_by_def((PyObject *)task);
  2708. if (Future_CheckExact(state, o) || Task_CheckExact(state, o)) {
  2709. PyObject *fut_result = NULL;
  2710. int res = future_get_result(state, (FutureObj*)o, &fut_result);
  2711. switch(res) {
  2712. case -1:
  2713. assert(fut_result == NULL);
  2714. break; /* exception raised */
  2715. case 0:
  2716. Py_DECREF(fut_result);
  2717. return task_step(state, task, NULL);
  2718. default:
  2719. assert(res == 1);
  2720. result = task_step(state, task, fut_result);
  2721. Py_DECREF(fut_result);
  2722. return result;
  2723. }
  2724. }
  2725. else {
  2726. PyObject *fut_result = PyObject_CallMethod(o, "result", NULL);
  2727. if (fut_result != NULL) {
  2728. Py_DECREF(fut_result);
  2729. return task_step(state, task, NULL);
  2730. }
  2731. /* exception raised */
  2732. }
  2733. PyObject *exc = PyErr_GetRaisedException();
  2734. assert(exc);
  2735. result = task_step(state, task, exc);
  2736. Py_DECREF(exc);
  2737. return result;
  2738. }
  2739. /*********************** Functions **************************/
  2740. /*[clinic input]
  2741. _asyncio._get_running_loop
  2742. Return the running event loop or None.
  2743. This is a low-level function intended to be used by event loops.
  2744. This function is thread-specific.
  2745. [clinic start generated code]*/
  2746. static PyObject *
  2747. _asyncio__get_running_loop_impl(PyObject *module)
  2748. /*[clinic end generated code: output=b4390af721411a0a input=0a21627e25a4bd43]*/
  2749. {
  2750. PyObject *loop;
  2751. asyncio_state *state = get_asyncio_state(module);
  2752. if (get_running_loop(state, &loop)) {
  2753. return NULL;
  2754. }
  2755. if (loop == NULL) {
  2756. /* There's no currently running event loop */
  2757. Py_RETURN_NONE;
  2758. }
  2759. return loop;
  2760. }
  2761. /*[clinic input]
  2762. _asyncio._set_running_loop
  2763. loop: 'O'
  2764. /
  2765. Set the running event loop.
  2766. This is a low-level function intended to be used by event loops.
  2767. This function is thread-specific.
  2768. [clinic start generated code]*/
  2769. static PyObject *
  2770. _asyncio__set_running_loop(PyObject *module, PyObject *loop)
  2771. /*[clinic end generated code: output=ae56bf7a28ca189a input=4c9720233d606604]*/
  2772. {
  2773. asyncio_state *state = get_asyncio_state(module);
  2774. if (set_running_loop(state, loop)) {
  2775. return NULL;
  2776. }
  2777. Py_RETURN_NONE;
  2778. }
  2779. /*[clinic input]
  2780. _asyncio.get_event_loop
  2781. Return an asyncio event loop.
  2782. When called from a coroutine or a callback (e.g. scheduled with
  2783. call_soon or similar API), this function will always return the
  2784. running event loop.
  2785. If there is no running event loop set, the function will return
  2786. the result of `get_event_loop_policy().get_event_loop()` call.
  2787. [clinic start generated code]*/
  2788. static PyObject *
  2789. _asyncio_get_event_loop_impl(PyObject *module)
  2790. /*[clinic end generated code: output=2a2d8b2f824c648b input=9364bf2916c8655d]*/
  2791. {
  2792. asyncio_state *state = get_asyncio_state(module);
  2793. return get_event_loop(state);
  2794. }
  2795. /*[clinic input]
  2796. _asyncio.get_running_loop
  2797. Return the running event loop. Raise a RuntimeError if there is none.
  2798. This function is thread-specific.
  2799. [clinic start generated code]*/
  2800. static PyObject *
  2801. _asyncio_get_running_loop_impl(PyObject *module)
  2802. /*[clinic end generated code: output=c247b5f9e529530e input=2a3bf02ba39f173d]*/
  2803. {
  2804. PyObject *loop;
  2805. asyncio_state *state = get_asyncio_state(module);
  2806. if (get_running_loop(state, &loop)) {
  2807. return NULL;
  2808. }
  2809. if (loop == NULL) {
  2810. /* There's no currently running event loop */
  2811. PyErr_SetString(
  2812. PyExc_RuntimeError, "no running event loop");
  2813. }
  2814. return loop;
  2815. }
  2816. /*[clinic input]
  2817. _asyncio._register_task
  2818. task: object
  2819. Register a new task in asyncio as executed by loop.
  2820. Returns None.
  2821. [clinic start generated code]*/
  2822. static PyObject *
  2823. _asyncio__register_task_impl(PyObject *module, PyObject *task)
  2824. /*[clinic end generated code: output=8672dadd69a7d4e2 input=21075aaea14dfbad]*/
  2825. {
  2826. asyncio_state *state = get_asyncio_state(module);
  2827. if (register_task(state, task) < 0) {
  2828. return NULL;
  2829. }
  2830. Py_RETURN_NONE;
  2831. }
  2832. /*[clinic input]
  2833. _asyncio._register_eager_task
  2834. task: object
  2835. Register a new task in asyncio as executed by loop.
  2836. Returns None.
  2837. [clinic start generated code]*/
  2838. static PyObject *
  2839. _asyncio__register_eager_task_impl(PyObject *module, PyObject *task)
  2840. /*[clinic end generated code: output=dfe1d45367c73f1a input=237f684683398c51]*/
  2841. {
  2842. asyncio_state *state = get_asyncio_state(module);
  2843. if (register_eager_task(state, task) < 0) {
  2844. return NULL;
  2845. }
  2846. Py_RETURN_NONE;
  2847. }
  2848. /*[clinic input]
  2849. _asyncio._unregister_task
  2850. task: object
  2851. Unregister a task.
  2852. Returns None.
  2853. [clinic start generated code]*/
  2854. static PyObject *
  2855. _asyncio__unregister_task_impl(PyObject *module, PyObject *task)
  2856. /*[clinic end generated code: output=6e5585706d568a46 input=28fb98c3975f7bdc]*/
  2857. {
  2858. asyncio_state *state = get_asyncio_state(module);
  2859. if (unregister_task(state, task) < 0) {
  2860. return NULL;
  2861. }
  2862. Py_RETURN_NONE;
  2863. }
  2864. /*[clinic input]
  2865. _asyncio._unregister_eager_task
  2866. task: object
  2867. Unregister a task.
  2868. Returns None.
  2869. [clinic start generated code]*/
  2870. static PyObject *
  2871. _asyncio__unregister_eager_task_impl(PyObject *module, PyObject *task)
  2872. /*[clinic end generated code: output=a426922bd07f23d1 input=9d07401ef14ee048]*/
  2873. {
  2874. asyncio_state *state = get_asyncio_state(module);
  2875. if (unregister_eager_task(state, task) < 0) {
  2876. return NULL;
  2877. }
  2878. Py_RETURN_NONE;
  2879. }
  2880. /*[clinic input]
  2881. _asyncio._enter_task
  2882. loop: object
  2883. task: object
  2884. Enter into task execution or resume suspended task.
  2885. Task belongs to loop.
  2886. Returns None.
  2887. [clinic start generated code]*/
  2888. static PyObject *
  2889. _asyncio__enter_task_impl(PyObject *module, PyObject *loop, PyObject *task)
  2890. /*[clinic end generated code: output=a22611c858035b73 input=de1b06dca70d8737]*/
  2891. {
  2892. asyncio_state *state = get_asyncio_state(module);
  2893. if (enter_task(state, loop, task) < 0) {
  2894. return NULL;
  2895. }
  2896. Py_RETURN_NONE;
  2897. }
  2898. /*[clinic input]
  2899. _asyncio._leave_task
  2900. loop: object
  2901. task: object
  2902. Leave task execution or suspend a task.
  2903. Task belongs to loop.
  2904. Returns None.
  2905. [clinic start generated code]*/
  2906. static PyObject *
  2907. _asyncio__leave_task_impl(PyObject *module, PyObject *loop, PyObject *task)
  2908. /*[clinic end generated code: output=0ebf6db4b858fb41 input=51296a46313d1ad8]*/
  2909. {
  2910. asyncio_state *state = get_asyncio_state(module);
  2911. if (leave_task(state, loop, task) < 0) {
  2912. return NULL;
  2913. }
  2914. Py_RETURN_NONE;
  2915. }
  2916. /*[clinic input]
  2917. _asyncio._swap_current_task
  2918. loop: object
  2919. task: object
  2920. Temporarily swap in the supplied task and return the original one (or None).
  2921. This is intended for use during eager coroutine execution.
  2922. [clinic start generated code]*/
  2923. static PyObject *
  2924. _asyncio__swap_current_task_impl(PyObject *module, PyObject *loop,
  2925. PyObject *task)
  2926. /*[clinic end generated code: output=9f88de958df74c7e input=c9c72208d3d38b6c]*/
  2927. {
  2928. return swap_current_task(get_asyncio_state(module), loop, task);
  2929. }
  2930. /*[clinic input]
  2931. _asyncio.current_task
  2932. loop: object = None
  2933. Return a currently executed task.
  2934. [clinic start generated code]*/
  2935. static PyObject *
  2936. _asyncio_current_task_impl(PyObject *module, PyObject *loop)
  2937. /*[clinic end generated code: output=fe15ac331a7f981a input=58910f61a5627112]*/
  2938. {
  2939. PyObject *ret;
  2940. asyncio_state *state = get_asyncio_state(module);
  2941. if (loop == Py_None) {
  2942. loop = _asyncio_get_running_loop_impl(module);
  2943. if (loop == NULL) {
  2944. return NULL;
  2945. }
  2946. } else {
  2947. Py_INCREF(loop);
  2948. }
  2949. ret = PyDict_GetItemWithError(state->current_tasks, loop);
  2950. Py_DECREF(loop);
  2951. if (ret == NULL && PyErr_Occurred()) {
  2952. return NULL;
  2953. }
  2954. else if (ret == NULL) {
  2955. Py_RETURN_NONE;
  2956. }
  2957. Py_INCREF(ret);
  2958. return ret;
  2959. }
  2960. /*********************** Module **************************/
  2961. static void
  2962. module_free_freelists(asyncio_state *state)
  2963. {
  2964. PyObject *next;
  2965. PyObject *current;
  2966. next = (PyObject*) state->fi_freelist;
  2967. while (next != NULL) {
  2968. assert(state->fi_freelist_len > 0);
  2969. state->fi_freelist_len--;
  2970. current = next;
  2971. next = (PyObject*) ((futureiterobject*) current)->future;
  2972. PyObject_GC_Del(current);
  2973. }
  2974. assert(state->fi_freelist_len == 0);
  2975. state->fi_freelist = NULL;
  2976. }
  2977. static int
  2978. module_traverse(PyObject *mod, visitproc visit, void *arg)
  2979. {
  2980. asyncio_state *state = get_asyncio_state(mod);
  2981. Py_VISIT(state->FutureIterType);
  2982. Py_VISIT(state->TaskStepMethWrapper_Type);
  2983. Py_VISIT(state->FutureType);
  2984. Py_VISIT(state->TaskType);
  2985. Py_VISIT(state->asyncio_mod);
  2986. Py_VISIT(state->traceback_extract_stack);
  2987. Py_VISIT(state->asyncio_future_repr_func);
  2988. Py_VISIT(state->asyncio_get_event_loop_policy);
  2989. Py_VISIT(state->asyncio_iscoroutine_func);
  2990. Py_VISIT(state->asyncio_task_get_stack_func);
  2991. Py_VISIT(state->asyncio_task_print_stack_func);
  2992. Py_VISIT(state->asyncio_task_repr_func);
  2993. Py_VISIT(state->asyncio_InvalidStateError);
  2994. Py_VISIT(state->asyncio_CancelledError);
  2995. Py_VISIT(state->scheduled_tasks);
  2996. Py_VISIT(state->eager_tasks);
  2997. Py_VISIT(state->current_tasks);
  2998. Py_VISIT(state->iscoroutine_typecache);
  2999. Py_VISIT(state->context_kwname);
  3000. // Visit freelist.
  3001. PyObject *next = (PyObject*) state->fi_freelist;
  3002. while (next != NULL) {
  3003. PyObject *current = next;
  3004. Py_VISIT(current);
  3005. next = (PyObject*) ((futureiterobject*) current)->future;
  3006. }
  3007. return 0;
  3008. }
  3009. static int
  3010. module_clear(PyObject *mod)
  3011. {
  3012. asyncio_state *state = get_asyncio_state(mod);
  3013. Py_CLEAR(state->FutureIterType);
  3014. Py_CLEAR(state->TaskStepMethWrapper_Type);
  3015. Py_CLEAR(state->FutureType);
  3016. Py_CLEAR(state->TaskType);
  3017. Py_CLEAR(state->asyncio_mod);
  3018. Py_CLEAR(state->traceback_extract_stack);
  3019. Py_CLEAR(state->asyncio_future_repr_func);
  3020. Py_CLEAR(state->asyncio_get_event_loop_policy);
  3021. Py_CLEAR(state->asyncio_iscoroutine_func);
  3022. Py_CLEAR(state->asyncio_task_get_stack_func);
  3023. Py_CLEAR(state->asyncio_task_print_stack_func);
  3024. Py_CLEAR(state->asyncio_task_repr_func);
  3025. Py_CLEAR(state->asyncio_InvalidStateError);
  3026. Py_CLEAR(state->asyncio_CancelledError);
  3027. Py_CLEAR(state->scheduled_tasks);
  3028. Py_CLEAR(state->eager_tasks);
  3029. Py_CLEAR(state->current_tasks);
  3030. Py_CLEAR(state->iscoroutine_typecache);
  3031. Py_CLEAR(state->context_kwname);
  3032. module_free_freelists(state);
  3033. return 0;
  3034. }
  3035. static void
  3036. module_free(void *mod)
  3037. {
  3038. (void)module_clear((PyObject *)mod);
  3039. }
  3040. static int
  3041. module_init(asyncio_state *state)
  3042. {
  3043. PyObject *module = NULL;
  3044. state->asyncio_mod = PyImport_ImportModule("asyncio");
  3045. if (state->asyncio_mod == NULL) {
  3046. goto fail;
  3047. }
  3048. state->current_tasks = PyDict_New();
  3049. if (state->current_tasks == NULL) {
  3050. goto fail;
  3051. }
  3052. state->iscoroutine_typecache = PySet_New(NULL);
  3053. if (state->iscoroutine_typecache == NULL) {
  3054. goto fail;
  3055. }
  3056. state->context_kwname = Py_BuildValue("(s)", "context");
  3057. if (state->context_kwname == NULL) {
  3058. goto fail;
  3059. }
  3060. #define WITH_MOD(NAME) \
  3061. Py_CLEAR(module); \
  3062. module = PyImport_ImportModule(NAME); \
  3063. if (module == NULL) { \
  3064. goto fail; \
  3065. }
  3066. #define GET_MOD_ATTR(VAR, NAME) \
  3067. VAR = PyObject_GetAttrString(module, NAME); \
  3068. if (VAR == NULL) { \
  3069. goto fail; \
  3070. }
  3071. WITH_MOD("asyncio.events")
  3072. GET_MOD_ATTR(state->asyncio_get_event_loop_policy, "get_event_loop_policy")
  3073. WITH_MOD("asyncio.base_futures")
  3074. GET_MOD_ATTR(state->asyncio_future_repr_func, "_future_repr")
  3075. WITH_MOD("asyncio.exceptions")
  3076. GET_MOD_ATTR(state->asyncio_InvalidStateError, "InvalidStateError")
  3077. GET_MOD_ATTR(state->asyncio_CancelledError, "CancelledError")
  3078. WITH_MOD("asyncio.base_tasks")
  3079. GET_MOD_ATTR(state->asyncio_task_repr_func, "_task_repr")
  3080. GET_MOD_ATTR(state->asyncio_task_get_stack_func, "_task_get_stack")
  3081. GET_MOD_ATTR(state->asyncio_task_print_stack_func, "_task_print_stack")
  3082. WITH_MOD("asyncio.coroutines")
  3083. GET_MOD_ATTR(state->asyncio_iscoroutine_func, "iscoroutine")
  3084. WITH_MOD("traceback")
  3085. GET_MOD_ATTR(state->traceback_extract_stack, "extract_stack")
  3086. PyObject *weak_set;
  3087. WITH_MOD("weakref")
  3088. GET_MOD_ATTR(weak_set, "WeakSet");
  3089. state->scheduled_tasks = PyObject_CallNoArgs(weak_set);
  3090. Py_CLEAR(weak_set);
  3091. if (state->scheduled_tasks == NULL) {
  3092. goto fail;
  3093. }
  3094. state->eager_tasks = PySet_New(NULL);
  3095. if (state->eager_tasks == NULL) {
  3096. goto fail;
  3097. }
  3098. Py_DECREF(module);
  3099. return 0;
  3100. fail:
  3101. Py_CLEAR(module);
  3102. return -1;
  3103. #undef WITH_MOD
  3104. #undef GET_MOD_ATTR
  3105. }
  3106. PyDoc_STRVAR(module_doc, "Accelerator module for asyncio");
  3107. static PyMethodDef asyncio_methods[] = {
  3108. _ASYNCIO_CURRENT_TASK_METHODDEF
  3109. _ASYNCIO_GET_EVENT_LOOP_METHODDEF
  3110. _ASYNCIO_GET_RUNNING_LOOP_METHODDEF
  3111. _ASYNCIO__GET_RUNNING_LOOP_METHODDEF
  3112. _ASYNCIO__SET_RUNNING_LOOP_METHODDEF
  3113. _ASYNCIO__REGISTER_TASK_METHODDEF
  3114. _ASYNCIO__REGISTER_EAGER_TASK_METHODDEF
  3115. _ASYNCIO__UNREGISTER_TASK_METHODDEF
  3116. _ASYNCIO__UNREGISTER_EAGER_TASK_METHODDEF
  3117. _ASYNCIO__ENTER_TASK_METHODDEF
  3118. _ASYNCIO__LEAVE_TASK_METHODDEF
  3119. _ASYNCIO__SWAP_CURRENT_TASK_METHODDEF
  3120. {NULL, NULL}
  3121. };
  3122. static int
  3123. module_exec(PyObject *mod)
  3124. {
  3125. asyncio_state *state = get_asyncio_state(mod);
  3126. #define CREATE_TYPE(m, tp, spec, base) \
  3127. do { \
  3128. tp = (PyTypeObject *)PyType_FromMetaclass(NULL, m, spec, \
  3129. (PyObject *)base); \
  3130. if (tp == NULL) { \
  3131. return -1; \
  3132. } \
  3133. } while (0)
  3134. CREATE_TYPE(mod, state->TaskStepMethWrapper_Type, &TaskStepMethWrapper_spec, NULL);
  3135. CREATE_TYPE(mod, state->FutureIterType, &FutureIter_spec, NULL);
  3136. CREATE_TYPE(mod, state->FutureType, &Future_spec, NULL);
  3137. CREATE_TYPE(mod, state->TaskType, &Task_spec, state->FutureType);
  3138. #undef CREATE_TYPE
  3139. if (PyModule_AddType(mod, state->FutureType) < 0) {
  3140. return -1;
  3141. }
  3142. if (PyModule_AddType(mod, state->TaskType) < 0) {
  3143. return -1;
  3144. }
  3145. // Must be done after types are added to avoid a circular dependency
  3146. if (module_init(state) < 0) {
  3147. return -1;
  3148. }
  3149. if (PyModule_AddObjectRef(mod, "_scheduled_tasks", state->scheduled_tasks) < 0) {
  3150. return -1;
  3151. }
  3152. if (PyModule_AddObjectRef(mod, "_eager_tasks", state->eager_tasks) < 0) {
  3153. return -1;
  3154. }
  3155. if (PyModule_AddObjectRef(mod, "_current_tasks", state->current_tasks) < 0) {
  3156. return -1;
  3157. }
  3158. return 0;
  3159. }
  3160. static struct PyModuleDef_Slot module_slots[] = {
  3161. {Py_mod_exec, module_exec},
  3162. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  3163. {0, NULL},
  3164. };
  3165. static struct PyModuleDef _asynciomodule = {
  3166. .m_base = PyModuleDef_HEAD_INIT,
  3167. .m_name = "_asyncio",
  3168. .m_doc = module_doc,
  3169. .m_size = sizeof(asyncio_state),
  3170. .m_methods = asyncio_methods,
  3171. .m_slots = module_slots,
  3172. .m_traverse = module_traverse,
  3173. .m_clear = module_clear,
  3174. .m_free = (freefunc)module_free,
  3175. };
  3176. PyMODINIT_FUNC
  3177. PyInit__asyncio(void)
  3178. {
  3179. return PyModuleDef_Init(&_asynciomodule);
  3180. }