swd_probe_app.c 81 KB

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