swd_probe_app.c 72 KB

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