swd_probe_app.c 70 KB

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