swd_probe_app.c 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745
  1. #include <furi.h>
  2. #include <gui/gui.h>
  3. #include <gui/elements.h>
  4. #include <dialogs/dialogs.h>
  5. #include <input/input.h>
  6. #include <storage/storage.h>
  7. #include <stdlib.h>
  8. #include <dolphin/dolphin.h>
  9. #include <notification/notification.h>
  10. #include <notification/notification_messages.h>
  11. #include <math.h>
  12. #include "swd_probe_app.h"
  13. #include "swd_probe_icons.h"
  14. #include "jep106.h"
  15. /* short debug message */
  16. #define DBGS(format) furi_log_print_format(FuriLogLevelDebug, TAG, "%s: " format, __FUNCTION__)
  17. /* formatted debug message */
  18. #define DBG(format, ...) \
  19. furi_log_print_format(FuriLogLevelDebug, TAG, "%s: " format, __FUNCTION__, __VA_ARGS__)
  20. /* log message*/
  21. #define LOG(...) furi_log_print_format(FuriLogLevelDefault, TAG, __VA_ARGS__)
  22. #define COUNT(x) ((size_t)(sizeof(x) / sizeof((x)[0])))
  23. static void render_callback(Canvas* const canvas, void* cb_ctx);
  24. static bool swd_message_process(AppFSM* ctx);
  25. static uint8_t swd_transfer(AppFSM* const ctx, bool ap, bool write, uint8_t a23, uint32_t* data);
  26. static bool swd_execute_script(AppFSM* const ctx, const char* filename);
  27. static const GpioPin* gpios[] = {
  28. &gpio_ext_pc0,
  29. &gpio_ext_pc1,
  30. &gpio_ext_pc3,
  31. &gpio_ext_pb2,
  32. &gpio_ext_pb3,
  33. &gpio_ext_pa4,
  34. &gpio_ext_pa6,
  35. &gpio_ext_pa7};
  36. static const char* gpio_names[] = {"PC0", "PC1", "PC3", "PB2", "PB3", "PA4", "PA6", "PA7"};
  37. /* bit set: clock, else data */
  38. static const uint8_t gpio_direction_mask[6] =
  39. {0b10101010, 0b01010101, 0b11001100, 0b00110011, 0b11110000, 0b00001111};
  40. static bool has_multiple_bits(uint8_t x) {
  41. return (x & (x - 1)) != 0;
  42. }
  43. static uint8_t get_bit_num(uint8_t x) {
  44. return (uint8_t)__builtin_ctz(x);
  45. }
  46. static const char* gpio_name(uint8_t mask) {
  47. if(has_multiple_bits(mask)) {
  48. return "Pxx";
  49. }
  50. uint8_t io = get_bit_num(mask);
  51. if(io >= COUNT(gpio_names)) {
  52. return "Pxx";
  53. }
  54. return gpio_names[io];
  55. }
  56. static void swd_configure_pins(AppFSM* const ctx, bool output) {
  57. if(ctx->mode_page > ModePageFound && ctx->io_num_swc < 8 && ctx->io_num_swd < 8) {
  58. furi_hal_gpio_init(
  59. gpios[ctx->io_num_swc], GpioModeOutputPushPull, GpioPullNo, GpioSpeedVeryHigh);
  60. if(!output) {
  61. furi_hal_gpio_init(
  62. gpios[ctx->io_num_swd], GpioModeInput, GpioPullUp, GpioSpeedVeryHigh);
  63. } else {
  64. furi_hal_gpio_init(
  65. gpios[ctx->io_num_swd], GpioModeOutputOpenDrain, GpioPullUp, GpioSpeedVeryHigh);
  66. }
  67. return;
  68. }
  69. for(int io = 0; io < 8; io++) {
  70. uint8_t bitmask = 1 << io;
  71. /* if neither candidate for SWC nor SWD then skip */
  72. if(!(ctx->io_swc & bitmask) && !(ctx->io_swd & bitmask)) {
  73. furi_hal_gpio_init(gpios[io], GpioModeInput, GpioPullUp, GpioSpeedVeryHigh);
  74. continue;
  75. }
  76. if(ctx->current_mask & bitmask) {
  77. /* set for clock */
  78. furi_hal_gpio_init(gpios[io], GpioModeOutputPushPull, GpioPullNo, GpioSpeedVeryHigh);
  79. } else {
  80. /* set for data */
  81. if(!output) {
  82. furi_hal_gpio_init(gpios[io], GpioModeInput, GpioPullUp, GpioSpeedVeryHigh);
  83. } else {
  84. furi_hal_gpio_init(
  85. gpios[io], GpioModeOutputOpenDrain, GpioPullUp, GpioSpeedVeryHigh);
  86. }
  87. }
  88. }
  89. }
  90. static void swd_set_clock(AppFSM* const ctx, const uint8_t level) {
  91. if(ctx->mode_page > ModePageFound && ctx->io_num_swc < 8) {
  92. furi_hal_gpio_write(gpios[ctx->io_num_swc], level);
  93. return;
  94. }
  95. for(int io = 0; io < 8; io++) {
  96. uint8_t bitmask = 1 << io;
  97. /* if no candidate for SWC then skip */
  98. if(!(ctx->io_swc & bitmask)) {
  99. continue;
  100. }
  101. if(ctx->current_mask & bitmask) {
  102. furi_hal_gpio_write(gpios[io], level);
  103. }
  104. }
  105. }
  106. static void swd_set_data(AppFSM* const ctx, const uint8_t level) {
  107. if(ctx->mode_page > ModePageFound && ctx->io_num_swd < 8) {
  108. furi_hal_gpio_write(gpios[ctx->io_num_swd], level);
  109. return;
  110. }
  111. for(int io = 0; io < 8; io++) {
  112. uint8_t bitmask = 1 << io;
  113. /* if no candidate for SWD then skip */
  114. if(!(ctx->io_swd & bitmask)) {
  115. continue;
  116. }
  117. if(!(ctx->current_mask & bitmask)) {
  118. furi_hal_gpio_write(gpios[io], level);
  119. }
  120. }
  121. }
  122. static uint8_t swd_get_data(AppFSM* const ctx) {
  123. if(ctx->mode_page > ModePageFound && ctx->io_num_swd < 8) {
  124. return furi_hal_gpio_read(gpios[ctx->io_num_swd]);
  125. }
  126. uint8_t bits = 0;
  127. for(int io = 0; io < 8; io++) {
  128. uint8_t bitmask = 1 << io;
  129. /* if no candidate for SWD then skip */
  130. if(!(ctx->io_swd & bitmask)) {
  131. continue;
  132. }
  133. bits |= furi_hal_gpio_read(gpios[io]) ? bitmask : 0;
  134. }
  135. return bits;
  136. }
  137. static void swd_clock_delay(AppFSM* const ctx) {
  138. if(ctx->swd_clock_delay) {
  139. furi_delay_us(ctx->swd_clock_delay);
  140. }
  141. }
  142. static void swd_write_bit(AppFSM* const ctx, bool level) {
  143. swd_set_clock(ctx, 0);
  144. swd_set_data(ctx, level);
  145. swd_clock_delay(ctx);
  146. swd_set_clock(ctx, 1);
  147. swd_clock_delay(ctx);
  148. swd_set_clock(ctx, 0);
  149. }
  150. static uint8_t swd_read_bit(AppFSM* const ctx) {
  151. swd_set_clock(ctx, 1);
  152. swd_clock_delay(ctx);
  153. swd_set_clock(ctx, 0);
  154. uint8_t bits = swd_get_data(ctx);
  155. swd_clock_delay(ctx);
  156. swd_set_clock(ctx, 1);
  157. return bits;
  158. }
  159. /* send a byte or less LSB-first */
  160. static void swd_write_byte(AppFSM* const ctx, const uint8_t data, size_t bits) {
  161. for(size_t pos = 0; pos < bits; pos++) {
  162. swd_write_bit(ctx, data & (1 << pos));
  163. }
  164. }
  165. /* send a sequence of bytes LSB-first */
  166. static void swd_write(AppFSM* const ctx, const uint8_t* data, size_t bits) {
  167. size_t byte_pos = 0;
  168. while(bits > 0) {
  169. size_t remain = (bits > 8) ? 8 : bits;
  170. swd_write_byte(ctx, data[byte_pos++], remain);
  171. bits -= remain;
  172. }
  173. }
  174. static uint8_t swd_transfer(AppFSM* const ctx, bool ap, bool write, uint8_t a23, uint32_t* data) {
  175. notification_message(ctx->notification, &sequence_set_red_255);
  176. swd_set_data(ctx, false);
  177. swd_configure_pins(ctx, true);
  178. uint32_t idle = 0;
  179. swd_write(ctx, (uint8_t*)&idle, ctx->swd_idle_bits);
  180. uint8_t request[] = {0};
  181. request[0] |= 0x01; /* start bit*/
  182. request[0] |= ap ? 0x02 : 0; /* APnDP */
  183. request[0] |= write ? 0 : 0x04; /* operation */
  184. request[0] |= (a23 & 0x01) ? 0x08 : 0; /* A[2:3] */
  185. request[0] |= (a23 & 0x02) ? 0x10 : 0; /* A[2:3] */
  186. request[0] |= 0x80; /* park bit */
  187. request[0] |= __builtin_parity(request[0]) ? 0x20 : 0; /* parity */
  188. swd_write(ctx, request, sizeof(request) * 8);
  189. /* turnaround cycle */
  190. swd_configure_pins(ctx, false);
  191. uint8_t ack = 0;
  192. /* receive 3 ACK bits */
  193. for(int pos = 0; pos < 3; pos++) {
  194. ack >>= 1;
  195. ack |= swd_read_bit(ctx) ? 0x04 : 0;
  196. }
  197. /* force ABORT/CTRL to always work */
  198. if(!ap && a23 == 0) {
  199. ack = 1;
  200. }
  201. if(ack != 0x01) {
  202. notification_message(ctx->notification, &sequence_reset_red);
  203. return ack;
  204. }
  205. if(write) {
  206. swd_write_bit(ctx, 0);
  207. swd_configure_pins(ctx, true);
  208. /* send 32 WDATA bits */
  209. for(int pos = 0; pos < 32; pos++) {
  210. swd_write_bit(ctx, *data & (1 << pos));
  211. }
  212. /* send parity bit */
  213. swd_write_bit(ctx, __builtin_parity(*data));
  214. } else {
  215. *data = 0;
  216. /* receive 32 RDATA bits */
  217. for(int pos = 0; pos < 32; pos++) {
  218. *data >>= 1;
  219. *data |= swd_read_bit(ctx) ? 0x80000000 : 0;
  220. }
  221. /* receive parity bit */
  222. bool parity = swd_read_bit(ctx);
  223. if(parity != __builtin_parity(*data)) {
  224. notification_message(ctx->notification, &sequence_reset_red);
  225. return 8;
  226. }
  227. }
  228. swd_set_data(ctx, false);
  229. swd_configure_pins(ctx, true);
  230. notification_message(ctx->notification, &sequence_reset_red);
  231. return ack;
  232. }
  233. /* A line reset is achieved by holding the data signal HIGH for at least 50 clock cycles, followed by at least two idle cycles. */
  234. static void swd_line_reset(AppFSM* const ctx) {
  235. notification_message(ctx->notification, &sequence_set_red_255);
  236. for(int bitcount = 0; bitcount < 50; bitcount += 8) {
  237. swd_write_byte(ctx, 0xFF, 8);
  238. }
  239. swd_write_byte(ctx, 0, 8);
  240. ctx->dp_regs.select_ok = false;
  241. notification_message(ctx->notification, &sequence_reset_red);
  242. }
  243. static void swd_abort(AppFSM* const ctx) {
  244. uint32_t dpidr;
  245. /* first reset the line */
  246. swd_line_reset(ctx);
  247. swd_transfer(ctx, false, false, 0, &dpidr);
  248. uint32_t abort = 0x0E;
  249. swd_transfer(ctx, false, true, 0, &abort);
  250. }
  251. static void swd_abort_simple(AppFSM* const ctx) {
  252. uint32_t abort = 0x0E;
  253. swd_transfer(ctx, false, true, 0, &abort);
  254. uint32_t dpidr;
  255. if(swd_transfer(ctx, false, false, 0, &dpidr) != 1) {
  256. swd_abort(ctx);
  257. }
  258. }
  259. static uint8_t swd_select(AppFSM* const ctx, uint8_t ap_sel, uint8_t ap_bank, uint8_t dp_bank) {
  260. uint32_t bank_reg = (ap_sel << 24) | ((ap_bank & 0x0F) << 4) | (dp_bank & 0x0F);
  261. if(ctx->dp_regs.select_ok && bank_reg == ctx->dp_regs.select) {
  262. return 1;
  263. }
  264. uint8_t ret = swd_transfer(ctx, false, true, REG_SELECT, &bank_reg);
  265. if(ret != 1) {
  266. ctx->dp_regs.select_ok = false;
  267. DBG("failed: %d", ret);
  268. return ret;
  269. }
  270. ctx->dp_regs.select = bank_reg;
  271. ctx->dp_regs.select_ok = true;
  272. return ret;
  273. }
  274. static uint8_t
  275. swd_read_dpbank(AppFSM* const ctx, uint8_t dp_off, uint8_t dp_bank, uint32_t* data) {
  276. uint8_t ret = 0;
  277. /* select target bank */
  278. if(dp_bank < 0x10) {
  279. uint8_t ret = swd_select(ctx, 0, 0, dp_bank);
  280. if(ret != 1) {
  281. DBGS("swd_select failed");
  282. return ret;
  283. }
  284. }
  285. /* read data from it */
  286. *data = 0;
  287. ret = swd_transfer(ctx, false, false, dp_off, data);
  288. if(ret != 1) {
  289. DBG("failed: %d", ret);
  290. return ret;
  291. }
  292. return ret;
  293. }
  294. static uint8_t
  295. swd_write_dpbank(AppFSM* const ctx, uint8_t dp_off, uint8_t dp_bank, uint32_t* data) {
  296. uint8_t ret = 0;
  297. /* select target bank */
  298. if(dp_bank < 0x10) {
  299. ret = swd_select(ctx, 0, 0, dp_bank);
  300. if(ret != 1) {
  301. DBGS("swd_select failed");
  302. return ret;
  303. }
  304. }
  305. /* write it */
  306. ret = swd_transfer(ctx, false, true, dp_off, data);
  307. if(ret != 1) {
  308. DBG("failed: %d", ret);
  309. return ret;
  310. }
  311. return ret;
  312. }
  313. static uint8_t swd_read_ap(AppFSM* const ctx, uint8_t ap, uint8_t ap_off, uint32_t* data) {
  314. /* select target bank */
  315. uint8_t ret = swd_select(ctx, ap, (ap_off >> 4) & 0x0F, 0);
  316. if(ret != 1) {
  317. DBGS("swd_select failed");
  318. return ret;
  319. }
  320. ret = swd_transfer(ctx, true, false, (ap_off >> 2) & 3, data);
  321. *data = 0;
  322. ret = swd_transfer(ctx, true, false, (ap_off >> 2) & 3, data);
  323. if(ret != 1) {
  324. DBG("failed: %d", ret);
  325. return ret;
  326. }
  327. return ret;
  328. }
  329. static uint8_t swd_read_ap_single(AppFSM* const ctx, uint8_t ap, uint8_t ap_off, uint32_t* data) {
  330. uint8_t ret = swd_select(ctx, ap, (ap_off >> 4) & 0x0F, 0);
  331. if(ret != 1) {
  332. DBGS("swd_select failed");
  333. return ret;
  334. }
  335. *data = 0;
  336. ret = swd_transfer(ctx, true, false, (ap_off >> 2) & 3, data);
  337. if(ret != 1) {
  338. DBG("failed: %d", ret);
  339. return ret;
  340. }
  341. return ret;
  342. }
  343. static uint8_t swd_write_ap(AppFSM* const ctx, uint8_t ap, uint8_t ap_off, uint32_t data) {
  344. uint8_t ret = swd_select(ctx, ap, (ap_off >> 4) & 0x0F, 0);
  345. if(ret != 1) {
  346. DBGS("swd_select failed");
  347. return ret;
  348. }
  349. ret = swd_transfer(ctx, true, true, (ap_off >> 2) & 3, &data);
  350. if(ret != 1) {
  351. DBG("failed: %d", ret);
  352. return ret;
  353. }
  354. return ret;
  355. }
  356. static uint8_t swd_write_memory(AppFSM* const ctx, uint8_t ap, uint32_t address, uint32_t data) {
  357. uint8_t ret = 0;
  358. uint32_t csw = 0x23000002;
  359. ret |= swd_write_ap(ctx, ap, MEMAP_CSW, csw);
  360. ret |= swd_write_ap(ctx, ap, MEMAP_TAR, address);
  361. ret |= swd_write_ap(ctx, ap, MEMAP_DRW, data);
  362. DBG("write 0x%08lX to 0x%08lX", data, address);
  363. if(ret != 1) {
  364. swd_abort(ctx);
  365. }
  366. return ret;
  367. }
  368. static uint8_t swd_read_memory(AppFSM* const ctx, uint8_t ap, uint32_t address, uint32_t* data) {
  369. uint8_t ret = 0;
  370. uint32_t csw = 0x23000002;
  371. ret |= swd_write_ap(ctx, ap, MEMAP_CSW, csw);
  372. ret |= swd_write_ap(ctx, ap, MEMAP_TAR, address);
  373. ret |= swd_read_ap(ctx, ap, MEMAP_DRW, data);
  374. if(ret != 1) {
  375. swd_abort(ctx);
  376. }
  377. return ret;
  378. }
  379. static uint8_t swd_read_memory_block(
  380. AppFSM* const ctx,
  381. uint8_t ap,
  382. uint32_t address,
  383. uint8_t* buf,
  384. uint32_t len) {
  385. uint8_t ret = 0;
  386. uint32_t data = 0;
  387. uint32_t csw = 0x23000012;
  388. ret |= swd_write_ap(ctx, ap, MEMAP_CSW, csw);
  389. ret |= swd_write_ap(ctx, ap, MEMAP_TAR, address);
  390. ret |= swd_read_ap_single(ctx, ap, MEMAP_DRW, &data);
  391. for(size_t pos = 0; pos < len; pos += 4) {
  392. data = 0xDEADBEEF;
  393. ret |= swd_read_ap_single(ctx, ap, MEMAP_DRW, &data);
  394. DBG("read %lX", data);
  395. memcpy(&buf[pos], &data, 4);
  396. if(ret != 1) {
  397. swd_abort(ctx);
  398. return ret;
  399. }
  400. }
  401. return ret;
  402. }
  403. static uint32_t swd_detect(AppFSM* const ctx) {
  404. swd_set_data(ctx, false);
  405. swd_configure_pins(ctx, true);
  406. uint8_t data[] = {0xA5};
  407. swd_write(ctx, data, sizeof(data) * 8);
  408. /* turnaround cycle */
  409. swd_configure_pins(ctx, false);
  410. uint8_t ack_bits[3];
  411. uint8_t rdata[32];
  412. /* receive 3 ACK bits */
  413. for(int pos = 0; pos < 3; pos++) {
  414. ack_bits[pos] = swd_read_bit(ctx);
  415. }
  416. /* receive 32 RDATA bits */
  417. for(int pos = 0; pos < 32; pos++) {
  418. rdata[pos] = swd_read_bit(ctx);
  419. }
  420. /* receive parity bit */
  421. uint8_t parity = swd_read_bit(ctx);
  422. for(int io = 0; io < 8; io++) {
  423. uint8_t bitmask = 1 << io;
  424. /* skip if it's a clock */
  425. if(ctx->current_mask & bitmask) {
  426. continue;
  427. }
  428. uint8_t ack = 0;
  429. for(int pos = 0; pos < 3; pos++) {
  430. ack >>= 1;
  431. ack |= (ack_bits[pos] & bitmask) ? 4 : 0;
  432. }
  433. uint32_t dpidr = 0;
  434. for(int pos = 0; pos < 32; pos++) {
  435. dpidr >>= 1;
  436. dpidr |= (rdata[pos] & bitmask) ? 0x80000000 : 0;
  437. }
  438. if(ack == 1 && dpidr != 0 && dpidr != 0xFFFFFFFF) {
  439. bool received_parity = (parity & bitmask);
  440. if(__builtin_parity(dpidr) == received_parity) {
  441. ctx->dp_regs.dpidr = dpidr;
  442. ctx->dp_regs.dpidr_ok = true;
  443. ctx->detected = true;
  444. ctx->io_swd = bitmask;
  445. ctx->io_swc &= ctx->current_mask;
  446. LOG("swd_detect: data: %08lX, io_swd %02X, io_swc %02X",
  447. dpidr,
  448. ctx->io_swd,
  449. ctx->io_swc);
  450. if(!has_multiple_bits(ctx->io_swc)) {
  451. ctx->io_num_swd = get_bit_num(ctx->io_swd);
  452. ctx->io_num_swc = get_bit_num(ctx->io_swc);
  453. }
  454. }
  455. }
  456. }
  457. swd_set_data(ctx, false);
  458. swd_configure_pins(ctx, true);
  459. return 0;
  460. }
  461. static void swd_scan(AppFSM* const ctx) {
  462. /* To switch SWJ-DP from JTAG to SWD operation:
  463. 1. Send at least 50 SWCLKTCK cycles with SWDIOTMS HIGH. This ensures that the current interface is in its reset state. The JTAG interface only detects the 16-bit JTAG-to-SWD sequence starting from the Test-Logic-Reset state.
  464. 2. Send the 16-bit JTAG-to-SWD select sequence 0x79e7 on SWDIOTMS.
  465. 3. Send at least 50 SWCLKTCK cycles with SWDIOTMS HIGH. This ensures that if SWJ-DP was already in SWD operation before sending the select sequence, the SWD interface enters line reset state.
  466. */
  467. swd_configure_pins(ctx, true);
  468. /* reset JTAG interface */
  469. for(int bitcount = 0; bitcount < 50; bitcount += 8) {
  470. swd_write_byte(ctx, 0xFF, 8);
  471. }
  472. /* Send the 16-bit JTAG-to-SWD select sequence */
  473. swd_write_byte(ctx, 0x9E, 8);
  474. swd_write_byte(ctx, 0xE7, 8);
  475. /* resynchronize SWD */
  476. swd_line_reset(ctx);
  477. swd_detect(ctx);
  478. }
  479. static bool swd_ensure_powerup(AppFSM* const ctx) {
  480. bool ret = true;
  481. if(!(ctx->dp_regs.ctrlstat & (CSYSPWRUPREQ | CDBGPWRUPREQ))) {
  482. DBGS("no (CSYSPWRUPREQ | CDBGPWRUPREQ)");
  483. /* fetch current CTRL/STAT */
  484. DBGS(" - Fetch CTRL/STAT");
  485. ctx->dp_regs.ctrlstat_ok =
  486. swd_read_dpbank(ctx, REG_CTRLSTAT, REG_CTRLSTAT_BANK, &ctx->dp_regs.ctrlstat) == 1;
  487. DBG(" %08lX %s", ctx->dp_regs.ctrlstat, ctx->dp_regs.ctrlstat_ok ? "OK" : "FAIL");
  488. /* enable requests */
  489. ctx->dp_regs.ctrlstat |= (CSYSPWRUPREQ | CDBGPWRUPREQ);
  490. swd_write_dpbank(ctx, REG_CTRLSTAT, REG_CTRLSTAT_BANK, &ctx->dp_regs.ctrlstat);
  491. ret = false;
  492. }
  493. if(!(ctx->dp_regs.ctrlstat & CDBGPWRUPACK)) {
  494. DBGS("no CDBGPWRUPACK");
  495. /* fetch current CTRL/STAT */
  496. swd_read_dpbank(ctx, REG_CTRLSTAT, REG_CTRLSTAT_BANK, &ctx->dp_regs.ctrlstat);
  497. ret = false;
  498. }
  499. if(!ret) {
  500. DBGS(" - Fetch CTRL/STAT");
  501. ctx->dp_regs.ctrlstat_ok =
  502. swd_read_dpbank(ctx, REG_CTRLSTAT, REG_CTRLSTAT_BANK, &ctx->dp_regs.ctrlstat) == 1;
  503. DBG(" %08lX %s", ctx->dp_regs.ctrlstat, ctx->dp_regs.ctrlstat_ok ? "OK" : "FAIL");
  504. }
  505. return ret;
  506. }
  507. static void swd_apscan_reset(AppFSM* const ctx) {
  508. for(size_t reset_ap = 0; reset_ap < COUNT(ctx->apidr_info); reset_ap++) {
  509. ctx->apidr_info[reset_ap].tested = false;
  510. }
  511. }
  512. static bool swd_apscan_test(AppFSM* const ctx, uint32_t ap) {
  513. furi_assert(ctx);
  514. furi_assert(ap < sizeof(ctx->apidr_info));
  515. bool ret = true;
  516. ctx->apidr_info[ap].tested = true;
  517. uint32_t data = 0;
  518. if(swd_read_ap(ctx, ap, AP_IDR, &data) != 1) {
  519. swd_abort(ctx);
  520. return false;
  521. }
  522. if(data == 0) {
  523. return false;
  524. }
  525. DBG("AP%lu detected", ap);
  526. ctx->apidr_info[ap].ok = true;
  527. ctx->apidr_info[ap].revision = (data >> 24) & 0x0F;
  528. ctx->apidr_info[ap].designer = (data >> 17) & 0x3FF;
  529. ctx->apidr_info[ap].class = (data >> 13) & 0x0F;
  530. ctx->apidr_info[ap].variant = (data >> 4) & 0x0F;
  531. ctx->apidr_info[ap].type = (data >> 0) & 0x0F;
  532. if(swd_read_ap(ctx, ap, AP_BASE, &ctx->apidr_info[ap].base) != 1) {
  533. swd_abort(ctx);
  534. ret = false;
  535. }
  536. return ret;
  537. }
  538. /************************** script helpers **************************/
  539. static void swd_script_log(ScriptContext* ctx, FuriLogLevel level, const char* format, ...) {
  540. bool commandline = false;
  541. ScriptContext* cur = ctx;
  542. char buffer[256];
  543. va_list argp;
  544. va_start(argp, format);
  545. do {
  546. if(cur == ctx->app->commandline) {
  547. commandline = true;
  548. }
  549. cur = cur->parent;
  550. } while(cur);
  551. if(commandline) {
  552. const char* prefix = "";
  553. switch(level) {
  554. case FuriLogLevelWarn:
  555. prefix = "Warning: ";
  556. break;
  557. case FuriLogLevelError:
  558. prefix = "ERROR: ";
  559. break;
  560. default:
  561. break;
  562. }
  563. strcpy(buffer, prefix);
  564. size_t pos = strlen(buffer);
  565. vsnprintf(&buffer[pos], sizeof(buffer) - pos - 2, format, argp);
  566. strcat(buffer, "\n");
  567. usb_uart_tx_data(ctx->app->uart, (uint8_t*)buffer, strlen(buffer));
  568. } else {
  569. LOG(buffer);
  570. }
  571. va_end(argp);
  572. }
  573. /* read characters until newline was read */
  574. static bool swd_script_seek_newline(ScriptContext* ctx) {
  575. while(true) {
  576. uint8_t ch = 0;
  577. if(ctx->script_file) {
  578. if(storage_file_read(ctx->script_file, &ch, 1) != 1) {
  579. return false;
  580. }
  581. } else {
  582. ch = ctx->line_data[ctx->line_pos];
  583. if(ch == 0) {
  584. return false;
  585. }
  586. ctx->line_pos++;
  587. }
  588. if(ch == '\n') {
  589. return true;
  590. }
  591. }
  592. }
  593. /* read whitespaces until the next character is read.
  594. returns false if EOF or newline was read */
  595. static bool swd_script_skip_whitespace(ScriptContext* ctx) {
  596. while(true) {
  597. uint8_t ch = 0;
  598. uint64_t start_pos = 0;
  599. if(ctx->script_file) {
  600. start_pos = storage_file_tell(ctx->script_file);
  601. if(storage_file_read(ctx->script_file, &ch, 1) != 1) {
  602. return false;
  603. }
  604. } else {
  605. start_pos = ctx->line_pos;
  606. ch = ctx->line_data[ctx->line_pos];
  607. if(ch == 0) {
  608. return false;
  609. }
  610. ctx->line_pos++;
  611. }
  612. if(ch == '\n') {
  613. return false;
  614. }
  615. if(ch != ' ') {
  616. if(ctx->script_file) {
  617. storage_file_seek(ctx->script_file, start_pos, true);
  618. } else {
  619. ctx->line_pos = start_pos;
  620. }
  621. return true;
  622. }
  623. }
  624. }
  625. static bool swd_script_get_string(ScriptContext* ctx, char* str, size_t max_length) {
  626. bool quot = false;
  627. size_t pos = 0;
  628. str[pos] = '\000';
  629. while(true) {
  630. char ch = 0;
  631. uint64_t start_pos = 0;
  632. if(ctx->script_file) {
  633. start_pos = storage_file_tell(ctx->script_file);
  634. if(storage_file_read(ctx->script_file, &ch, 1) != 1) {
  635. DBGS("end reached");
  636. return false;
  637. }
  638. } else {
  639. start_pos = ctx->line_pos;
  640. ch = ctx->line_data[ctx->line_pos];
  641. if(ch == 0) {
  642. DBGS("end reached");
  643. return false;
  644. }
  645. ctx->line_pos++;
  646. }
  647. if(ch == '"') {
  648. quot = !quot;
  649. continue;
  650. }
  651. if(!quot) {
  652. if(ch == ' ') {
  653. break;
  654. }
  655. if(ch == '\r' || ch == '\n') {
  656. if(ctx->script_file) {
  657. storage_file_seek(ctx->script_file, start_pos, true);
  658. } else {
  659. ctx->line_pos = start_pos;
  660. }
  661. break;
  662. }
  663. }
  664. if(pos + 2 > max_length) {
  665. DBGS("too long");
  666. return false;
  667. }
  668. str[pos++] = ch;
  669. str[pos] = '\000';
  670. }
  671. DBG("got '%s'", str);
  672. return true;
  673. }
  674. static bool swd_script_get_number(ScriptContext* ctx, uint32_t* number) {
  675. char str[16];
  676. if(!swd_script_get_string(ctx, str, sizeof(str))) {
  677. DBGS("could not get string");
  678. return false;
  679. }
  680. DBG("got '%s'", str);
  681. size_t pos = 0;
  682. *number = 0;
  683. /* hex number? */
  684. if(!strncmp(str, "0x", 2)) {
  685. pos += 2;
  686. while(str[pos]) {
  687. uint8_t ch = str[pos++];
  688. uint8_t ch_num = ch - '0';
  689. uint8_t ch_hex = (ch & ~0x20) - 'A';
  690. *number <<= 4;
  691. if(ch_num <= 10) {
  692. *number += ch_num;
  693. } else if(ch_hex <= 5) {
  694. *number += 10 + ch_hex;
  695. } else {
  696. return false;
  697. }
  698. }
  699. } else {
  700. while(str[pos]) {
  701. uint8_t ch = str[pos++];
  702. uint8_t ch_num = ch - '0';
  703. *number *= 10;
  704. if(ch_num < 10) {
  705. *number += ch_num;
  706. } else {
  707. return false;
  708. }
  709. }
  710. }
  711. return true;
  712. }
  713. static void swd_script_gui_refresh(ScriptContext* ctx) {
  714. if(furi_message_queue_get_count(ctx->app->event_queue) > 0) {
  715. swd_message_process(ctx->app);
  716. }
  717. if(!ctx->status_ignore) {
  718. DBG("Status: %s", ctx->app->state_string);
  719. view_port_update(ctx->app->view_port);
  720. }
  721. }
  722. /************************** script functions **************************/
  723. static bool swd_scriptfunc_comment(ScriptContext* ctx) {
  724. DBGS("comment");
  725. swd_script_seek_newline(ctx);
  726. return true;
  727. }
  728. static bool swd_scriptfunc_label(ScriptContext* ctx) {
  729. char label[256];
  730. DBGS("label");
  731. swd_script_skip_whitespace(ctx);
  732. if(!swd_script_get_string(ctx, label, sizeof(label))) {
  733. swd_script_log(ctx, FuriLogLevelError, "failed to parse label");
  734. return false;
  735. }
  736. if(!strcmp(label, ctx->goto_label)) {
  737. ctx->goto_active = false;
  738. DBG("matches '%s'", ctx->goto_label);
  739. }
  740. swd_script_seek_newline(ctx);
  741. return true;
  742. }
  743. static bool swd_scriptfunc_goto(ScriptContext* ctx) {
  744. DBGS("goto");
  745. swd_script_skip_whitespace(ctx);
  746. if(!swd_script_get_string(ctx, ctx->goto_label, sizeof(ctx->goto_label))) {
  747. swd_script_log(ctx, FuriLogLevelError, "failed to parse target label");
  748. return false;
  749. }
  750. /* start from beginning and rerun starting from label */
  751. ctx->goto_active = true;
  752. ctx->restart = true;
  753. swd_script_seek_newline(ctx);
  754. return true;
  755. }
  756. static bool swd_scriptfunc_call(ScriptContext* ctx) {
  757. DBGS("call");
  758. swd_script_skip_whitespace(ctx);
  759. /* fetch previous file directory */
  760. char filename[MAX_FILE_LENGTH];
  761. strncpy(filename, ctx->filename, sizeof(filename));
  762. char* path = strrchr(filename, '/');
  763. path[1] = '\000';
  764. /* append filename */
  765. if(!swd_script_get_string(ctx, &path[1], sizeof(filename) - strlen(path))) {
  766. swd_script_log(ctx, FuriLogLevelError, "failed to parse filename");
  767. return false;
  768. }
  769. swd_script_seek_newline(ctx);
  770. /* append extension */
  771. if(strlen(filename) + 5 >= sizeof(filename)) {
  772. swd_script_log(ctx, FuriLogLevelError, "name too long");
  773. return false;
  774. }
  775. strcat(filename, ".swd");
  776. bool ret = swd_execute_script(ctx->app, filename);
  777. if(!ret) {
  778. swd_script_log(ctx, FuriLogLevelError, "failed to exec '%s'", filename);
  779. return false;
  780. }
  781. return true;
  782. }
  783. static bool swd_scriptfunc_status(ScriptContext* ctx) {
  784. uint32_t status = 1;
  785. DBGS("status");
  786. swd_script_skip_whitespace(ctx);
  787. swd_script_get_number(ctx, &status);
  788. ctx->status_ignore = (status == 0);
  789. swd_script_seek_newline(ctx);
  790. return true;
  791. }
  792. static bool swd_scriptfunc_errors(ScriptContext* ctx) {
  793. char type[32];
  794. DBGS("errors");
  795. swd_script_skip_whitespace(ctx);
  796. if(!swd_script_get_string(ctx, type, sizeof(type))) {
  797. swd_script_log(ctx, FuriLogLevelError, "failed to parse");
  798. return false;
  799. }
  800. if(!strcmp(type, "ignore")) {
  801. ctx->errors_ignore = true;
  802. }
  803. if(!strcmp(type, "fail")) {
  804. ctx->errors_ignore = false;
  805. }
  806. swd_script_seek_newline(ctx);
  807. return true;
  808. }
  809. static bool swd_scriptfunc_beep(ScriptContext* ctx) {
  810. uint32_t sound = 0;
  811. DBGS("beep");
  812. swd_script_skip_whitespace(ctx);
  813. swd_script_get_number(ctx, &sound);
  814. notification_message_block(ctx->app->notification, seq_sounds[sound]);
  815. swd_script_seek_newline(ctx);
  816. return true;
  817. }
  818. static bool swd_scriptfunc_message(ScriptContext* ctx) {
  819. uint32_t wait_time = 0;
  820. char message[256];
  821. char type[256];
  822. bool success = true;
  823. bool show_dialog = false;
  824. if(!swd_script_skip_whitespace(ctx)) {
  825. swd_script_log(ctx, FuriLogLevelError, "missing whitespace");
  826. return false;
  827. }
  828. if(!swd_script_get_number(ctx, &wait_time)) {
  829. swd_script_log(ctx, FuriLogLevelError, "failed to parse wait_time");
  830. return false;
  831. }
  832. if(!swd_script_get_string(ctx, message, sizeof(message))) {
  833. swd_script_log(ctx, FuriLogLevelError, "failed to parse message");
  834. return false;
  835. }
  836. if(swd_script_get_string(ctx, type, sizeof(type))) {
  837. if(!strcmp(type, "dialog")) {
  838. show_dialog = true;
  839. }
  840. }
  841. if(wait_time <= 60 * 1000) {
  842. strncpy(ctx->app->state_string, message, sizeof(ctx->app->state_string));
  843. swd_script_gui_refresh(ctx);
  844. furi_delay_ms(wait_time);
  845. if(show_dialog) {
  846. DialogMessage* message = dialog_message_alloc();
  847. dialog_message_set_header(message, "SWD Probe", 16, 2, AlignLeft, AlignTop);
  848. dialog_message_set_icon(message, &I_app, 3, 2);
  849. dialog_message_set_text(message, ctx->app->state_string, 3, 16, AlignLeft, AlignTop);
  850. dialog_message_set_buttons(message, "Abort", "Ok", NULL);
  851. success = dialog_message_show(ctx->app->dialogs, message) == DialogMessageButtonCenter;
  852. dialog_message_free(message);
  853. }
  854. }
  855. swd_script_seek_newline(ctx);
  856. return success;
  857. }
  858. static bool swd_scriptfunc_swd_idle_bits(ScriptContext* ctx) {
  859. uint32_t swd_idle_bits = 0;
  860. if(!swd_script_skip_whitespace(ctx)) {
  861. swd_script_log(ctx, FuriLogLevelError, "missing whitespace");
  862. return false;
  863. }
  864. if(!swd_script_get_number(ctx, &swd_idle_bits)) {
  865. swd_script_log(ctx, FuriLogLevelError, "failed to parse");
  866. return false;
  867. }
  868. if(swd_idle_bits <= 32) {
  869. ctx->app->swd_idle_bits = swd_idle_bits;
  870. } else {
  871. swd_script_log(ctx, FuriLogLevelError, "value must be between 1 and 32");
  872. }
  873. swd_script_seek_newline(ctx);
  874. return true;
  875. }
  876. static bool swd_scriptfunc_swd_clock_delay(ScriptContext* ctx) {
  877. uint32_t swd_clock_delay = 0;
  878. if(!swd_script_skip_whitespace(ctx)) {
  879. swd_script_log(ctx, FuriLogLevelError, "missing whitespace");
  880. return false;
  881. }
  882. if(!swd_script_get_number(ctx, &swd_clock_delay)) {
  883. swd_script_log(ctx, FuriLogLevelError, "failed to parse");
  884. return false;
  885. }
  886. if(swd_clock_delay <= 1000000) {
  887. ctx->app->swd_clock_delay = swd_clock_delay;
  888. } else {
  889. swd_script_log(ctx, FuriLogLevelError, "value must be between 1 and 1000000");
  890. }
  891. swd_script_seek_newline(ctx);
  892. return true;
  893. }
  894. static bool swd_scriptfunc_maxtries(ScriptContext* ctx) {
  895. uint32_t max_tries = 0;
  896. if(!swd_script_skip_whitespace(ctx)) {
  897. swd_script_log(ctx, FuriLogLevelError, "missing whitespace");
  898. return false;
  899. }
  900. if(!swd_script_get_number(ctx, &max_tries)) {
  901. swd_script_log(ctx, FuriLogLevelError, "failed to parse");
  902. return false;
  903. }
  904. if(max_tries >= 1 && max_tries <= 1024) {
  905. ctx->max_tries = max_tries;
  906. } else {
  907. DBGS("value must be between 1 and 1024");
  908. }
  909. swd_script_seek_newline(ctx);
  910. return true;
  911. }
  912. static bool swd_scriptfunc_blocksize(ScriptContext* ctx) {
  913. uint32_t block_size = 0;
  914. if(!swd_script_skip_whitespace(ctx)) {
  915. swd_script_log(ctx, FuriLogLevelError, "missing whitespace");
  916. return false;
  917. }
  918. if(!swd_script_get_number(ctx, &block_size)) {
  919. swd_script_log(ctx, FuriLogLevelError, "failed to parse");
  920. return false;
  921. }
  922. if(block_size >= 4 && block_size <= 0x1000) {
  923. ctx->block_size = block_size;
  924. } else {
  925. swd_script_log(ctx, FuriLogLevelError, "value must be between 4 and 4096");
  926. }
  927. swd_script_seek_newline(ctx);
  928. return true;
  929. }
  930. static bool swd_scriptfunc_apselect(ScriptContext* ctx) {
  931. uint32_t ap = 0;
  932. if(!swd_script_skip_whitespace(ctx)) {
  933. swd_script_log(ctx, FuriLogLevelError, "missing whitespace");
  934. return false;
  935. }
  936. if(!swd_script_get_number(ctx, &ap)) {
  937. swd_script_log(ctx, FuriLogLevelError, "failed to parse AP");
  938. return false;
  939. }
  940. if(!swd_apscan_test(ctx->app, ap)) {
  941. swd_script_log(ctx, FuriLogLevelError, "no selected AP");
  942. return false;
  943. }
  944. ctx->selected_ap = ap;
  945. swd_script_seek_newline(ctx);
  946. return true;
  947. }
  948. static bool swd_scriptfunc_apscan(ScriptContext* ctx) {
  949. DBGS("Scanning APs");
  950. for(uint32_t ap = 0; ap < 255; ap++) {
  951. snprintf(ctx->app->state_string, sizeof(ctx->app->state_string), "Scan AP %lu", ap);
  952. swd_script_gui_refresh(ctx);
  953. if(swd_apscan_test(ctx->app, ap)) {
  954. DBG(" AP%lu detected", ap);
  955. }
  956. }
  957. swd_script_seek_newline(ctx);
  958. return true;
  959. }
  960. static bool swd_scriptfunc_abort(ScriptContext* ctx) {
  961. DBGS("Aborting");
  962. swd_abort(ctx->app);
  963. swd_script_seek_newline(ctx);
  964. return true;
  965. }
  966. static bool swd_scriptfunc_mem_dump(ScriptContext* ctx) {
  967. char filename[MAX_FILE_LENGTH];
  968. uint32_t address = 0;
  969. uint32_t length = 0;
  970. uint32_t flags = 0;
  971. bool success = true;
  972. /* get file */
  973. if(!swd_script_skip_whitespace(ctx)) {
  974. swd_script_log(ctx, FuriLogLevelError, "missing whitespace");
  975. return false;
  976. }
  977. if(!swd_script_get_string(ctx, filename, sizeof(filename))) {
  978. swd_script_log(ctx, FuriLogLevelError, "failed to parse filename");
  979. return false;
  980. }
  981. /* get address */
  982. if(!swd_script_get_number(ctx, &address)) {
  983. swd_script_log(ctx, FuriLogLevelError, "failed to parse address");
  984. return false;
  985. }
  986. /* get length */
  987. if(!swd_script_get_number(ctx, &length)) {
  988. swd_script_log(ctx, FuriLogLevelError, "failed to parse length");
  989. return false;
  990. }
  991. /* get flags */
  992. if(swd_script_get_number(ctx, &flags)) {
  993. DBGS("found extra flags");
  994. }
  995. LOG("would dump %08lX, len %08lX into %s", address, length, filename);
  996. File* dump = storage_file_alloc(ctx->app->storage);
  997. if(!storage_file_open(dump, filename, FSAM_WRITE, FSOM_CREATE_ALWAYS)) {
  998. storage_file_free(dump);
  999. snprintf(ctx->app->state_string, sizeof(ctx->app->state_string), "Failed to create file");
  1000. swd_script_gui_refresh(ctx);
  1001. notification_message_block(ctx->app->notification, &seq_error);
  1002. return false;
  1003. }
  1004. if(ctx->block_size == 0) {
  1005. ctx->block_size = 0x100;
  1006. }
  1007. if(ctx->block_size > 0x1000) {
  1008. ctx->block_size = 0x1000;
  1009. }
  1010. uint8_t* buffer = malloc(ctx->block_size);
  1011. furi_mutex_acquire(ctx->app->swd_mutex, FuriWaitForever);
  1012. for(uint32_t pos = 0; pos < length; pos += ctx->block_size) {
  1013. if((pos & 0xFF) == 0) {
  1014. int pct = pos * 100 / length;
  1015. snprintf(
  1016. ctx->app->state_string,
  1017. sizeof(ctx->app->state_string),
  1018. "Dump %08lX (%d%%)",
  1019. pos,
  1020. pct);
  1021. swd_script_gui_refresh(ctx);
  1022. }
  1023. bool read_ok = false;
  1024. for(uint32_t tries = 0; tries < ctx->max_tries; tries++) {
  1025. if(ctx->abort) {
  1026. DBGS("aborting read");
  1027. break;
  1028. }
  1029. uint32_t ret = 0;
  1030. if(ctx->block_size > 4) {
  1031. ret = swd_read_memory_block(
  1032. ctx->app, ctx->selected_ap, address + pos, buffer, ctx->block_size);
  1033. } else {
  1034. ret =
  1035. swd_read_memory(ctx->app, ctx->selected_ap, address + pos, (uint32_t*)buffer);
  1036. }
  1037. read_ok = (ret == 1);
  1038. if(!read_ok) {
  1039. snprintf(
  1040. ctx->app->state_string,
  1041. sizeof(ctx->app->state_string),
  1042. "Failed at 0x%08lX",
  1043. address + pos);
  1044. swd_script_gui_refresh(ctx);
  1045. furi_delay_ms(100);
  1046. } else {
  1047. break;
  1048. }
  1049. }
  1050. if(ctx->abort) {
  1051. DBGS("aborting");
  1052. break;
  1053. }
  1054. if(!read_ok) {
  1055. /* flags == 1: "continue reading even if it fails" */
  1056. /* flags == 2: "its okay if cannot dump fully" */
  1057. if(flags & 1) {
  1058. /* set all content to a known value as indication */
  1059. for(size_t fill_pos = 0; fill_pos < ctx->block_size; fill_pos += 4) {
  1060. *((uint32_t*)&buffer[fill_pos]) = 0xDEADFACE;
  1061. }
  1062. } else if(flags & 2) {
  1063. success = (pos > 0);
  1064. break;
  1065. } else {
  1066. notification_message_block(ctx->app->notification, &seq_error);
  1067. success = false;
  1068. break;
  1069. }
  1070. }
  1071. storage_file_write(dump, buffer, ctx->block_size);
  1072. }
  1073. furi_mutex_release(ctx->app->swd_mutex);
  1074. storage_file_close(dump);
  1075. swd_script_seek_newline(ctx);
  1076. free(buffer);
  1077. return success;
  1078. }
  1079. static bool swd_scriptfunc_mem_write(ScriptContext* ctx) {
  1080. uint32_t address = 0;
  1081. uint32_t data = 0;
  1082. bool success = true;
  1083. /* get file */
  1084. if(!swd_script_skip_whitespace(ctx)) {
  1085. swd_script_log(ctx, FuriLogLevelError, "missing whitespace");
  1086. return false;
  1087. }
  1088. /* get address */
  1089. if(!swd_script_get_number(ctx, &address)) {
  1090. swd_script_log(ctx, FuriLogLevelError, "failed to parse address");
  1091. return false;
  1092. }
  1093. /* get data */
  1094. if(!swd_script_get_number(ctx, &data)) {
  1095. swd_script_log(ctx, FuriLogLevelError, "failed to parse data");
  1096. return false;
  1097. }
  1098. DBG("write %08lX to %08lX", data, address);
  1099. bool access_ok = false;
  1100. for(uint32_t tries = 0; tries < ctx->max_tries; tries++) {
  1101. if(ctx->abort) {
  1102. DBGS("aborting");
  1103. break;
  1104. }
  1105. furi_mutex_acquire(ctx->app->swd_mutex, FuriWaitForever);
  1106. access_ok = swd_write_memory(ctx->app, ctx->selected_ap, address, data) == 1;
  1107. furi_mutex_release(ctx->app->swd_mutex);
  1108. access_ok |= ctx->errors_ignore;
  1109. swd_read_memory(ctx->app, ctx->selected_ap, address, &data);
  1110. DBG("read %08lX from %08lX", data, address);
  1111. if(!access_ok) {
  1112. snprintf(
  1113. ctx->app->state_string,
  1114. sizeof(ctx->app->state_string),
  1115. "Failed write 0x%08lX",
  1116. address);
  1117. swd_script_gui_refresh(ctx);
  1118. } else {
  1119. break;
  1120. }
  1121. }
  1122. if(!access_ok) {
  1123. notification_message_block(ctx->app->notification, &seq_error);
  1124. success = false;
  1125. }
  1126. swd_script_seek_newline(ctx);
  1127. return success;
  1128. }
  1129. static bool swd_scriptfunc_mem_ldmst(ScriptContext* ctx) {
  1130. uint32_t address = 0;
  1131. uint32_t data = 0;
  1132. uint32_t mask = 0;
  1133. bool success = true;
  1134. if(!swd_script_skip_whitespace(ctx)) {
  1135. swd_script_log(ctx, FuriLogLevelError, "missing whitespace");
  1136. return false;
  1137. }
  1138. /* get address */
  1139. if(!swd_script_get_number(ctx, &address)) {
  1140. swd_script_log(ctx, FuriLogLevelError, "failed to parse address");
  1141. return false;
  1142. }
  1143. /* get data */
  1144. if(!swd_script_get_number(ctx, &data)) {
  1145. swd_script_log(ctx, FuriLogLevelError, "failed to parse data");
  1146. return false;
  1147. }
  1148. /* get mask */
  1149. if(!swd_script_get_number(ctx, &mask)) {
  1150. swd_script_log(ctx, FuriLogLevelError, "failed to parse mask");
  1151. return false;
  1152. }
  1153. LOG("write %08lX to %08lX, mask %08lX", data, address, mask);
  1154. bool access_ok = false;
  1155. uint32_t modified = 0;
  1156. for(uint32_t tries = 0; tries < ctx->max_tries; tries++) {
  1157. if(ctx->abort) {
  1158. DBGS("aborting");
  1159. break;
  1160. }
  1161. furi_mutex_acquire(ctx->app->swd_mutex, FuriWaitForever);
  1162. access_ok = swd_read_memory(ctx->app, ctx->selected_ap, address, &modified) == 1;
  1163. modified = (modified & mask) | data;
  1164. access_ok &= swd_write_memory(ctx->app, ctx->selected_ap, address, modified) == 1;
  1165. furi_mutex_release(ctx->app->swd_mutex);
  1166. access_ok |= ctx->errors_ignore;
  1167. if(!access_ok) {
  1168. snprintf(
  1169. ctx->app->state_string,
  1170. sizeof(ctx->app->state_string),
  1171. "Failed access 0x%08lX",
  1172. address);
  1173. swd_script_gui_refresh(ctx);
  1174. } else {
  1175. break;
  1176. }
  1177. }
  1178. if(!access_ok) {
  1179. notification_message_block(ctx->app->notification, &seq_error);
  1180. success = false;
  1181. }
  1182. swd_script_seek_newline(ctx);
  1183. return success;
  1184. }
  1185. static bool swd_scriptfunc_dp_write(ScriptContext* ctx) {
  1186. uint32_t dp_bank = 0;
  1187. uint32_t dp_off = 0;
  1188. uint32_t data = 0;
  1189. bool success = true;
  1190. if(!swd_script_skip_whitespace(ctx)) {
  1191. swd_script_log(ctx, FuriLogLevelError, "missing whitespace");
  1192. return false;
  1193. }
  1194. /* get data */
  1195. if(!swd_script_get_number(ctx, &data)) {
  1196. swd_script_log(ctx, FuriLogLevelError, "failed to parse data");
  1197. return false;
  1198. }
  1199. /* get dp_off */
  1200. if(!swd_script_get_number(ctx, &dp_off)) {
  1201. swd_script_log(ctx, FuriLogLevelError, "failed to parse DP offset");
  1202. return false;
  1203. }
  1204. /* get dp_bank */
  1205. if(!swd_script_get_number(ctx, &dp_bank)) {
  1206. dp_bank = 0xFF;
  1207. }
  1208. swd_script_log(
  1209. ctx, FuriLogLevelDefault, "write %08lX to reg %08lX / bank %08lX", data, dp_off, dp_bank);
  1210. furi_mutex_acquire(ctx->app->swd_mutex, FuriWaitForever);
  1211. uint8_t ret = swd_write_dpbank(ctx->app, dp_off, dp_bank, &data);
  1212. if(ret != 1) {
  1213. swd_script_log(ctx, FuriLogLevelError, "swd_write_dpbank failed");
  1214. success = false;
  1215. }
  1216. furi_mutex_release(ctx->app->swd_mutex);
  1217. swd_script_seek_newline(ctx);
  1218. return success;
  1219. }
  1220. static bool swd_scriptfunc_dp_read(ScriptContext* ctx) {
  1221. uint32_t dp_bank = 0;
  1222. uint32_t dp_off = 0;
  1223. uint32_t data = 0;
  1224. bool success = true;
  1225. if(!swd_script_skip_whitespace(ctx)) {
  1226. swd_script_log(ctx, FuriLogLevelError, "missing whitespace");
  1227. return false;
  1228. }
  1229. /* get dp_off */
  1230. if(!swd_script_get_number(ctx, &dp_off)) {
  1231. swd_script_log(ctx, FuriLogLevelError, "failed to parse DP offset");
  1232. return false;
  1233. }
  1234. /* get dp_bank */
  1235. if(!swd_script_get_number(ctx, &dp_bank)) {
  1236. dp_bank = 0xFF;
  1237. }
  1238. swd_script_log(ctx, FuriLogLevelDefault, "read reg %02lX / bank %02lX", dp_off, dp_bank);
  1239. furi_mutex_acquire(ctx->app->swd_mutex, FuriWaitForever);
  1240. uint8_t ret = swd_read_dpbank(ctx->app, dp_off, dp_bank, &data);
  1241. if(ret != 1) {
  1242. swd_script_log(ctx, FuriLogLevelError, "swd_read_dpbank failed");
  1243. success = false;
  1244. } else {
  1245. swd_script_log(ctx, FuriLogLevelDefault, "result: 0x%08lX", data);
  1246. }
  1247. furi_mutex_release(ctx->app->swd_mutex);
  1248. swd_script_seek_newline(ctx);
  1249. return success;
  1250. }
  1251. static bool swd_scriptfunc_ap_write(ScriptContext* ctx) {
  1252. uint32_t ap_reg = 0;
  1253. uint32_t data = 0;
  1254. bool success = true;
  1255. if(!swd_script_skip_whitespace(ctx)) {
  1256. swd_script_log(ctx, FuriLogLevelError, "missing whitespace");
  1257. return false;
  1258. }
  1259. /* get data */
  1260. if(!swd_script_get_number(ctx, &data)) {
  1261. swd_script_log(ctx, FuriLogLevelError, "failed to parse data");
  1262. return false;
  1263. }
  1264. /* get ap_reg */
  1265. if(!swd_script_get_number(ctx, &ap_reg)) {
  1266. swd_script_log(ctx, FuriLogLevelError, "failed to parse AP register");
  1267. return false;
  1268. }
  1269. swd_script_log(
  1270. ctx, FuriLogLevelDefault, "AP%d %08lX -> %02lX", ctx->selected_ap, data, ap_reg);
  1271. furi_mutex_acquire(ctx->app->swd_mutex, FuriWaitForever);
  1272. uint8_t ret = swd_write_ap(ctx->app, ctx->selected_ap, ap_reg, data);
  1273. if(ret != 1) {
  1274. swd_script_log(ctx, FuriLogLevelError, "swd_write_ap failed");
  1275. success = false;
  1276. }
  1277. furi_mutex_release(ctx->app->swd_mutex);
  1278. swd_script_seek_newline(ctx);
  1279. return success;
  1280. }
  1281. static bool swd_scriptfunc_ap_read(ScriptContext* ctx) {
  1282. uint32_t ap_reg = 0;
  1283. uint32_t data = 0;
  1284. bool success = true;
  1285. if(!swd_script_skip_whitespace(ctx)) {
  1286. swd_script_log(ctx, FuriLogLevelError, "missing whitespace");
  1287. return false;
  1288. }
  1289. /* get ap_reg */
  1290. if(!swd_script_get_number(ctx, &ap_reg)) {
  1291. swd_script_log(ctx, FuriLogLevelError, "failed to parse AP register");
  1292. return false;
  1293. }
  1294. furi_mutex_acquire(ctx->app->swd_mutex, FuriWaitForever);
  1295. uint8_t ret = swd_read_ap(ctx->app, ctx->selected_ap, ap_reg, &data);
  1296. if(ret != 1) {
  1297. swd_script_log(ctx, FuriLogLevelError, "swd_read_ap failed");
  1298. success = false;
  1299. } else {
  1300. swd_script_log(
  1301. ctx, FuriLogLevelDefault, "AP%d %02lX: %08lX", ctx->selected_ap, ap_reg, data);
  1302. }
  1303. furi_mutex_release(ctx->app->swd_mutex);
  1304. swd_script_seek_newline(ctx);
  1305. return success;
  1306. }
  1307. static const ScriptFunctionInfo script_funcs[] = {
  1308. {"#", &swd_scriptfunc_comment},
  1309. {".label", &swd_scriptfunc_label},
  1310. {"goto", &swd_scriptfunc_goto},
  1311. {"call", &swd_scriptfunc_call},
  1312. {"status", &swd_scriptfunc_status},
  1313. {"errors", &swd_scriptfunc_errors},
  1314. {"message", &swd_scriptfunc_message},
  1315. {"beep", &swd_scriptfunc_beep},
  1316. {"max_tries", &swd_scriptfunc_maxtries},
  1317. {"swd_clock_delay", &swd_scriptfunc_swd_clock_delay},
  1318. {"swd_idle_bits", &swd_scriptfunc_swd_idle_bits},
  1319. {"block_size", &swd_scriptfunc_blocksize},
  1320. {"abort", &swd_scriptfunc_abort},
  1321. {"mem_dump", &swd_scriptfunc_mem_dump},
  1322. {"mem_ldmst", &swd_scriptfunc_mem_ldmst},
  1323. {"mem_write", &swd_scriptfunc_mem_write},
  1324. {"dp_write", &swd_scriptfunc_dp_write},
  1325. {"dp_read", &swd_scriptfunc_dp_read},
  1326. {"ap_scan", &swd_scriptfunc_apscan},
  1327. {"ap_select", &swd_scriptfunc_apselect},
  1328. {"ap_read", &swd_scriptfunc_ap_read},
  1329. {"ap_write", &swd_scriptfunc_ap_write}};
  1330. /************************** script main code **************************/
  1331. static bool swd_execute_script_line(ScriptContext* const ctx) {
  1332. char buffer[64];
  1333. uint64_t start_pos = 0;
  1334. if(ctx->script_file) {
  1335. start_pos = storage_file_tell(ctx->script_file);
  1336. uint16_t ret = storage_file_read(ctx->script_file, buffer, 2);
  1337. storage_file_seek(ctx->script_file, start_pos, true);
  1338. if(ret < 2) {
  1339. return true;
  1340. }
  1341. } else {
  1342. start_pos = ctx->line_pos;
  1343. strncpy(buffer, ctx->line_data, 2);
  1344. if(buffer[0] == 0 || buffer[1] == 0) {
  1345. return true;
  1346. }
  1347. }
  1348. if(buffer[0] == '\n' || (buffer[0] == '\r' && buffer[1] == '\n')) {
  1349. swd_script_seek_newline(ctx);
  1350. return true;
  1351. }
  1352. for(size_t entry = 0; entry < COUNT(script_funcs); entry++) {
  1353. if(ctx->abort) {
  1354. DBGS("aborting");
  1355. break;
  1356. }
  1357. size_t expected = strlen(script_funcs[entry].prefix);
  1358. if(ctx->script_file) {
  1359. storage_file_seek(ctx->script_file, start_pos, true);
  1360. if(storage_file_read(ctx->script_file, buffer, expected) != expected) {
  1361. continue;
  1362. }
  1363. } else {
  1364. ctx->line_pos = start_pos;
  1365. if(strlen(ctx->line_data) < expected) {
  1366. continue;
  1367. }
  1368. strncpy(buffer, ctx->line_data, expected);
  1369. ctx->line_pos += expected;
  1370. }
  1371. buffer[expected] = '\000';
  1372. if(strncmp(buffer, script_funcs[entry].prefix, expected)) {
  1373. continue;
  1374. }
  1375. bool success = true;
  1376. if(ctx->goto_active) {
  1377. DBG("ignore: '%s'", script_funcs[entry].prefix);
  1378. /* only execute label handlers */
  1379. if(buffer[0] == '.') {
  1380. success = script_funcs[entry].func(ctx);
  1381. } else {
  1382. swd_script_seek_newline(ctx);
  1383. }
  1384. } else {
  1385. DBG("command: '%s'", script_funcs[entry].prefix);
  1386. if(!ctx->status_ignore) {
  1387. snprintf(
  1388. ctx->app->state_string,
  1389. sizeof(ctx->app->state_string),
  1390. "CMD: %s",
  1391. script_funcs[entry].prefix);
  1392. }
  1393. swd_script_gui_refresh(ctx);
  1394. /* function, execute */
  1395. success = script_funcs[entry].func(ctx);
  1396. if(!success && !ctx->errors_ignore) {
  1397. swd_script_log(
  1398. ctx, FuriLogLevelError, "Command failed: %s", script_funcs[entry].prefix);
  1399. snprintf(
  1400. ctx->app->state_string,
  1401. sizeof(ctx->app->state_string),
  1402. "Command failed: %s",
  1403. script_funcs[entry].prefix);
  1404. return false;
  1405. }
  1406. }
  1407. return true;
  1408. }
  1409. swd_script_log(ctx, FuriLogLevelError, "unknown command '%s'", buffer);
  1410. return false;
  1411. }
  1412. static bool swd_execute_script(AppFSM* const ctx, const char* filename) {
  1413. bool success = true;
  1414. /* fetch current script and set as parent */
  1415. ScriptContext* parent = ctx->script;
  1416. ctx->script = malloc(sizeof(ScriptContext));
  1417. ctx->script->app = ctx;
  1418. ctx->script->max_tries = 1;
  1419. ctx->script->parent = parent;
  1420. strcpy(ctx->script->filename, filename);
  1421. if(!storage_file_exists(ctx->storage, filename)) {
  1422. DBG("Does not exist '%s'", filename);
  1423. parent = ctx->script->parent;
  1424. free(ctx->script);
  1425. ctx->script = parent;
  1426. return false;
  1427. }
  1428. /* first allocate a file object */
  1429. ctx->script->script_file = storage_file_alloc(ctx->storage);
  1430. /* then get our script opened */
  1431. if(!storage_file_open(ctx->script->script_file, filename, FSAM_READ, FSOM_OPEN_EXISTING)) {
  1432. FURI_LOG_E(TAG, "open, %s", storage_file_get_error_desc(ctx->script->script_file));
  1433. DBG("Failed to open '%s'", filename);
  1434. storage_file_free(ctx->script->script_file);
  1435. parent = ctx->script->parent;
  1436. free(ctx->script);
  1437. ctx->script = parent;
  1438. return false;
  1439. }
  1440. do {
  1441. success = true;
  1442. ctx->script->restart = false;
  1443. storage_file_seek(ctx->script->script_file, 0, true);
  1444. uint32_t line = 1;
  1445. while(line < SCRIPT_MAX_LINES) {
  1446. if(ctx->script->abort) {
  1447. DBGS("Abort requested");
  1448. break;
  1449. }
  1450. if(storage_file_eof(ctx->script->script_file)) {
  1451. break;
  1452. }
  1453. DBG("line %lu", line);
  1454. if(!swd_execute_script_line(ctx->script)) {
  1455. success = false;
  1456. break;
  1457. }
  1458. if(ctx->script->restart) {
  1459. break;
  1460. }
  1461. line++;
  1462. }
  1463. if(ctx->script->restart) {
  1464. DBGS("Restarting");
  1465. } else {
  1466. DBGS("Finished");
  1467. }
  1468. if(line >= SCRIPT_MAX_LINES) {
  1469. success = true;
  1470. char text_buf[128];
  1471. snprintf(text_buf, sizeof(text_buf), "aborting after %d lines", SCRIPT_MAX_LINES);
  1472. DialogMessage* message = dialog_message_alloc();
  1473. dialog_message_set_header(message, "SWD Probe", 16, 2, AlignLeft, AlignTop);
  1474. dialog_message_set_icon(message, &I_app, 3, 2);
  1475. dialog_message_set_text(message, text_buf, 3, 16, AlignLeft, AlignTop);
  1476. dialog_message_set_buttons(message, "Back", NULL, NULL);
  1477. dialog_message_free(message);
  1478. ctx->script->restart = false;
  1479. }
  1480. if(!success) {
  1481. char text_buf[128];
  1482. snprintf(text_buf, sizeof(text_buf), "Line %lu failed:\n%s", line, ctx->state_string);
  1483. DialogMessage* message = dialog_message_alloc();
  1484. dialog_message_set_header(message, "SWD Probe", 16, 2, AlignLeft, AlignTop);
  1485. dialog_message_set_icon(message, &I_app, 3, 2);
  1486. dialog_message_set_text(message, text_buf, 3, 16, AlignLeft, AlignTop);
  1487. dialog_message_set_buttons(message, "Back", "Retry", NULL);
  1488. if(dialog_message_show(ctx->dialogs, message) == DialogMessageButtonCenter) {
  1489. ctx->script->restart = true;
  1490. }
  1491. dialog_message_free(message);
  1492. }
  1493. } while(ctx->script->restart);
  1494. storage_file_close(ctx->script->script_file);
  1495. storage_file_free(ctx->script->script_file);
  1496. parent = ctx->script->parent;
  1497. free(ctx->script);
  1498. ctx->script = parent;
  1499. return success;
  1500. }
  1501. /************************** UI functions **************************/
  1502. #define CANVAS_WIDTH 128
  1503. #define CANVAS_HEIGHT 64
  1504. #define COERCE(d, min, max) \
  1505. do { \
  1506. if(d < (min)) { \
  1507. d = (min); \
  1508. } \
  1509. if(d > (max)) { \
  1510. d = (max); \
  1511. } \
  1512. } while(0)
  1513. #define COERCE_COORDS(x1, y1, x2, y2) \
  1514. do { \
  1515. COERCE(x1, 0, CANVAS_WIDTH); \
  1516. COERCE(x2, 0, CANVAS_WIDTH); \
  1517. COERCE(y1, 0, CANVAS_HEIGHT); \
  1518. COERCE(y1, 0, CANVAS_HEIGHT); \
  1519. } while(0)
  1520. #include "model/model_chip.h"
  1521. static int rotatedVertexCoords[NUM_VERTICES][3];
  1522. static void draw_model(Canvas* const canvas) {
  1523. static float xAngle = 0;
  1524. static float yAngle = 0;
  1525. static float zAngle = 0;
  1526. static float zoom = 0;
  1527. static float speed = 0.6f;
  1528. float cosXAngle = cosf(xAngle);
  1529. float sinXAngle = sinf(xAngle);
  1530. float cosYAngle = cosf(yAngle);
  1531. float sinYAngle = sinf(yAngle);
  1532. float cosZAngle = cosf(zAngle);
  1533. float sinZAngle = sinf(zAngle);
  1534. float sinZoom = 1.2f + sinf(zoom) * 0.25f;
  1535. int centerX = CANVAS_WIDTH / 2;
  1536. int centerY = CANVAS_HEIGHT / 2 + 5;
  1537. for(int i = 0; i < NUM_VERTICES; i++) {
  1538. int x = vertexCoords[i][0] * sinZoom * 16;
  1539. int y = vertexCoords[i][1] * sinZoom * 16;
  1540. int z = vertexCoords[i][2] * sinZoom * 16;
  1541. int y1 = y * cosXAngle - z * sinXAngle;
  1542. int z1 = y * sinXAngle + z * cosXAngle;
  1543. int x2 = x * cosYAngle + z1 * sinYAngle;
  1544. int z2 = -x * sinYAngle + z1 * cosYAngle;
  1545. int x3 = x2 * cosZAngle - y1 * sinZAngle;
  1546. int y3 = x2 * sinZAngle + y1 * cosZAngle;
  1547. rotatedVertexCoords[i][0] = x3 + centerX;
  1548. rotatedVertexCoords[i][1] = y3 + centerY;
  1549. rotatedVertexCoords[i][2] = z2;
  1550. }
  1551. for(size_t i = 0; i < COUNT(edgeIndices); i++) {
  1552. int v1Index = edgeIndices[i][0];
  1553. int v2Index = edgeIndices[i][1];
  1554. int x1 = rotatedVertexCoords[v1Index][0];
  1555. int y1 = rotatedVertexCoords[v1Index][1];
  1556. int x2 = rotatedVertexCoords[v2Index][0];
  1557. int y2 = rotatedVertexCoords[v2Index][1];
  1558. COERCE_COORDS(x1, y1, x2, y2);
  1559. canvas_draw_line(canvas, x1, y1, x2, y2);
  1560. }
  1561. xAngle += speed * 0.02 / sinZoom;
  1562. yAngle += speed * 0.023 / sinZoom;
  1563. zAngle += speed * 0.029 * sinZoom;
  1564. zoom += speed * 0.005;
  1565. }
  1566. static void render_callback(Canvas* const canvas, void* ctx_in) {
  1567. furi_assert(canvas);
  1568. furi_assert(ctx_in);
  1569. AppFSM* ctx = ctx_in;
  1570. DBGS("furi_mutex_acquire");
  1571. furi_mutex_acquire(ctx->gui_mutex, FuriWaitForever);
  1572. char buffer[64];
  1573. int y = 10;
  1574. canvas_draw_frame(canvas, 0, 0, 128, 64);
  1575. canvas_set_font(canvas, FontPrimary);
  1576. DBG("render page %lu (%s)", ctx->mode_page, ctx->detected_device ? "Detected" : "Searching");
  1577. if(!ctx->detected_device) {
  1578. ctx->mode_page = ModePageScan;
  1579. } else if(ctx->mode_page == ModePageScan) {
  1580. ctx->mode_page = ModePageFound;
  1581. }
  1582. /* if seen less than a quarter second ago */
  1583. switch(ctx->mode_page) {
  1584. case ModePageScan: {
  1585. ctx->mode_page = 0;
  1586. draw_model(canvas);
  1587. canvas_draw_str_aligned(canvas, 64, y, AlignCenter, AlignBottom, "Searching");
  1588. y += 14;
  1589. canvas_set_font(canvas, FontSecondary);
  1590. bool info_page = (ctx->loop_count % 500) >= 250;
  1591. if(info_page) {
  1592. canvas_draw_str(canvas, 2, y, "Connect GND with target GND");
  1593. y += 10;
  1594. canvas_draw_str(canvas, 2, y, "and any two GPIOs with pads");
  1595. y += 10;
  1596. canvas_draw_str(canvas, 2, y, "you want to check for SWD");
  1597. canvas_set_font(canvas, FontPrimary);
  1598. canvas_draw_str(canvas, 111, 62, "2/2");
  1599. } else {
  1600. const char* filename = "<none>";
  1601. if(strlen(ctx->script_detected) > 0) {
  1602. const char* slash = strrchr(ctx->script_detected, '/');
  1603. if(slash) {
  1604. filename = &slash[1];
  1605. } else {
  1606. filename = ctx->script_detected;
  1607. }
  1608. }
  1609. canvas_set_font(canvas, FontSecondary);
  1610. canvas_draw_str_aligned(canvas, 64, y, AlignCenter, AlignBottom, "Autoexec Script");
  1611. y += 10;
  1612. canvas_set_font(canvas, FontKeyboard);
  1613. canvas_draw_str_aligned(canvas, 64, y, AlignCenter, AlignBottom, filename);
  1614. y += 16;
  1615. canvas_set_font(canvas, FontSecondary);
  1616. canvas_draw_icon(canvas, 14, y - 5, &I_ButtonUp_7x4);
  1617. canvas_draw_icon(canvas, 78, y - 5, &I_ButtonDown_7x4);
  1618. canvas_draw_str(canvas, 23, y, "Clear");
  1619. canvas_draw_str(canvas, 87, y, "Choose");
  1620. canvas_set_font(canvas, FontPrimary);
  1621. canvas_draw_str(canvas, 111, 62, "1/2");
  1622. }
  1623. canvas_set_font(canvas, FontSecondary);
  1624. elements_button_left(canvas, "Script");
  1625. break;
  1626. }
  1627. case ModePageFound: {
  1628. if((ctx->detected_timeout + TIMER_HZ / 4) >= TIMER_HZ * TIMEOUT) {
  1629. snprintf(buffer, sizeof(buffer), "FOUND!");
  1630. } else {
  1631. /* if it was seen more than a quarter second ago, show countdown */
  1632. snprintf(
  1633. buffer, sizeof(buffer), "FOUND! (%lus)", (ctx->detected_timeout / TIMER_HZ) + 1);
  1634. }
  1635. canvas_draw_str_aligned(canvas, 64, y, AlignCenter, AlignBottom, buffer);
  1636. y += 10;
  1637. canvas_set_font(canvas, FontKeyboard);
  1638. snprintf(
  1639. buffer,
  1640. sizeof(buffer),
  1641. "SWC/SWD: %s/%s",
  1642. gpio_name(ctx->io_swc),
  1643. gpio_name(ctx->io_swd));
  1644. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1645. y += 10;
  1646. snprintf(buffer, sizeof(buffer), "DPIDR 0x%08lX", ctx->dp_regs.dpidr);
  1647. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1648. y += 10;
  1649. snprintf(
  1650. buffer,
  1651. sizeof(buffer),
  1652. "Part %02X Rev %X DAPv%d",
  1653. ctx->dpidr_info.partno,
  1654. ctx->dpidr_info.revision,
  1655. ctx->dpidr_info.version);
  1656. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1657. y += 10;
  1658. canvas_set_font(canvas, FontSecondary);
  1659. snprintf(buffer, sizeof(buffer), "%s", jep106_manufacturer(ctx->dpidr_info.designer));
  1660. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1661. y += 10;
  1662. canvas_set_font(canvas, FontSecondary);
  1663. elements_button_left(canvas, "Script");
  1664. elements_button_right(canvas, "DP Regs");
  1665. break;
  1666. }
  1667. case ModePageDPRegs: {
  1668. canvas_draw_str_aligned(canvas, 64, y, AlignCenter, AlignBottom, "DP Registers");
  1669. y += 10;
  1670. canvas_set_font(canvas, FontKeyboard);
  1671. if(ctx->dp_regs.dpidr_ok) {
  1672. snprintf(buffer, sizeof(buffer), "DPIDR %08lX", ctx->dp_regs.dpidr);
  1673. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1674. }
  1675. y += 10;
  1676. if(ctx->dp_regs.ctrlstat_ok) {
  1677. snprintf(buffer, sizeof(buffer), "CTRL %08lX", ctx->dp_regs.ctrlstat);
  1678. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1679. }
  1680. y += 10;
  1681. if(ctx->dp_regs.targetid_ok) {
  1682. snprintf(buffer, sizeof(buffer), "TGTID %08lX", ctx->dp_regs.targetid);
  1683. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1684. }
  1685. y += 10;
  1686. if(ctx->dp_regs.eventstat_ok) {
  1687. snprintf(buffer, sizeof(buffer), "EVTST %08lX", ctx->dp_regs.eventstat);
  1688. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1689. }
  1690. y += 10;
  1691. canvas_set_font(canvas, FontSecondary);
  1692. elements_button_left(canvas, "Scan");
  1693. elements_button_right(canvas, "DPID");
  1694. break;
  1695. }
  1696. case ModePageDPID: {
  1697. canvas_draw_str_aligned(canvas, 64, y, AlignCenter, AlignBottom, "DP ID Register");
  1698. y += 10;
  1699. canvas_set_font(canvas, FontKeyboard);
  1700. if(ctx->dpidr_info.version != 2) {
  1701. snprintf(buffer, sizeof(buffer), "TARGETID not supported");
  1702. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1703. y += 10;
  1704. } else {
  1705. if(ctx->dp_regs.targetid_ok) {
  1706. snprintf(buffer, sizeof(buffer), "TGTID %08lX", ctx->dp_regs.targetid);
  1707. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1708. y += 10;
  1709. snprintf(buffer, sizeof(buffer), "Part No. %04X", ctx->targetid_info.partno);
  1710. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1711. y += 10;
  1712. snprintf(
  1713. buffer, sizeof(buffer), "%s", jep106_manufacturer(ctx->targetid_info.designer));
  1714. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1715. y += 10;
  1716. }
  1717. }
  1718. canvas_set_font(canvas, FontSecondary);
  1719. elements_button_left(canvas, "DP Regs");
  1720. elements_button_right(canvas, "APs");
  1721. break;
  1722. }
  1723. case ModePageAPID: {
  1724. canvas_draw_str_aligned(canvas, 64, y, AlignCenter, AlignBottom, "AP Menu");
  1725. y += 10;
  1726. canvas_set_font(canvas, FontKeyboard);
  1727. char state = ' ';
  1728. if(ctx->ap_pos >= ctx->ap_scanned && ctx->ap_pos <= ctx->ap_scanned + 10) {
  1729. state = '*';
  1730. }
  1731. if(!ctx->apidr_info[ctx->ap_pos].ok) {
  1732. snprintf(buffer, sizeof(buffer), "[%d]%c<none>", ctx->ap_pos, state);
  1733. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1734. y += 10;
  1735. if(ctx->ap_pos == 0) {
  1736. for(size_t pos = 0; pos < COUNT(ctx->apidr_info); pos++) {
  1737. if(ctx->apidr_info[pos].ok) {
  1738. ctx->ap_pos = pos;
  1739. }
  1740. }
  1741. }
  1742. } else {
  1743. const char* class = "";
  1744. switch(ctx->apidr_info[ctx->ap_pos].class) {
  1745. case 0:
  1746. class = "und";
  1747. break;
  1748. case 1:
  1749. class = "COM";
  1750. break;
  1751. case 8:
  1752. class = "MEM";
  1753. break;
  1754. default:
  1755. class = "unk";
  1756. break;
  1757. }
  1758. const char* types[] = {
  1759. "COM-AP",
  1760. "AHB3",
  1761. "APB2 or APB3",
  1762. "Type unknown",
  1763. "AXI3 or AXI4",
  1764. "AHB5",
  1765. "APB4 and APB5",
  1766. "AXI5",
  1767. "AHB5 enh.",
  1768. };
  1769. const char* type = "Type unk";
  1770. if(ctx->apidr_info[ctx->ap_pos].type < COUNT(types)) {
  1771. type = types[ctx->apidr_info[ctx->ap_pos].type];
  1772. }
  1773. snprintf(buffer, sizeof(buffer), "[%d]%c%s, %s", ctx->ap_pos, state, class, type);
  1774. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1775. y += 10;
  1776. snprintf(buffer, sizeof(buffer), "Base 0x%08lX", ctx->apidr_info[ctx->ap_pos].base);
  1777. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1778. y += 10;
  1779. snprintf(
  1780. buffer,
  1781. sizeof(buffer),
  1782. "Rev %d Var %d",
  1783. ctx->apidr_info[ctx->ap_pos].revision,
  1784. ctx->apidr_info[ctx->ap_pos].variant);
  1785. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1786. y += 10;
  1787. snprintf(
  1788. buffer,
  1789. sizeof(buffer),
  1790. "%s",
  1791. jep106_manufacturer(ctx->apidr_info[ctx->ap_pos].designer));
  1792. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1793. y += 10;
  1794. elements_button_center(canvas, "Show");
  1795. }
  1796. canvas_set_font(canvas, FontSecondary);
  1797. elements_button_left(canvas, "DPID");
  1798. elements_scrollbar_pos(canvas, 4, 10, 40, ctx->ap_pos / 32, COUNT(ctx->apidr_info) / 32);
  1799. break;
  1800. }
  1801. /* hex dump view */
  1802. case ModePageHexDump: {
  1803. canvas_draw_str_aligned(canvas, 64, y, AlignCenter, AlignBottom, "Hex dump");
  1804. y += 10;
  1805. canvas_set_font(canvas, FontKeyboard);
  1806. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, "Addr:");
  1807. snprintf(buffer, sizeof(buffer), "%08lX", ctx->hex_addr);
  1808. canvas_draw_str_aligned(canvas, 38, y, AlignLeft, AlignBottom, buffer);
  1809. uint32_t font_width = canvas_glyph_width(canvas, '0');
  1810. uint32_t x = 37 + (7 - ctx->hex_select) * font_width;
  1811. /* draw selection */
  1812. canvas_draw_line(canvas, x, y + 1, x + font_width, y + 1);
  1813. y += 10;
  1814. uint32_t byte_num = 0;
  1815. for(int line = 0; line < 4; line++) {
  1816. uint32_t x_pos = 5;
  1817. for(int byte_pos = 0; byte_pos < 8; byte_pos++) {
  1818. if(ctx->hex_buffer_valid[byte_num / 4]) {
  1819. snprintf(buffer, sizeof(buffer), "%02X", ctx->hex_buffer[byte_num]);
  1820. } else {
  1821. snprintf(buffer, sizeof(buffer), "--");
  1822. }
  1823. byte_num++;
  1824. canvas_draw_str_aligned(canvas, x_pos, y, AlignLeft, AlignBottom, buffer);
  1825. x_pos += font_width * 2 + font_width / 2;
  1826. }
  1827. y += 10;
  1828. }
  1829. break;
  1830. }
  1831. /* hex dump view */
  1832. case ModePageScript: {
  1833. canvas_draw_str_aligned(canvas, 64, y, AlignCenter, AlignBottom, "Script");
  1834. y += 10;
  1835. y += 10;
  1836. canvas_draw_str_aligned(canvas, 10, y, AlignLeft, AlignBottom, "Status:");
  1837. y += 10;
  1838. canvas_set_font(canvas, FontKeyboard);
  1839. canvas_draw_str_aligned(canvas, 64, y, AlignCenter, AlignBottom, ctx->state_string);
  1840. y += 10;
  1841. break;
  1842. }
  1843. }
  1844. DBGS("furi_mutex_release");
  1845. furi_mutex_release(ctx->gui_mutex);
  1846. }
  1847. static void input_callback(InputEvent* input_event, void* ctx_in) {
  1848. furi_assert(input_event);
  1849. furi_assert(ctx_in);
  1850. AppFSM* ctx = ctx_in;
  1851. DBGS("furi_message_queue_get_count");
  1852. /* better skip than sorry */
  1853. if(furi_message_queue_get_count(ctx->event_queue) < QUEUE_SIZE) {
  1854. DBGS("furi_message_queue_put");
  1855. AppEvent event = {.type = EventKeyPress, .input = *input_event};
  1856. furi_message_queue_put(ctx->event_queue, &event, 100);
  1857. }
  1858. }
  1859. static void timer_tick_callback(void* ctx_in) {
  1860. furi_assert(ctx_in);
  1861. AppFSM* ctx = ctx_in;
  1862. //DBGS("furi_message_queue_get_count");
  1863. /* filling buffer makes no sense, as we lost timing anyway */
  1864. if(furi_message_queue_get_count(ctx->event_queue) < 1) {
  1865. //DBGS("furi_message_queue_put");
  1866. AppEvent event = {.type = EventTimerTick};
  1867. furi_message_queue_put(ctx->event_queue, &event, 100);
  1868. }
  1869. }
  1870. static void app_init(AppFSM* const app) {
  1871. app->loop_count = 0;
  1872. app->current_mask_id = 0;
  1873. app->current_mask = gpio_direction_mask[app->current_mask_id];
  1874. app->io_swd = 0xFF;
  1875. app->io_swc = 0xFF;
  1876. app->hex_addr = 0x40002800;
  1877. app->hex_addr = 0xE000EDF0;
  1878. app->swd_clock_delay = CLOCK_DELAY;
  1879. app->swd_idle_bits = IDLE_BITS;
  1880. strcpy(app->state_string, "none");
  1881. strcpy(app->script_detected, "");
  1882. }
  1883. static void app_deinit(AppFSM* const app) {
  1884. strcpy(app->state_string, "exiting");
  1885. }
  1886. static void on_timer_tick(AppFSM* ctx) {
  1887. ctx->loop_count++;
  1888. switch(ctx->mode_page) {
  1889. case ModePageScan:
  1890. case ModePageFound: {
  1891. /* reset after timeout */
  1892. if(ctx->detected_timeout > 0) {
  1893. ctx->detected_timeout--;
  1894. } else {
  1895. DBGS("Reset detected flag");
  1896. ctx->detected_device = false;
  1897. ctx->io_swd = 0xFF;
  1898. ctx->io_swc = 0xFF;
  1899. ctx->io_num_swd = 0xFF;
  1900. ctx->io_num_swc = 0xFF;
  1901. ctx->ap_scanned = 0;
  1902. memset(&ctx->dp_regs, 0x00, sizeof(ctx->dp_regs));
  1903. memset(&ctx->targetid_info, 0x00, sizeof(ctx->targetid_info));
  1904. memset(&ctx->apidr_info, 0x00, sizeof(ctx->apidr_info));
  1905. ctx->script_detected_executed = false;
  1906. }
  1907. ctx->detected = false;
  1908. ctx->current_mask = gpio_direction_mask[ctx->current_mask_id];
  1909. /* when SWD was already detected, set it to data pin regardless of the mask */
  1910. if(ctx->detected_device) {
  1911. ctx->current_mask &= ~ctx->io_swd;
  1912. }
  1913. /* do the scan */
  1914. furi_mutex_acquire(ctx->swd_mutex, FuriWaitForever);
  1915. swd_scan(ctx);
  1916. furi_mutex_release(ctx->swd_mutex);
  1917. /* now when detected a device, set the timeout */
  1918. if(ctx->detected) {
  1919. DBGS("Set detected flag");
  1920. ctx->detected_device = true;
  1921. ctx->detected_timeout = TIMER_HZ * TIMEOUT;
  1922. /* update DPIDR fields */
  1923. ctx->dpidr_info.revision = (ctx->dp_regs.dpidr >> 28) & 0x0F;
  1924. ctx->dpidr_info.partno = (ctx->dp_regs.dpidr >> 20) & 0xFF;
  1925. ctx->dpidr_info.version = (ctx->dp_regs.dpidr >> 12) & 0x0F;
  1926. ctx->dpidr_info.designer = (ctx->dp_regs.dpidr >> 1) & 0x3FF;
  1927. if(!has_multiple_bits(ctx->io_swc)) {
  1928. DBGS(" - Detected pins");
  1929. DBGS(" - Resetting error");
  1930. furi_mutex_acquire(ctx->swd_mutex, FuriWaitForever);
  1931. /* reset error */
  1932. /* first make sure we have the correct bank by invalidating the current select cache */
  1933. ctx->dp_regs.select_ok = false;
  1934. uint8_t ack =
  1935. swd_read_dpbank(ctx, REG_CTRLSTAT, REG_CTRLSTAT_BANK, &ctx->dp_regs.ctrlstat);
  1936. if(ack != 1 || (ctx->dp_regs.ctrlstat & STAT_ERROR_FLAGS)) {
  1937. DBGS(" - send ABORT");
  1938. swd_abort(ctx);
  1939. }
  1940. DBGS(" - Fetch CTRL/STAT");
  1941. ctx->dp_regs.ctrlstat_ok =
  1942. swd_read_dpbank(
  1943. ctx, REG_CTRLSTAT, REG_CTRLSTAT_BANK, &ctx->dp_regs.ctrlstat) == 1;
  1944. DBG(" %08lX %s",
  1945. ctx->dp_regs.ctrlstat,
  1946. ctx->dp_regs.ctrlstat_ok ? "OK" : "FAIL");
  1947. if(ctx->dpidr_info.version >= 1) {
  1948. DBGS(" - DAPv1, read DLCR");
  1949. ctx->dp_regs.dlcr_ok =
  1950. swd_read_dpbank(ctx, REG_DLCR, REG_DLCR_BANK, &ctx->dp_regs.dlcr) == 1;
  1951. DBG(" %08lX %s", ctx->dp_regs.dlcr, ctx->dp_regs.dlcr_ok ? "OK" : "FAIL");
  1952. }
  1953. if(ctx->dpidr_info.version >= 2) {
  1954. DBGS(" - DAPv2, read TARGETID");
  1955. ctx->dp_regs.targetid_ok =
  1956. swd_read_dpbank(
  1957. ctx, REG_TARGETID, REG_TARGETID_BANK, &ctx->dp_regs.targetid) == 1;
  1958. DBG(" %08lX %s",
  1959. ctx->dp_regs.targetid,
  1960. ctx->dp_regs.targetid_ok ? "OK" : "FAIL");
  1961. DBGS(" - DAPv2, read EVENTSTAT");
  1962. ctx->dp_regs.eventstat_ok =
  1963. swd_read_dpbank(
  1964. ctx, REG_EVENTSTAT, REG_EVENTSTAT_BANK, &ctx->dp_regs.eventstat) == 1;
  1965. DBG(" %08lX %s",
  1966. ctx->dp_regs.eventstat,
  1967. ctx->dp_regs.eventstat_ok ? "OK" : "FAIL");
  1968. DBGS(" - DAPv2, read DLPIDR");
  1969. ctx->dp_regs.dlpidr_ok =
  1970. swd_read_dpbank(ctx, REG_DLPIDR, REG_DLPIDR_BANK, &ctx->dp_regs.dlpidr) ==
  1971. 1;
  1972. DBG(" %08lX %s",
  1973. ctx->dp_regs.dlpidr,
  1974. ctx->dp_regs.dlpidr_ok ? "OK" : "FAIL");
  1975. }
  1976. if(ctx->dp_regs.targetid_ok) {
  1977. ctx->targetid_info.revision = (ctx->dp_regs.targetid >> 28) & 0x0F;
  1978. ctx->targetid_info.partno = (ctx->dp_regs.targetid >> 12) & 0xFFFF;
  1979. ctx->targetid_info.designer = (ctx->dp_regs.targetid >> 1) & 0x3FF;
  1980. }
  1981. if(!ctx->script_detected_executed && strlen(ctx->script_detected) > 0) {
  1982. DBG(" - Run script '%s'", ctx->script_detected);
  1983. ctx->script_detected_executed = true;
  1984. ctx->mode_page = ModePageScript;
  1985. swd_execute_script(ctx, ctx->script_detected);
  1986. ctx->mode_page = ModePageFound;
  1987. }
  1988. furi_mutex_release(ctx->swd_mutex);
  1989. }
  1990. } else {
  1991. if(!has_multiple_bits(ctx->io_swc)) {
  1992. DBGS(" - Lost device");
  1993. }
  1994. }
  1995. ctx->current_mask_id = (ctx->current_mask_id + 1) % COUNT(gpio_direction_mask);
  1996. break;
  1997. }
  1998. case ModePageDPRegs:
  1999. case ModePageDPID:
  2000. case ModePageAPID: {
  2001. furi_mutex_acquire(ctx->swd_mutex, FuriWaitForever);
  2002. /* set debug enable request */
  2003. if(!swd_ensure_powerup(ctx)) {
  2004. furi_mutex_release(ctx->swd_mutex);
  2005. break;
  2006. }
  2007. /* only scan a few APs at once to stay responsive */
  2008. for(int pos = 0; pos < 8; pos++) {
  2009. if(ctx->ap_scanned == 0) {
  2010. swd_apscan_reset(ctx);
  2011. }
  2012. uint8_t ap = ctx->ap_scanned++;
  2013. if(ctx->apidr_info[ap].tested) {
  2014. continue;
  2015. }
  2016. if(swd_apscan_test(ctx, ap)) {
  2017. break;
  2018. }
  2019. }
  2020. furi_mutex_release(ctx->swd_mutex);
  2021. break;
  2022. }
  2023. case ModePageHexDump: {
  2024. if(ctx->hex_read_delay++ < 10) {
  2025. break;
  2026. }
  2027. ctx->hex_read_delay = 0;
  2028. furi_mutex_acquire(ctx->swd_mutex, FuriWaitForever);
  2029. memset(ctx->hex_buffer, 0xEE, sizeof(ctx->hex_buffer));
  2030. uint32_t addr = ctx->hex_addr;
  2031. uint32_t data = 0;
  2032. for(size_t pos = 0; pos < sizeof(ctx->hex_buffer) / 4; pos++) {
  2033. ctx->hex_buffer_valid[pos] = swd_read_memory(ctx, ctx->ap_pos, addr, &data) == 1;
  2034. if(ctx->hex_buffer_valid[pos]) {
  2035. memcpy(&ctx->hex_buffer[pos * 4], &data, 4);
  2036. } else {
  2037. swd_abort_simple(ctx);
  2038. }
  2039. addr += 4;
  2040. }
  2041. furi_mutex_release(ctx->swd_mutex);
  2042. }
  2043. }
  2044. }
  2045. static bool swd_message_process(AppFSM* ctx) {
  2046. bool processing = true;
  2047. AppEvent event;
  2048. FuriStatus event_status = furi_message_queue_get(ctx->event_queue, &event, 100);
  2049. if(event_status == FuriStatusOk) {
  2050. if(event.type == EventKeyPress) {
  2051. if(event.input.type == InputTypePress) {
  2052. switch(event.input.key) {
  2053. case InputKeyUp:
  2054. switch(ctx->mode_page) {
  2055. default:
  2056. break;
  2057. case ModePageScan:
  2058. case ModePageFound: {
  2059. strcpy(ctx->script_detected, "");
  2060. break;
  2061. }
  2062. case ModePageAPID:
  2063. if(ctx->ap_pos > 0) {
  2064. ctx->ap_pos--;
  2065. }
  2066. break;
  2067. case ModePageHexDump: {
  2068. ctx->hex_addr +=
  2069. ((ctx->hex_select) ? 1 : 8) * (1 << (4 * ctx->hex_select));
  2070. break;
  2071. }
  2072. }
  2073. break;
  2074. case InputKeyDown:
  2075. switch(ctx->mode_page) {
  2076. default:
  2077. break;
  2078. case ModePageScan: {
  2079. FuriString* result_path = furi_string_alloc_printf(ANY_PATH("swd"));
  2080. FuriString* preselected = furi_string_alloc_printf(
  2081. (strlen(ctx->script_detected) > 0) ? ctx->script_detected :
  2082. ANY_PATH("swd"));
  2083. DialogsFileBrowserOptions options;
  2084. dialog_file_browser_set_basic_options(&options, "swd", &I_swd);
  2085. if(dialog_file_browser_show(
  2086. ctx->dialogs, result_path, preselected, &options)) {
  2087. const char* path = furi_string_get_cstr(result_path);
  2088. strcpy(ctx->script_detected, path);
  2089. }
  2090. furi_string_free(result_path);
  2091. furi_string_free(preselected);
  2092. break;
  2093. }
  2094. case ModePageAPID:
  2095. if(ctx->ap_pos + 1U < COUNT(ctx->apidr_info)) {
  2096. ctx->ap_pos++;
  2097. }
  2098. break;
  2099. case ModePageHexDump: {
  2100. ctx->hex_addr -=
  2101. ((ctx->hex_select) ? 1 : 8) * (1 << (4 * ctx->hex_select));
  2102. break;
  2103. }
  2104. }
  2105. break;
  2106. case InputKeyRight:
  2107. if(ctx->mode_page == ModePageHexDump) {
  2108. if(ctx->hex_select > 0) {
  2109. ctx->hex_select--;
  2110. }
  2111. } else if(ctx->detected) {
  2112. if(ctx->mode_page + 1 < ModePageCount) {
  2113. ctx->mode_page++;
  2114. }
  2115. }
  2116. break;
  2117. case InputKeyLeft:
  2118. if(ctx->mode_page == ModePageHexDump) {
  2119. if(ctx->hex_select < 7) {
  2120. ctx->hex_select++;
  2121. }
  2122. } else if((ctx->mode_page == ModePageScan) || (ctx->mode_page == ModePageFound)) {
  2123. uint32_t mode_page = ctx->mode_page;
  2124. FuriString* result_path = furi_string_alloc_printf(ANY_PATH("swd"));
  2125. FuriString* preselected = furi_string_alloc_printf(
  2126. (strlen(ctx->script_detected) > 0) ? ctx->script_detected :
  2127. ANY_PATH("swd"));
  2128. DialogsFileBrowserOptions options;
  2129. dialog_file_browser_set_basic_options(&options, "swd", &I_swd);
  2130. if(dialog_file_browser_show(
  2131. ctx->dialogs, result_path, preselected, &options)) {
  2132. const char* path = furi_string_get_cstr(result_path);
  2133. ctx->mode_page = ModePageScript;
  2134. swd_execute_script(ctx, path);
  2135. ctx->mode_page = mode_page;
  2136. }
  2137. furi_string_free(result_path);
  2138. furi_string_free(preselected);
  2139. break;
  2140. } else {
  2141. if(ctx->mode_page > 0) {
  2142. ctx->mode_page--;
  2143. }
  2144. }
  2145. break;
  2146. case InputKeyOk:
  2147. if(ctx->mode_page == ModePageAPID && ctx->apidr_info[ctx->ap_pos].ok) {
  2148. ctx->mode_page = ModePageHexDump;
  2149. }
  2150. break;
  2151. case InputKeyBack:
  2152. if(ctx->mode_page == ModePageHexDump) {
  2153. ctx->mode_page = ModePageAPID;
  2154. } else if(ctx->mode_page == ModePageScript) {
  2155. ctx->script->abort = true;
  2156. } else if(ctx->mode_page > ModePageFound) {
  2157. ctx->mode_page = ModePageScan;
  2158. } else if(ctx->mode_page == ModePageScan) {
  2159. processing = false;
  2160. } else if(ctx->mode_page == ModePageFound) {
  2161. processing = false;
  2162. }
  2163. break;
  2164. default:
  2165. break;
  2166. }
  2167. }
  2168. } else if(event.type == EventTimerTick) {
  2169. on_timer_tick(ctx);
  2170. }
  2171. } else {
  2172. /* timeout */
  2173. }
  2174. return processing;
  2175. }
  2176. size_t data_received(void* ctx, uint8_t* data, size_t length) {
  2177. AppFSM* app = (AppFSM*)ctx;
  2178. strncpy(app->commandline->line_data, (const char*)data, length);
  2179. app->commandline->line_pos = 0;
  2180. for(size_t pos = 0; pos < length; pos++) {
  2181. uint8_t ch = app->commandline->line_data[pos];
  2182. if((ch == '\r') || (ch == '\n')) {
  2183. app->commandline->line_data[pos++] = '\n';
  2184. app->commandline->line_data[pos] = 0;
  2185. LOG("direct command '%s'", app->commandline->line_data);
  2186. swd_execute_script_line(app->commandline);
  2187. return pos;
  2188. }
  2189. }
  2190. return 0;
  2191. }
  2192. int32_t swd_probe_app_main(void* p) {
  2193. UNUSED(p);
  2194. AppFSM* app = malloc(sizeof(AppFSM));
  2195. DBGS("App init");
  2196. app_init(app);
  2197. DBGS("furi_record_open");
  2198. app->notification = furi_record_open(RECORD_NOTIFICATION);
  2199. app->gui = furi_record_open(RECORD_GUI);
  2200. app->dialogs = furi_record_open(RECORD_DIALOGS);
  2201. app->storage = furi_record_open(RECORD_STORAGE);
  2202. DBGS("furi_mutex_alloc");
  2203. app->swd_mutex = furi_mutex_alloc(FuriMutexTypeNormal);
  2204. app->gui_mutex = furi_mutex_alloc(FuriMutexTypeNormal);
  2205. app->event_queue = furi_message_queue_alloc(QUEUE_SIZE, sizeof(AppEvent));
  2206. DBGS("usb_uart_enable");
  2207. UsbUartConfig uart_config;
  2208. uart_config.vcp_ch = 1;
  2209. uart_config.rx_data = &data_received;
  2210. uart_config.rx_data_ctx = app;
  2211. app->uart = usb_uart_enable(&uart_config);
  2212. app->commandline = malloc(sizeof(ScriptContext));
  2213. app->commandline->max_tries = 1;
  2214. app->commandline->app = app;
  2215. DBGS("view_port_alloc");
  2216. app->view_port = view_port_alloc();
  2217. view_port_draw_callback_set(app->view_port, render_callback, app);
  2218. view_port_input_callback_set(app->view_port, input_callback, app);
  2219. gui_add_view_port(app->gui, app->view_port, GuiLayerFullscreen);
  2220. DBGS("furi_timer_alloc");
  2221. app->timer = furi_timer_alloc(timer_tick_callback, FuriTimerTypePeriodic, app);
  2222. furi_timer_start(app->timer, furi_kernel_get_tick_frequency() / TIMER_HZ);
  2223. DBGS("notification_message_block");
  2224. notification_message(app->notification, &sequence_display_backlight_enforce_on);
  2225. DBGS("swd_execute_script");
  2226. swd_execute_script(app, ANY_PATH("swd/startup.swd"));
  2227. DOLPHIN_DEED(DolphinDeedPluginGameStart);
  2228. DBGS("processing");
  2229. for(bool processing = true; processing;) {
  2230. processing = swd_message_process(app);
  2231. view_port_update(app->view_port);
  2232. bool beep = false;
  2233. if(app->detected_device && !app->detected_notified) {
  2234. app->detected_notified = true;
  2235. beep = true;
  2236. }
  2237. if(!app->detected_device && app->detected_notified) {
  2238. app->detected_notified = false;
  2239. }
  2240. if(beep) {
  2241. notification_message_block(app->notification, &seq_c_minor);
  2242. }
  2243. }
  2244. app_deinit(app);
  2245. furi_timer_free(app->timer);
  2246. notification_message(app->notification, &sequence_display_backlight_enforce_auto);
  2247. usb_uart_disable(app->uart);
  2248. view_port_enabled_set(app->view_port, false);
  2249. gui_remove_view_port(app->gui, app->view_port);
  2250. view_port_free(app->view_port);
  2251. furi_message_queue_free(app->event_queue);
  2252. furi_mutex_free(app->gui_mutex);
  2253. furi_mutex_free(app->swd_mutex);
  2254. free(app);
  2255. furi_record_close(RECORD_GUI);
  2256. furi_record_close(RECORD_NOTIFICATION);
  2257. furi_record_close(RECORD_DIALOGS);
  2258. furi_record_close(RECORD_STORAGE);
  2259. return 0;
  2260. }