swd_probe_app.c 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294
  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. /* short debug message */
  15. #define DBGS(format) furi_log_print_format(FuriLogLevelDebug, TAG, "%s: " format, __FUNCTION__)
  16. /* formatted debug message */
  17. #define DBG(format, ...) \
  18. furi_log_print_format(FuriLogLevelDebug, TAG, "%s: " format, __FUNCTION__, __VA_ARGS__)
  19. /* log message*/
  20. #define LOG(...) furi_log_print_format(FuriLogLevelDefault, TAG, __VA_ARGS__)
  21. #define COUNT(x) ((size_t)(sizeof(x) / sizeof((x)[0])))
  22. static void render_callback(Canvas* const canvas, void* cb_ctx);
  23. static bool swd_message_process(AppFSM* ctx);
  24. static uint8_t swd_transfer(AppFSM* const ctx, bool ap, bool write, uint8_t a23, uint32_t* data);
  25. static bool swd_execute_script(AppFSM* const ctx, const char* filename);
  26. static const GpioPin* gpios[] = {
  27. &gpio_ext_pc0,
  28. &gpio_ext_pc1,
  29. &gpio_ext_pc3,
  30. &gpio_ext_pb2,
  31. &gpio_ext_pb3,
  32. &gpio_ext_pa4,
  33. &gpio_ext_pa6,
  34. &gpio_ext_pa7};
  35. static const char* gpio_names[] = {"PC0", "PC1", "PC3", "PB2", "PB3", "PA4", "PA6", "PA7"};
  36. /* bit set: clock, else data */
  37. static const uint8_t gpio_direction_mask[6] =
  38. {0b10101010, 0b01010101, 0b11001100, 0b00110011, 0b11110000, 0b00001111};
  39. static const uint8_t gpio_direction_ind[6] = "-\\||/-";
  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 = 0x23000002;
  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. DBGS(" - Fetch CTRL/STAT");
  487. ctx->dp_regs.ctrlstat_ok =
  488. swd_read_dpbank(ctx, REG_CTRLSTAT, REG_CTRLSTAT_BANK, &ctx->dp_regs.ctrlstat) == 1;
  489. DBG(" %08lX %s", ctx->dp_regs.ctrlstat, ctx->dp_regs.ctrlstat_ok ? "OK" : "FAIL");
  490. return ret;
  491. }
  492. static void swd_apscan_reset(AppFSM* const ctx) {
  493. for(size_t reset_ap = 0; reset_ap < COUNT(ctx->apidr_info); reset_ap++) {
  494. ctx->apidr_info[reset_ap].tested = false;
  495. }
  496. }
  497. static bool swd_apscan_test(AppFSM* const ctx, uint32_t ap) {
  498. furi_assert(ctx);
  499. furi_assert(ap < sizeof(ctx->apidr_info));
  500. ctx->apidr_info[ap].tested = true;
  501. uint32_t data = 0;
  502. if(swd_read_ap(ctx, ap, AP_IDR, &data) != 1) {
  503. swd_abort(ctx);
  504. return false;
  505. }
  506. if(data == 0) {
  507. return false;
  508. }
  509. DBG("AP%lu detected", ap);
  510. ctx->apidr_info[ap].ok = true;
  511. ctx->apidr_info[ap].revision = (data >> 24) & 0x0F;
  512. ctx->apidr_info[ap].designer = (data >> 17) & 0x3FF;
  513. ctx->apidr_info[ap].class = (data >> 13) & 0x0F;
  514. ctx->apidr_info[ap].variant = (data >> 4) & 0x0F;
  515. ctx->apidr_info[ap].type = (data >> 0) & 0x0F;
  516. if(swd_read_ap(ctx, ap, AP_BASE, &ctx->apidr_info[ap].base) != 1) {
  517. swd_abort(ctx);
  518. return false;
  519. }
  520. return true;
  521. }
  522. /************************** script helpers **************************/
  523. static bool swd_script_seek_newline(ScriptContext* ctx) {
  524. while(true) {
  525. uint8_t ch = 0;
  526. uint16_t ret = storage_file_read(ctx->script_file, &ch, 1);
  527. if(ret != 1) {
  528. return false;
  529. }
  530. if(ch == '\n') {
  531. return true;
  532. }
  533. }
  534. }
  535. static bool swd_script_skip_whitespace(ScriptContext* ctx) {
  536. while(true) {
  537. uint8_t ch = 0;
  538. uint64_t start_pos = storage_file_tell(ctx->script_file);
  539. uint16_t ret = storage_file_read(ctx->script_file, &ch, 1);
  540. if(ret != 1) {
  541. return false;
  542. }
  543. if(ch == '\n') {
  544. return false;
  545. }
  546. if(ch != ' ') {
  547. storage_file_seek(ctx->script_file, start_pos, true);
  548. return true;
  549. }
  550. }
  551. }
  552. static bool swd_script_get_string(ScriptContext* ctx, char* str, size_t max_length) {
  553. bool quot = false;
  554. size_t pos = 0;
  555. str[pos] = '\000';
  556. while(true) {
  557. char ch = 0;
  558. uint64_t start_pos = storage_file_tell(ctx->script_file);
  559. uint16_t ret = storage_file_read(ctx->script_file, &ch, 1);
  560. if(ret != 1) {
  561. DBGS("end reached?");
  562. return false;
  563. }
  564. if(ch == '"') {
  565. quot = !quot;
  566. continue;
  567. }
  568. if(!quot) {
  569. if(ch == ' ') {
  570. break;
  571. }
  572. if(ch == '\r' || ch == '\n') {
  573. storage_file_seek(ctx->script_file, start_pos, true);
  574. break;
  575. }
  576. }
  577. if(pos + 2 > max_length) {
  578. DBGS("too long");
  579. return false;
  580. }
  581. str[pos++] = ch;
  582. str[pos] = '\000';
  583. }
  584. DBG("got '%s'", str);
  585. return true;
  586. }
  587. static bool swd_script_get_number(ScriptContext* ctx, uint32_t* number) {
  588. char str[16];
  589. if(!swd_script_get_string(ctx, str, sizeof(str))) {
  590. DBGS("could not get string");
  591. return false;
  592. }
  593. DBG("got '%s'", str);
  594. size_t pos = 0;
  595. *number = 0;
  596. /* hex number? */
  597. if(!strncmp(str, "0x", 2)) {
  598. pos += 2;
  599. while(str[pos]) {
  600. uint8_t ch = str[pos++];
  601. uint8_t ch_num = ch - '0';
  602. uint8_t ch_hex = (ch & ~0x20) - 'A';
  603. *number <<= 4;
  604. if(ch_num <= 10) {
  605. *number += ch_num;
  606. } else if(ch_hex <= 5) {
  607. *number += 10 + ch_hex;
  608. } else {
  609. return false;
  610. }
  611. }
  612. } else {
  613. while(str[pos]) {
  614. uint8_t ch = str[pos++];
  615. uint8_t ch_num = ch - '0';
  616. *number *= 10;
  617. if(ch_num < 10) {
  618. *number += ch_num;
  619. } else {
  620. return false;
  621. }
  622. }
  623. }
  624. return true;
  625. }
  626. static void swd_script_gui_refresh(ScriptContext* ctx) {
  627. if(furi_message_queue_get_count(ctx->app->event_queue) > 0) {
  628. swd_message_process(ctx->app);
  629. }
  630. if(!ctx->status_ignore) {
  631. DBG("Status: %s", ctx->app->state_string);
  632. view_port_update(ctx->app->view_port);
  633. }
  634. }
  635. /************************** script functions **************************/
  636. static bool swd_scriptfunc_comment(ScriptContext* ctx) {
  637. DBGS("comment");
  638. swd_script_seek_newline(ctx);
  639. return true;
  640. }
  641. static bool swd_scriptfunc_label(ScriptContext* ctx) {
  642. char label[256];
  643. DBGS("label");
  644. swd_script_skip_whitespace(ctx);
  645. if(!swd_script_get_string(ctx, label, sizeof(label))) {
  646. DBGS("failed to parse");
  647. return false;
  648. }
  649. if(!strcmp(label, ctx->goto_label)) {
  650. ctx->goto_active = false;
  651. DBG("matches '%s'", ctx->goto_label);
  652. }
  653. swd_script_seek_newline(ctx);
  654. return true;
  655. }
  656. static bool swd_scriptfunc_goto(ScriptContext* ctx) {
  657. DBGS("goto");
  658. swd_script_skip_whitespace(ctx);
  659. if(!swd_script_get_string(ctx, ctx->goto_label, sizeof(ctx->goto_label))) {
  660. DBGS("failed to parse");
  661. return false;
  662. }
  663. /* start from beginning and rerun starting from label */
  664. ctx->goto_active = true;
  665. ctx->restart = true;
  666. swd_script_seek_newline(ctx);
  667. return true;
  668. }
  669. static bool swd_scriptfunc_call(ScriptContext* ctx) {
  670. DBGS("call");
  671. swd_script_skip_whitespace(ctx);
  672. /* fetch previous file directory */
  673. char filename[MAX_FILE_LENGTH];
  674. strncpy(filename, ctx->filename, sizeof(filename));
  675. char* path = strrchr(filename, '/');
  676. path[1] = '\000';
  677. /* append filename */
  678. if(!swd_script_get_string(ctx, &path[1], sizeof(filename) - strlen(path))) {
  679. DBGS("failed to parse");
  680. return false;
  681. }
  682. swd_script_seek_newline(ctx);
  683. /* append extension */
  684. if(strlen(filename) + 5 >= sizeof(filename)) {
  685. DBGS("name too long");
  686. return false;
  687. }
  688. strcat(filename, ".swd");
  689. bool ret = swd_execute_script(ctx->app, filename);
  690. if(!ret) {
  691. DBG("failed to exec '%s'", filename);
  692. return false;
  693. }
  694. return true;
  695. }
  696. static bool swd_scriptfunc_status(ScriptContext* ctx) {
  697. uint32_t status = 1;
  698. DBGS("status");
  699. swd_script_skip_whitespace(ctx);
  700. swd_script_get_number(ctx, &status);
  701. ctx->status_ignore = status == 0;
  702. swd_script_seek_newline(ctx);
  703. return true;
  704. }
  705. static bool swd_scriptfunc_errors(ScriptContext* ctx) {
  706. char type[32];
  707. DBGS("errors");
  708. swd_script_skip_whitespace(ctx);
  709. if(!swd_script_get_string(ctx, type, sizeof(type))) {
  710. DBGS("failed to parse");
  711. return false;
  712. }
  713. if(!strcmp(type, "ignore")) {
  714. ctx->errors_ignore = true;
  715. }
  716. if(!strcmp(type, "fail")) {
  717. ctx->errors_ignore = false;
  718. }
  719. swd_script_seek_newline(ctx);
  720. return true;
  721. }
  722. static bool swd_scriptfunc_beep(ScriptContext* ctx) {
  723. uint32_t sound = 0;
  724. DBGS("beep");
  725. swd_script_skip_whitespace(ctx);
  726. swd_script_get_number(ctx, &sound);
  727. notification_message_block(ctx->app->notification, seq_sounds[sound]);
  728. swd_script_seek_newline(ctx);
  729. return true;
  730. }
  731. static bool swd_scriptfunc_message(ScriptContext* ctx) {
  732. uint32_t wait_time = 0;
  733. char message[256];
  734. char type[256];
  735. bool success = true;
  736. bool show_dialog = false;
  737. if(!swd_script_skip_whitespace(ctx)) {
  738. DBGS("missing whitespace");
  739. return false;
  740. }
  741. if(!swd_script_get_number(ctx, &wait_time)) {
  742. DBGS("failed to parse wait_time");
  743. return false;
  744. }
  745. if(!swd_script_get_string(ctx, message, sizeof(message))) {
  746. DBGS("failed to parse message");
  747. return false;
  748. }
  749. if(swd_script_get_string(ctx, type, sizeof(type))) {
  750. if(!strcmp(type, "dialog")) {
  751. show_dialog = true;
  752. }
  753. }
  754. if(wait_time <= 60 * 1000) {
  755. strcpy(ctx->app->state_string, message);
  756. swd_script_gui_refresh(ctx);
  757. furi_delay_ms(wait_time);
  758. if(show_dialog) {
  759. DialogMessage* message = dialog_message_alloc();
  760. dialog_message_set_header(message, "SWD Probe", 16, 2, AlignLeft, AlignTop);
  761. dialog_message_set_icon(message, &I_app, 3, 2);
  762. dialog_message_set_text(message, ctx->app->state_string, 3, 16, AlignLeft, AlignTop);
  763. dialog_message_set_buttons(message, "Abort", "Ok", NULL);
  764. success = dialog_message_show(ctx->app->dialogs, message) == DialogMessageButtonCenter;
  765. dialog_message_free(message);
  766. }
  767. }
  768. swd_script_seek_newline(ctx);
  769. return success;
  770. }
  771. static bool swd_scriptfunc_swd_idle_bits(ScriptContext* ctx) {
  772. uint32_t swd_idle_bits = 0;
  773. if(!swd_script_skip_whitespace(ctx)) {
  774. DBGS("missing whitespace");
  775. return false;
  776. }
  777. if(!swd_script_get_number(ctx, &swd_idle_bits)) {
  778. DBGS("failed to parse");
  779. return false;
  780. }
  781. if(swd_idle_bits <= 32) {
  782. ctx->app->swd_idle_bits = swd_idle_bits;
  783. } else {
  784. DBGS("value must be between 1 and 32");
  785. }
  786. swd_script_seek_newline(ctx);
  787. return true;
  788. }
  789. static bool swd_scriptfunc_swd_clock_delay(ScriptContext* ctx) {
  790. uint32_t swd_clock_delay = 0;
  791. if(!swd_script_skip_whitespace(ctx)) {
  792. DBGS("missing whitespace");
  793. return false;
  794. }
  795. if(!swd_script_get_number(ctx, &swd_clock_delay)) {
  796. DBGS("failed to parse");
  797. return false;
  798. }
  799. if(swd_clock_delay <= 1000000) {
  800. ctx->app->swd_clock_delay = swd_clock_delay;
  801. } else {
  802. DBGS("value must be between 1 and 1000000");
  803. }
  804. swd_script_seek_newline(ctx);
  805. return true;
  806. }
  807. static bool swd_scriptfunc_maxtries(ScriptContext* ctx) {
  808. uint32_t max_tries = 0;
  809. if(!swd_script_skip_whitespace(ctx)) {
  810. DBGS("missing whitespace");
  811. return false;
  812. }
  813. if(!swd_script_get_number(ctx, &max_tries)) {
  814. DBGS("failed to parse");
  815. return false;
  816. }
  817. if(max_tries >= 1 && max_tries <= 1024) {
  818. ctx->max_tries = max_tries;
  819. } else {
  820. DBGS("value must be between 1 and 1024");
  821. }
  822. swd_script_seek_newline(ctx);
  823. return true;
  824. }
  825. static bool swd_scriptfunc_blocksize(ScriptContext* ctx) {
  826. uint32_t block_size = 0;
  827. if(!swd_script_skip_whitespace(ctx)) {
  828. DBGS("missing whitespace");
  829. return false;
  830. }
  831. if(!swd_script_get_number(ctx, &block_size)) {
  832. DBGS("failed to parse");
  833. return false;
  834. }
  835. if(block_size >= 4 && block_size <= 0x1000) {
  836. ctx->block_size = block_size;
  837. } else {
  838. DBGS("value must be between 4 and 4096");
  839. }
  840. swd_script_seek_newline(ctx);
  841. return true;
  842. }
  843. static bool swd_scriptfunc_apselect(ScriptContext* ctx) {
  844. uint32_t ap = 0;
  845. if(!swd_script_skip_whitespace(ctx)) {
  846. DBGS("missing whitespace");
  847. return false;
  848. }
  849. if(!swd_script_get_number(ctx, &ap)) {
  850. DBGS("failed to parse");
  851. return false;
  852. }
  853. if(!swd_apscan_test(ctx->app, ap)) {
  854. DBGS("no selected AP");
  855. return false;
  856. }
  857. ctx->selected_ap = ap;
  858. swd_script_seek_newline(ctx);
  859. return true;
  860. }
  861. static bool swd_scriptfunc_apscan(ScriptContext* ctx) {
  862. DBGS("Scanning APs");
  863. for(uint32_t ap = 0; ap < 255; ap++) {
  864. snprintf(ctx->app->state_string, sizeof(ctx->app->state_string), "Scan AP %lu", ap);
  865. swd_script_gui_refresh(ctx);
  866. if(swd_apscan_test(ctx->app, ap)) {
  867. DBG(" AP%lu detected", ap);
  868. }
  869. }
  870. swd_script_seek_newline(ctx);
  871. return true;
  872. }
  873. static bool swd_scriptfunc_abort(ScriptContext* ctx) {
  874. DBGS("Aborting");
  875. swd_abort(ctx->app);
  876. swd_script_seek_newline(ctx);
  877. return true;
  878. }
  879. static bool swd_scriptfunc_mem_dump(ScriptContext* ctx) {
  880. char filename[MAX_FILE_LENGTH];
  881. uint32_t address = 0;
  882. uint32_t length = 0;
  883. uint32_t flags = 0;
  884. bool success = true;
  885. /* get file */
  886. if(!swd_script_skip_whitespace(ctx)) {
  887. DBGS("missing whitespace");
  888. return false;
  889. }
  890. if(!swd_script_get_string(ctx, filename, sizeof(filename))) {
  891. DBGS("failed to parse filename");
  892. return false;
  893. }
  894. /* get address */
  895. if(!swd_script_get_number(ctx, &address)) {
  896. DBGS("failed to parse address");
  897. return false;
  898. }
  899. /* get length */
  900. if(!swd_script_get_number(ctx, &length)) {
  901. DBGS("failed to parse length");
  902. return false;
  903. }
  904. /* get flags */
  905. if(swd_script_get_number(ctx, &flags)) {
  906. DBGS("found extra flags");
  907. }
  908. LOG("would dump %08lX, len %08lX into %s", address, length, filename);
  909. File* dump = storage_file_alloc(ctx->app->storage);
  910. if(!storage_file_open(dump, filename, FSAM_WRITE, FSOM_CREATE_ALWAYS)) {
  911. storage_file_free(dump);
  912. snprintf(ctx->app->state_string, sizeof(ctx->app->state_string), "Failed to create file");
  913. swd_script_gui_refresh(ctx);
  914. notification_message_block(ctx->app->notification, &seq_error);
  915. return false;
  916. }
  917. if(ctx->block_size == 0) {
  918. ctx->block_size = 0x100;
  919. }
  920. if(ctx->block_size > 0x1000) {
  921. ctx->block_size = 0x1000;
  922. }
  923. uint8_t* buffer = malloc(ctx->block_size);
  924. for(uint32_t pos = 0; pos < length; pos += ctx->block_size) {
  925. if((pos & 0xFF) == 0) {
  926. int pct = pos * 100 / length;
  927. snprintf(
  928. ctx->app->state_string,
  929. sizeof(ctx->app->state_string),
  930. "Dump %08lX (%d%%)",
  931. pos,
  932. pct);
  933. swd_script_gui_refresh(ctx);
  934. }
  935. bool read_ok = false;
  936. for(uint32_t tries = 0; tries < ctx->max_tries; tries++) {
  937. if(ctx->abort) {
  938. DBGS("aborting read");
  939. break;
  940. }
  941. uint32_t ret = 0;
  942. if(ctx->block_size > 4) {
  943. ret = swd_read_memory_block(
  944. ctx->app, ctx->selected_ap, address + pos, buffer, ctx->block_size);
  945. } else {
  946. ret =
  947. swd_read_memory(ctx->app, ctx->selected_ap, address + pos, (uint32_t*)buffer);
  948. }
  949. read_ok = (ret == 1);
  950. if(!read_ok) {
  951. snprintf(
  952. ctx->app->state_string,
  953. sizeof(ctx->app->state_string),
  954. "Failed at 0x%08lX",
  955. address + pos);
  956. swd_script_gui_refresh(ctx);
  957. furi_delay_ms(100);
  958. } else {
  959. break;
  960. }
  961. }
  962. if(ctx->abort) {
  963. DBGS("aborting");
  964. break;
  965. }
  966. if(!read_ok) {
  967. /* flags == 1: "continue reading even if it fails" */
  968. /* flags == 2: "its okay if cannot dump fully" */
  969. if(flags & 1) {
  970. /* set all content to a known value as indication */
  971. for(size_t fill_pos = 0; fill_pos < ctx->block_size; fill_pos += 4) {
  972. *((uint32_t*)&buffer[fill_pos]) = 0xDEADFACE;
  973. }
  974. } else if(flags & 2) {
  975. success = (pos > 0);
  976. break;
  977. } else {
  978. notification_message_block(ctx->app->notification, &seq_error);
  979. success = false;
  980. break;
  981. }
  982. }
  983. storage_file_write(dump, buffer, ctx->block_size);
  984. }
  985. storage_file_close(dump);
  986. swd_script_seek_newline(ctx);
  987. free(buffer);
  988. return success;
  989. }
  990. static bool swd_scriptfunc_mem_write(ScriptContext* ctx) {
  991. uint32_t address = 0;
  992. uint32_t data = 0;
  993. bool success = true;
  994. /* get file */
  995. if(!swd_script_skip_whitespace(ctx)) {
  996. DBGS("missing whitespace");
  997. return false;
  998. }
  999. /* get address */
  1000. if(!swd_script_get_number(ctx, &address)) {
  1001. DBGS("failed to parse 1");
  1002. return false;
  1003. }
  1004. /* get data */
  1005. if(!swd_script_get_number(ctx, &data)) {
  1006. DBGS("failed to parse 2");
  1007. return false;
  1008. }
  1009. DBG("write %08lX to %08lX", data, address);
  1010. bool access_ok = false;
  1011. for(uint32_t tries = 0; tries < ctx->max_tries; tries++) {
  1012. if(ctx->abort) {
  1013. DBGS("aborting");
  1014. break;
  1015. }
  1016. access_ok = swd_write_memory(ctx->app, ctx->selected_ap, address, data) == 1;
  1017. access_ok |= ctx->errors_ignore;
  1018. swd_read_memory(ctx->app, ctx->selected_ap, address, &data);
  1019. DBG("read %08lX from %08lX", data, address);
  1020. if(!access_ok) {
  1021. snprintf(
  1022. ctx->app->state_string,
  1023. sizeof(ctx->app->state_string),
  1024. "Failed write 0x%08lX",
  1025. address);
  1026. swd_script_gui_refresh(ctx);
  1027. }
  1028. }
  1029. if(!access_ok) {
  1030. notification_message_block(ctx->app->notification, &seq_error);
  1031. success = false;
  1032. }
  1033. swd_script_seek_newline(ctx);
  1034. return success;
  1035. }
  1036. static bool swd_scriptfunc_mem_ldmst(ScriptContext* ctx) {
  1037. uint32_t address = 0;
  1038. uint32_t data = 0;
  1039. uint32_t mask = 0;
  1040. bool success = true;
  1041. /* get file */
  1042. if(!swd_script_skip_whitespace(ctx)) {
  1043. DBGS("missing whitespace");
  1044. return false;
  1045. }
  1046. /* get address */
  1047. if(!swd_script_get_number(ctx, &address)) {
  1048. DBGS("failed to parse 1");
  1049. return false;
  1050. }
  1051. /* get data */
  1052. if(!swd_script_get_number(ctx, &data)) {
  1053. DBGS("failed to parse 2");
  1054. return false;
  1055. }
  1056. /* get mask */
  1057. if(!swd_script_get_number(ctx, &mask)) {
  1058. DBGS("failed to parse 2");
  1059. return false;
  1060. }
  1061. LOG("write %08lX to %08lX, mask %08lX", data, address, mask);
  1062. bool access_ok = false;
  1063. uint32_t modified = 0;
  1064. for(uint32_t tries = 0; tries < ctx->max_tries; tries++) {
  1065. if(ctx->abort) {
  1066. DBGS("aborting");
  1067. break;
  1068. }
  1069. access_ok = swd_read_memory(ctx->app, ctx->selected_ap, address, &modified) == 1;
  1070. modified = (modified & mask) | data;
  1071. access_ok &= swd_write_memory(ctx->app, ctx->selected_ap, address, modified) == 1;
  1072. access_ok |= ctx->errors_ignore;
  1073. if(!access_ok) {
  1074. snprintf(
  1075. ctx->app->state_string,
  1076. sizeof(ctx->app->state_string),
  1077. "Failed access 0x%08lX",
  1078. address);
  1079. swd_script_gui_refresh(ctx);
  1080. }
  1081. }
  1082. if(!access_ok) {
  1083. notification_message_block(ctx->app->notification, &seq_error);
  1084. success = false;
  1085. }
  1086. swd_script_seek_newline(ctx);
  1087. return success;
  1088. }
  1089. static const ScriptFunctionInfo script_funcs[] = {
  1090. {"#", &swd_scriptfunc_comment},
  1091. {".label", &swd_scriptfunc_label},
  1092. {"goto", &swd_scriptfunc_goto},
  1093. {"call", &swd_scriptfunc_call},
  1094. {"status", &swd_scriptfunc_status},
  1095. {"errors", &swd_scriptfunc_errors},
  1096. {"message", &swd_scriptfunc_message},
  1097. {"beep", &swd_scriptfunc_beep},
  1098. {"apscan", &swd_scriptfunc_apscan},
  1099. {"apselect", &swd_scriptfunc_apselect},
  1100. {"max_tries", &swd_scriptfunc_maxtries},
  1101. {"swd_clock_delay", &swd_scriptfunc_swd_clock_delay},
  1102. {"swd_idle_bits", &swd_scriptfunc_swd_idle_bits},
  1103. {"block_size", &swd_scriptfunc_blocksize},
  1104. {"abort", &swd_scriptfunc_abort},
  1105. {"mem_dump", &swd_scriptfunc_mem_dump},
  1106. {"mem_ldmst", &swd_scriptfunc_mem_ldmst},
  1107. {"mem_write", &swd_scriptfunc_mem_write}};
  1108. /************************** script main code **************************/
  1109. static bool swd_execute_script_line(ScriptContext* const ctx) {
  1110. char buffer[64];
  1111. uint64_t start_pos = storage_file_tell(ctx->script_file);
  1112. uint16_t ret = storage_file_read(ctx->script_file, buffer, 2);
  1113. storage_file_seek(ctx->script_file, start_pos, true);
  1114. if(ret < 2) {
  1115. return true;
  1116. }
  1117. if(buffer[0] == '\n' || (buffer[0] == '\r' && buffer[1] == '\n')) {
  1118. swd_script_seek_newline(ctx);
  1119. return true;
  1120. }
  1121. for(size_t entry = 0; entry < COUNT(script_funcs); entry++) {
  1122. if(ctx->abort) {
  1123. DBGS("aborting");
  1124. break;
  1125. }
  1126. char buffer[64];
  1127. storage_file_seek(ctx->script_file, start_pos, true);
  1128. size_t expected = strlen(script_funcs[entry].prefix);
  1129. uint16_t ret = storage_file_read(ctx->script_file, buffer, expected);
  1130. if(ret != expected) {
  1131. continue;
  1132. }
  1133. buffer[expected] = '\000';
  1134. if(strncmp(buffer, script_funcs[entry].prefix, expected)) {
  1135. continue;
  1136. }
  1137. bool success = true;
  1138. if(ctx->goto_active) {
  1139. DBG("ignore: '%s'", script_funcs[entry].prefix);
  1140. /* only execute label handlers */
  1141. if(buffer[0] == '.') {
  1142. success = script_funcs[entry].func(ctx);
  1143. } else {
  1144. swd_script_seek_newline(ctx);
  1145. }
  1146. } else {
  1147. DBG("command: '%s'", script_funcs[entry].prefix);
  1148. if(!ctx->status_ignore) {
  1149. snprintf(
  1150. ctx->app->state_string,
  1151. sizeof(ctx->app->state_string),
  1152. "CMD: %s",
  1153. script_funcs[entry].prefix);
  1154. }
  1155. swd_script_gui_refresh(ctx);
  1156. /* function, execute */
  1157. success = script_funcs[entry].func(ctx);
  1158. if(!success && !ctx->errors_ignore) {
  1159. DBG("Command failed: %s", script_funcs[entry].prefix);
  1160. snprintf(
  1161. ctx->app->state_string,
  1162. sizeof(ctx->app->state_string),
  1163. "Command failed: %s",
  1164. script_funcs[entry].prefix);
  1165. return false;
  1166. }
  1167. }
  1168. return true;
  1169. }
  1170. DBG("unknown command '%s'", buffer);
  1171. return false;
  1172. }
  1173. static bool swd_execute_script(AppFSM* const ctx, const char* filename) {
  1174. bool success = true;
  1175. /* fetch current script and set as parent */
  1176. ScriptContext* parent = ctx->script;
  1177. ctx->script = malloc(sizeof(ScriptContext));
  1178. ctx->script->app = ctx;
  1179. ctx->script->max_tries = 1;
  1180. ctx->script->parent = parent;
  1181. strcpy(ctx->script->filename, filename);
  1182. if(!storage_file_exists(ctx->storage, filename)) {
  1183. DBG("Does not exist '%s'", filename);
  1184. parent = ctx->script->parent;
  1185. free(ctx->script);
  1186. ctx->script = parent;
  1187. return false;
  1188. }
  1189. /* first allocate a file object */
  1190. ctx->script->script_file = storage_file_alloc(ctx->storage);
  1191. /* then get our script opened */
  1192. if(!storage_file_open(ctx->script->script_file, filename, FSAM_READ, FSOM_OPEN_EXISTING)) {
  1193. FURI_LOG_E(TAG, "open, %s", storage_file_get_error_desc(ctx->script->script_file));
  1194. DBG("Failed to open '%s'", filename);
  1195. storage_file_free(ctx->script->script_file);
  1196. parent = ctx->script->parent;
  1197. free(ctx->script);
  1198. ctx->script = parent;
  1199. return false;
  1200. }
  1201. do {
  1202. success = true;
  1203. ctx->script->restart = false;
  1204. storage_file_seek(ctx->script->script_file, 0, true);
  1205. uint32_t line = 1;
  1206. while(line < SCRIPT_MAX_LINES) {
  1207. if(ctx->script->abort) {
  1208. DBGS("Abort requested");
  1209. break;
  1210. }
  1211. if(storage_file_eof(ctx->script->script_file)) {
  1212. break;
  1213. }
  1214. DBG("line %lu", line);
  1215. if(!swd_execute_script_line(ctx->script)) {
  1216. success = false;
  1217. break;
  1218. }
  1219. if(ctx->script->restart) {
  1220. break;
  1221. }
  1222. line++;
  1223. }
  1224. if(ctx->script->restart) {
  1225. DBGS("Restarting");
  1226. } else {
  1227. DBGS("Finished");
  1228. }
  1229. if(line >= SCRIPT_MAX_LINES) {
  1230. success = true;
  1231. char text_buf[128];
  1232. snprintf(text_buf, sizeof(text_buf), "aborting after %d lines", SCRIPT_MAX_LINES);
  1233. DialogMessage* message = dialog_message_alloc();
  1234. dialog_message_set_header(message, "SWD Probe", 16, 2, AlignLeft, AlignTop);
  1235. dialog_message_set_icon(message, &I_app, 3, 2);
  1236. dialog_message_set_text(message, text_buf, 3, 16, AlignLeft, AlignTop);
  1237. dialog_message_set_buttons(message, "Back", NULL, NULL);
  1238. dialog_message_free(message);
  1239. ctx->script->restart = false;
  1240. }
  1241. if(!success) {
  1242. char text_buf[128];
  1243. snprintf(text_buf, sizeof(text_buf), "Line %lu failed:\n%s", line, ctx->state_string);
  1244. DialogMessage* message = dialog_message_alloc();
  1245. dialog_message_set_header(message, "SWD Probe", 16, 2, AlignLeft, AlignTop);
  1246. dialog_message_set_icon(message, &I_app, 3, 2);
  1247. dialog_message_set_text(message, text_buf, 3, 16, AlignLeft, AlignTop);
  1248. dialog_message_set_buttons(message, "Back", "Retry", NULL);
  1249. if(dialog_message_show(ctx->dialogs, message) == DialogMessageButtonCenter) {
  1250. ctx->script->restart = true;
  1251. }
  1252. dialog_message_free(message);
  1253. }
  1254. } while(ctx->script->restart);
  1255. storage_file_close(ctx->script->script_file);
  1256. storage_file_free(ctx->script->script_file);
  1257. parent = ctx->script->parent;
  1258. free(ctx->script);
  1259. ctx->script = parent;
  1260. return success;
  1261. }
  1262. /************************** UI functions **************************/
  1263. static void render_callback(Canvas* const canvas, void* cb_ctx) {
  1264. AppFSM* ctx = acquire_mutex((ValueMutex*)cb_ctx, 25);
  1265. if(ctx == NULL) {
  1266. return;
  1267. }
  1268. char buffer[64];
  1269. int y = 10;
  1270. canvas_draw_frame(canvas, 0, 0, 128, 64);
  1271. canvas_set_font(canvas, FontPrimary);
  1272. if(ctx->detected_device) {
  1273. /* if seen less than a quarter second ago */
  1274. switch(ctx->mode_page) {
  1275. case ModePageScan: {
  1276. if((ctx->detected_timeout + TIMER_HZ / 4) >= TIMER_HZ * TIMEOUT) {
  1277. snprintf(buffer, sizeof(buffer), "FOUND!");
  1278. } else {
  1279. /* if it was seen more than a quarter second ago, show countdown */
  1280. snprintf(
  1281. buffer,
  1282. sizeof(buffer),
  1283. "FOUND! (%lus)",
  1284. (ctx->detected_timeout / TIMER_HZ) + 1);
  1285. }
  1286. canvas_draw_str_aligned(canvas, 64, y, AlignCenter, AlignBottom, buffer);
  1287. y += 10;
  1288. canvas_set_font(canvas, FontKeyboard);
  1289. snprintf(
  1290. buffer,
  1291. sizeof(buffer),
  1292. "SWC/SWD: %s/%s",
  1293. gpio_name(ctx->io_swc),
  1294. gpio_name(ctx->io_swd));
  1295. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1296. y += 10;
  1297. snprintf(buffer, sizeof(buffer), "DPIDR 0x%08lX", ctx->dp_regs.dpidr);
  1298. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1299. y += 10;
  1300. snprintf(
  1301. buffer,
  1302. sizeof(buffer),
  1303. "Part %02X Rev %X DAPv%d",
  1304. ctx->dpidr_info.partno,
  1305. ctx->dpidr_info.revision,
  1306. ctx->dpidr_info.version);
  1307. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1308. y += 10;
  1309. canvas_set_font(canvas, FontSecondary);
  1310. snprintf(buffer, sizeof(buffer), "%s", jep106_manufacturer(ctx->dpidr_info.designer));
  1311. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1312. y += 10;
  1313. canvas_set_font(canvas, FontSecondary);
  1314. elements_button_left(canvas, "Script");
  1315. elements_button_right(canvas, "DP Regs");
  1316. break;
  1317. }
  1318. case ModePageDPRegs: {
  1319. canvas_draw_str_aligned(canvas, 64, y, AlignCenter, AlignBottom, "DP Registers");
  1320. y += 10;
  1321. canvas_set_font(canvas, FontKeyboard);
  1322. if(ctx->dp_regs.dpidr_ok) {
  1323. snprintf(buffer, sizeof(buffer), "DPIDR %08lX", ctx->dp_regs.dpidr);
  1324. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1325. }
  1326. y += 10;
  1327. if(ctx->dp_regs.ctrlstat_ok) {
  1328. snprintf(buffer, sizeof(buffer), "CTRL %08lX", ctx->dp_regs.ctrlstat);
  1329. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1330. }
  1331. y += 10;
  1332. if(ctx->dp_regs.targetid_ok) {
  1333. snprintf(buffer, sizeof(buffer), "TGTID %08lX", ctx->dp_regs.targetid);
  1334. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1335. }
  1336. y += 10;
  1337. if(ctx->dp_regs.eventstat_ok) {
  1338. snprintf(buffer, sizeof(buffer), "EVTST %08lX", ctx->dp_regs.eventstat);
  1339. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1340. }
  1341. y += 10;
  1342. canvas_set_font(canvas, FontSecondary);
  1343. elements_button_left(canvas, "Scan");
  1344. elements_button_right(canvas, "DPID");
  1345. break;
  1346. }
  1347. case ModePageDPID: {
  1348. canvas_draw_str_aligned(canvas, 64, y, AlignCenter, AlignBottom, "DP ID Register");
  1349. y += 10;
  1350. canvas_set_font(canvas, FontKeyboard);
  1351. if(ctx->dpidr_info.version != 2) {
  1352. snprintf(buffer, sizeof(buffer), "TARGETID not supported");
  1353. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1354. y += 10;
  1355. } else {
  1356. if(ctx->dp_regs.targetid_ok) {
  1357. snprintf(buffer, sizeof(buffer), "TGTID %08lX", ctx->dp_regs.targetid);
  1358. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1359. y += 10;
  1360. snprintf(buffer, sizeof(buffer), "Part No. %04X", ctx->targetid_info.partno);
  1361. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1362. y += 10;
  1363. snprintf(
  1364. buffer,
  1365. sizeof(buffer),
  1366. "%s",
  1367. jep106_manufacturer(ctx->targetid_info.designer));
  1368. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1369. y += 10;
  1370. }
  1371. }
  1372. canvas_set_font(canvas, FontSecondary);
  1373. elements_button_left(canvas, "DP Regs");
  1374. elements_button_right(canvas, "APs");
  1375. break;
  1376. }
  1377. case ModePageAPID: {
  1378. canvas_draw_str_aligned(canvas, 64, y, AlignCenter, AlignBottom, "AP Menu");
  1379. y += 10;
  1380. canvas_set_font(canvas, FontKeyboard);
  1381. char state = ' ';
  1382. if(ctx->ap_pos >= ctx->ap_scanned && ctx->ap_pos <= ctx->ap_scanned + 10) {
  1383. state = '*';
  1384. }
  1385. if(!ctx->apidr_info[ctx->ap_pos].ok) {
  1386. snprintf(buffer, sizeof(buffer), "[%d]%c<none>", ctx->ap_pos, state);
  1387. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1388. y += 10;
  1389. if(ctx->ap_pos == 0) {
  1390. for(size_t pos = 0; pos < COUNT(ctx->apidr_info); pos++) {
  1391. if(ctx->apidr_info[pos].ok) {
  1392. ctx->ap_pos = pos;
  1393. }
  1394. }
  1395. }
  1396. } else {
  1397. const char* class = "";
  1398. switch(ctx->apidr_info[ctx->ap_pos].class) {
  1399. case 0:
  1400. class = "und";
  1401. break;
  1402. case 1:
  1403. class = "COM";
  1404. break;
  1405. case 8:
  1406. class = "MEM";
  1407. break;
  1408. default:
  1409. class = "unk";
  1410. break;
  1411. }
  1412. const char* types[] = {
  1413. "COM-AP",
  1414. "AHB3",
  1415. "APB2 or APB3",
  1416. "Type unknown",
  1417. "AXI3 or AXI4",
  1418. "AHB5",
  1419. "APB4 and APB5",
  1420. "AXI5",
  1421. "AHB5 enh.",
  1422. };
  1423. const char* type = "Type unk";
  1424. if(ctx->apidr_info[ctx->ap_pos].type < COUNT(types)) {
  1425. type = types[ctx->apidr_info[ctx->ap_pos].type];
  1426. }
  1427. snprintf(buffer, sizeof(buffer), "[%d]%c%s, %s", ctx->ap_pos, state, class, type);
  1428. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1429. y += 10;
  1430. snprintf(
  1431. buffer, sizeof(buffer), "Base 0x%08lX", ctx->apidr_info[ctx->ap_pos].base);
  1432. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1433. y += 10;
  1434. snprintf(
  1435. buffer,
  1436. sizeof(buffer),
  1437. "Rev %d Var %d",
  1438. ctx->apidr_info[ctx->ap_pos].revision,
  1439. ctx->apidr_info[ctx->ap_pos].variant);
  1440. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1441. y += 10;
  1442. snprintf(
  1443. buffer,
  1444. sizeof(buffer),
  1445. "%s",
  1446. jep106_manufacturer(ctx->apidr_info[ctx->ap_pos].designer));
  1447. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, buffer);
  1448. y += 10;
  1449. elements_button_center(canvas, "Show");
  1450. }
  1451. canvas_set_font(canvas, FontSecondary);
  1452. elements_button_left(canvas, "DPID");
  1453. elements_scrollbar_pos(
  1454. canvas, 4, 10, 40, ctx->ap_pos / 32, COUNT(ctx->apidr_info) / 32);
  1455. } break;
  1456. /* hex dump view */
  1457. case ModePageHexDump: {
  1458. canvas_draw_str_aligned(canvas, 64, y, AlignCenter, AlignBottom, "Hex dump");
  1459. y += 10;
  1460. canvas_set_font(canvas, FontKeyboard);
  1461. canvas_draw_str_aligned(canvas, 5, y, AlignLeft, AlignBottom, "Addr:");
  1462. snprintf(buffer, sizeof(buffer), "%08lX", ctx->hex_addr);
  1463. canvas_draw_str_aligned(canvas, 38, y, AlignLeft, AlignBottom, buffer);
  1464. uint32_t font_width = canvas_glyph_width(canvas, '0');
  1465. uint32_t x = 37 + (7 - ctx->hex_select) * font_width;
  1466. /* draw selection */
  1467. canvas_draw_line(canvas, x, y + 1, x + font_width, y + 1);
  1468. y += 10;
  1469. uint32_t byte_num = 0;
  1470. for(int line = 0; line < 4; line++) {
  1471. uint32_t x_pos = 5;
  1472. for(int byte_pos = 0; byte_pos < 8; byte_pos++) {
  1473. if(ctx->hex_buffer_valid[byte_num / 4]) {
  1474. snprintf(buffer, sizeof(buffer), "%02X", ctx->hex_buffer[byte_num]);
  1475. } else {
  1476. snprintf(buffer, sizeof(buffer), "--");
  1477. }
  1478. byte_num++;
  1479. canvas_draw_str_aligned(canvas, x_pos, y, AlignLeft, AlignBottom, buffer);
  1480. x_pos += font_width * 2 + font_width / 2;
  1481. }
  1482. y += 10;
  1483. }
  1484. break;
  1485. }
  1486. /* hex dump view */
  1487. case ModePageScript: {
  1488. canvas_draw_str_aligned(canvas, 64, y, AlignCenter, AlignBottom, "Script");
  1489. y += 10;
  1490. y += 10;
  1491. canvas_draw_str_aligned(canvas, 10, y, AlignLeft, AlignBottom, "Status:");
  1492. y += 10;
  1493. canvas_set_font(canvas, FontKeyboard);
  1494. canvas_draw_str_aligned(canvas, 64, y, AlignCenter, AlignBottom, ctx->state_string);
  1495. y += 10;
  1496. } break;
  1497. }
  1498. } else {
  1499. snprintf(
  1500. buffer, sizeof(buffer), "Searching... %c", gpio_direction_ind[ctx->current_mask_id]);
  1501. canvas_draw_str(canvas, 25, 10, buffer);
  1502. y += 14;
  1503. canvas_set_font(canvas, FontSecondary);
  1504. bool info_page = (ctx->loop_count % 500) >= 250;
  1505. if(info_page) {
  1506. canvas_draw_str(canvas, 2, y, "Connect GND with target GND");
  1507. y += 10;
  1508. canvas_draw_str(canvas, 2, y, "and any two GPIOs with pads");
  1509. y += 10;
  1510. canvas_draw_str(canvas, 2, y, "you want to check for SWD");
  1511. canvas_set_font(canvas, FontPrimary);
  1512. canvas_draw_str(canvas, 111, 62, "2/2");
  1513. } else {
  1514. const char* filename = "<none>";
  1515. if(strlen(ctx->script_detected) > 0) {
  1516. const char* slash = strrchr(ctx->script_detected, '/');
  1517. if(slash) {
  1518. filename = &slash[1];
  1519. } else {
  1520. filename = ctx->script_detected;
  1521. }
  1522. }
  1523. canvas_set_font(canvas, FontSecondary);
  1524. canvas_draw_str_aligned(canvas, 64, y, AlignCenter, AlignBottom, "Autoexec Script");
  1525. y += 10;
  1526. canvas_set_font(canvas, FontKeyboard);
  1527. canvas_draw_str_aligned(canvas, 64, y, AlignCenter, AlignBottom, filename);
  1528. y += 16;
  1529. canvas_set_font(canvas, FontSecondary);
  1530. canvas_draw_icon(canvas, 14, y - 5, &I_ButtonUp_7x4);
  1531. canvas_draw_icon(canvas, 78, y - 5, &I_ButtonDown_7x4);
  1532. canvas_draw_str(canvas, 23, y, "Clear");
  1533. canvas_draw_str(canvas, 87, y, "Choose");
  1534. canvas_set_font(canvas, FontPrimary);
  1535. canvas_draw_str(canvas, 111, 62, "1/2");
  1536. }
  1537. canvas_set_font(canvas, FontSecondary);
  1538. elements_button_left(canvas, "Script");
  1539. }
  1540. release_mutex((ValueMutex*)cb_ctx, ctx);
  1541. }
  1542. static void input_callback(InputEvent* input_event, FuriMessageQueue* event_queue) {
  1543. furi_assert(event_queue);
  1544. /* better skip than sorry */
  1545. if(furi_message_queue_get_count(event_queue) < QUEUE_SIZE) {
  1546. AppEvent event = {.type = EventKeyPress, .input = *input_event};
  1547. furi_message_queue_put(event_queue, &event, 100);
  1548. }
  1549. }
  1550. static void timer_tick_callback(FuriMessageQueue* event_queue) {
  1551. furi_assert(event_queue);
  1552. /* filling buffer makes no sense, as we lost timing anyway */
  1553. if(furi_message_queue_get_count(event_queue) < 1) {
  1554. AppEvent event = {.type = EventTimerTick};
  1555. furi_message_queue_put(event_queue, &event, 100);
  1556. }
  1557. }
  1558. static void app_init(AppFSM* const app) {
  1559. app->loop_count = 0;
  1560. app->current_mask_id = 0;
  1561. app->current_mask = gpio_direction_mask[app->current_mask_id];
  1562. app->io_swd = 0xFF;
  1563. app->io_swc = 0xFF;
  1564. app->hex_addr = 0x40002800;
  1565. app->hex_addr = 0xE000EDF0;
  1566. app->swd_clock_delay = CLOCK_DELAY;
  1567. app->swd_idle_bits = IDLE_BITS;
  1568. strcpy(app->state_string, "none");
  1569. strcpy(app->script_detected, "");
  1570. }
  1571. static void app_deinit(AppFSM* const ctx) {
  1572. furi_timer_free(ctx->timer);
  1573. }
  1574. static void on_timer_tick(AppFSM* ctx) {
  1575. ctx->loop_count++;
  1576. switch(ctx->mode_page) {
  1577. case ModePageScan: {
  1578. /* reset after timeout */
  1579. if(ctx->detected_timeout == 0) {
  1580. ctx->detected_device = false;
  1581. ctx->io_swd = 0xFF;
  1582. ctx->io_swc = 0xFF;
  1583. ctx->io_num_swd = 0xFF;
  1584. ctx->io_num_swc = 0xFF;
  1585. ctx->ap_scanned = 0;
  1586. memset(&ctx->dp_regs, 0x00, sizeof(ctx->dp_regs));
  1587. memset(&ctx->targetid_info, 0x00, sizeof(ctx->targetid_info));
  1588. memset(&ctx->apidr_info, 0x00, sizeof(ctx->apidr_info));
  1589. ctx->script_detected_executed = false;
  1590. } else {
  1591. ctx->detected_timeout--;
  1592. }
  1593. ctx->detected = false;
  1594. ctx->current_mask = gpio_direction_mask[ctx->current_mask_id];
  1595. /* when SWD was already detected, set it to data pin regardless of the mask */
  1596. if(ctx->detected_device) {
  1597. ctx->current_mask &= ~ctx->io_swd;
  1598. }
  1599. /* do the scan */
  1600. swd_scan(ctx);
  1601. /* now when detected a device, set the timeout */
  1602. if(ctx->detected) {
  1603. ctx->detected_device = true;
  1604. ctx->detected_timeout = TIMER_HZ * TIMEOUT;
  1605. /* update DPIDR fields */
  1606. ctx->dpidr_info.revision = (ctx->dp_regs.dpidr >> 28) & 0x0F;
  1607. ctx->dpidr_info.partno = (ctx->dp_regs.dpidr >> 20) & 0xFF;
  1608. ctx->dpidr_info.version = (ctx->dp_regs.dpidr >> 12) & 0x0F;
  1609. ctx->dpidr_info.designer = (ctx->dp_regs.dpidr >> 1) & 0x3FF;
  1610. if(!has_multiple_bits(ctx->io_swc)) {
  1611. DBGS(" - Detected pins");
  1612. DBGS(" - Resetting error");
  1613. /* reset error */
  1614. /* first make sure we have the correct bank by invalidating the current select cache */
  1615. ctx->dp_regs.select_ok = false;
  1616. uint8_t ack =
  1617. swd_read_dpbank(ctx, REG_CTRLSTAT, REG_CTRLSTAT_BANK, &ctx->dp_regs.ctrlstat);
  1618. if(ack != 1 || (ctx->dp_regs.ctrlstat & STAT_ERROR_FLAGS)) {
  1619. DBGS(" - send ABORT");
  1620. swd_abort(ctx);
  1621. }
  1622. DBGS(" - Fetch CTRL/STAT");
  1623. ctx->dp_regs.ctrlstat_ok =
  1624. swd_read_dpbank(
  1625. ctx, REG_CTRLSTAT, REG_CTRLSTAT_BANK, &ctx->dp_regs.ctrlstat) == 1;
  1626. DBG(" %08lX %s",
  1627. ctx->dp_regs.ctrlstat,
  1628. ctx->dp_regs.ctrlstat_ok ? "OK" : "FAIL");
  1629. if(ctx->dpidr_info.version >= 1) {
  1630. DBGS(" - DAPv1, read DLCR");
  1631. ctx->dp_regs.dlcr_ok =
  1632. swd_read_dpbank(ctx, REG_DLCR, REG_DLCR_BANK, &ctx->dp_regs.dlcr) == 1;
  1633. DBG(" %08lX %s", ctx->dp_regs.dlcr, ctx->dp_regs.dlcr_ok ? "OK" : "FAIL");
  1634. }
  1635. if(ctx->dpidr_info.version >= 2) {
  1636. DBGS(" - DAPv2, read TARGETID");
  1637. ctx->dp_regs.targetid_ok =
  1638. swd_read_dpbank(
  1639. ctx, REG_TARGETID, REG_TARGETID_BANK, &ctx->dp_regs.targetid) == 1;
  1640. DBG(" %08lX %s",
  1641. ctx->dp_regs.targetid,
  1642. ctx->dp_regs.targetid_ok ? "OK" : "FAIL");
  1643. DBGS(" - DAPv2, read EVENTSTAT");
  1644. ctx->dp_regs.eventstat_ok =
  1645. swd_read_dpbank(
  1646. ctx, REG_EVENTSTAT, REG_EVENTSTAT_BANK, &ctx->dp_regs.eventstat) == 1;
  1647. DBG(" %08lX %s",
  1648. ctx->dp_regs.eventstat,
  1649. ctx->dp_regs.eventstat_ok ? "OK" : "FAIL");
  1650. DBGS(" - DAPv2, read DLPIDR");
  1651. ctx->dp_regs.dlpidr_ok =
  1652. swd_read_dpbank(ctx, REG_DLPIDR, REG_DLPIDR_BANK, &ctx->dp_regs.dlpidr) ==
  1653. 1;
  1654. DBG(" %08lX %s",
  1655. ctx->dp_regs.dlpidr,
  1656. ctx->dp_regs.dlpidr_ok ? "OK" : "FAIL");
  1657. }
  1658. if(ctx->dp_regs.targetid_ok) {
  1659. ctx->targetid_info.revision = (ctx->dp_regs.targetid >> 28) & 0x0F;
  1660. ctx->targetid_info.partno = (ctx->dp_regs.targetid >> 12) & 0xFFFF;
  1661. ctx->targetid_info.designer = (ctx->dp_regs.targetid >> 1) & 0x3FF;
  1662. }
  1663. if(!ctx->script_detected_executed && strlen(ctx->script_detected) > 0) {
  1664. DBG(" - Run script '%s'", ctx->script_detected);
  1665. ctx->script_detected_executed = true;
  1666. ctx->mode_page = ModePageScript;
  1667. swd_execute_script(ctx, ctx->script_detected);
  1668. ctx->mode_page = ModePageScan;
  1669. }
  1670. }
  1671. } else {
  1672. if(!has_multiple_bits(ctx->io_swc)) {
  1673. DBGS(" - Lost device");
  1674. }
  1675. }
  1676. ctx->current_mask_id = (ctx->current_mask_id + 1) % COUNT(gpio_direction_mask);
  1677. break;
  1678. }
  1679. case ModePageDPRegs:
  1680. case ModePageDPID:
  1681. case ModePageAPID: {
  1682. /* set debug enable request */
  1683. if(!swd_ensure_powerup(ctx)) {
  1684. break;
  1685. }
  1686. /* only scan a few APs at once to stay responsive */
  1687. for(int pos = 0; pos < 8; pos++) {
  1688. if(ctx->ap_scanned == 0) {
  1689. swd_apscan_reset(ctx);
  1690. }
  1691. uint8_t ap = ctx->ap_scanned++;
  1692. if(ctx->apidr_info[ap].tested) {
  1693. continue;
  1694. }
  1695. if(swd_apscan_test(ctx, ap)) {
  1696. break;
  1697. }
  1698. }
  1699. break;
  1700. }
  1701. case ModePageHexDump: {
  1702. if(ctx->hex_read_delay++ < 10) {
  1703. break;
  1704. }
  1705. ctx->hex_read_delay = 0;
  1706. memset(ctx->hex_buffer, 0xEE, sizeof(ctx->hex_buffer));
  1707. uint32_t addr = ctx->hex_addr;
  1708. uint32_t data = 0;
  1709. for(size_t pos = 0; pos < sizeof(ctx->hex_buffer) / 4; pos++) {
  1710. ctx->hex_buffer_valid[pos] = swd_read_memory(ctx, ctx->ap_pos, addr, &data) == 1;
  1711. if(ctx->hex_buffer_valid[pos]) {
  1712. memcpy(&ctx->hex_buffer[pos * 4], &data, 4);
  1713. } else {
  1714. swd_abort_simple(ctx);
  1715. }
  1716. addr += 4;
  1717. }
  1718. }
  1719. }
  1720. }
  1721. static bool swd_message_process(AppFSM* ctx) {
  1722. bool processing = true;
  1723. AppEvent event;
  1724. FuriStatus event_status = furi_message_queue_get(ctx->event_queue, &event, 100);
  1725. if(event_status == FuriStatusOk) {
  1726. if(event.type == EventKeyPress) {
  1727. if(event.input.type == InputTypePress) {
  1728. switch(event.input.key) {
  1729. case InputKeyUp:
  1730. switch(ctx->mode_page) {
  1731. default:
  1732. break;
  1733. case ModePageScan: {
  1734. strcpy(ctx->script_detected, "");
  1735. break;
  1736. }
  1737. case ModePageAPID:
  1738. if(ctx->ap_pos > 0) {
  1739. ctx->ap_pos--;
  1740. }
  1741. break;
  1742. case ModePageHexDump: {
  1743. ctx->hex_addr +=
  1744. ((ctx->hex_select) ? 1 : 8) * (1 << (4 * ctx->hex_select));
  1745. break;
  1746. }
  1747. }
  1748. break;
  1749. case InputKeyDown:
  1750. switch(ctx->mode_page) {
  1751. default:
  1752. break;
  1753. case ModePageScan: {
  1754. FuriString* result_path = furi_string_alloc_printf(ANY_PATH("swd"));
  1755. FuriString* preselected = furi_string_alloc_printf(
  1756. (strlen(ctx->script_detected) > 0) ? ctx->script_detected :
  1757. ANY_PATH("swd"));
  1758. DialogsFileBrowserOptions options;
  1759. dialog_file_browser_set_basic_options(&options, "swd", &I_swd);
  1760. if(dialog_file_browser_show(
  1761. ctx->dialogs, result_path, preselected, &options)) {
  1762. const char* path = furi_string_get_cstr(result_path);
  1763. strcpy(ctx->script_detected, path);
  1764. }
  1765. furi_string_free(result_path);
  1766. furi_string_free(preselected);
  1767. break;
  1768. }
  1769. case ModePageAPID:
  1770. if(ctx->ap_pos + 1U < COUNT(ctx->apidr_info)) {
  1771. ctx->ap_pos++;
  1772. }
  1773. break;
  1774. case ModePageHexDump: {
  1775. ctx->hex_addr -=
  1776. ((ctx->hex_select) ? 1 : 8) * (1 << (4 * ctx->hex_select));
  1777. break;
  1778. }
  1779. }
  1780. break;
  1781. case InputKeyRight:
  1782. if(ctx->mode_page == ModePageHexDump) {
  1783. if(ctx->hex_select > 0) {
  1784. ctx->hex_select--;
  1785. }
  1786. } else if(ctx->detected) {
  1787. if(ctx->mode_page + 1 < ModePageCount) {
  1788. ctx->mode_page++;
  1789. }
  1790. }
  1791. break;
  1792. case InputKeyLeft:
  1793. if(ctx->mode_page == ModePageHexDump) {
  1794. if(ctx->hex_select < 7) {
  1795. ctx->hex_select++;
  1796. }
  1797. } else if(ctx->mode_page == ModePageScan) {
  1798. FuriString* result_path = furi_string_alloc_printf(ANY_PATH("swd"));
  1799. FuriString* preselected = furi_string_alloc_printf(
  1800. (strlen(ctx->script_detected) > 0) ? ctx->script_detected :
  1801. ANY_PATH("swd"));
  1802. DialogsFileBrowserOptions options;
  1803. dialog_file_browser_set_basic_options(&options, "swd", &I_swd);
  1804. if(dialog_file_browser_show(
  1805. ctx->dialogs, result_path, preselected, &options)) {
  1806. const char* path = furi_string_get_cstr(result_path);
  1807. ctx->mode_page = ModePageScript;
  1808. swd_execute_script(ctx, path);
  1809. ctx->mode_page = ModePageScan;
  1810. }
  1811. furi_string_free(result_path);
  1812. furi_string_free(preselected);
  1813. break;
  1814. } else {
  1815. if(ctx->mode_page > 0) {
  1816. ctx->mode_page--;
  1817. }
  1818. }
  1819. break;
  1820. case InputKeyOk:
  1821. if(ctx->mode_page == ModePageAPID && ctx->apidr_info[ctx->ap_pos].ok) {
  1822. ctx->mode_page = ModePageHexDump;
  1823. }
  1824. break;
  1825. case InputKeyBack:
  1826. if(ctx->mode_page == ModePageHexDump) {
  1827. ctx->mode_page = ModePageAPID;
  1828. } else if(ctx->mode_page == ModePageScript) {
  1829. ctx->script->abort = true;
  1830. } else if(ctx->mode_page != ModePageScan) {
  1831. ctx->mode_page = ModePageScan;
  1832. } else {
  1833. processing = false;
  1834. }
  1835. break;
  1836. default:
  1837. break;
  1838. }
  1839. }
  1840. } else if(event.type == EventTimerTick) {
  1841. on_timer_tick(ctx);
  1842. }
  1843. } else {
  1844. /* timeout */
  1845. }
  1846. return processing;
  1847. }
  1848. int32_t swd_probe_app_main(void* p) {
  1849. UNUSED(p);
  1850. AppFSM* app = malloc(sizeof(AppFSM));
  1851. app_init(app);
  1852. if(!init_mutex(&app->state_mutex, app, sizeof(AppFSM))) {
  1853. FURI_LOG_E(TAG, "cannot create mutex\r\n");
  1854. free(app);
  1855. return 255;
  1856. }
  1857. app->notification = furi_record_open(RECORD_NOTIFICATION);
  1858. app->gui = furi_record_open(RECORD_GUI);
  1859. app->dialogs = furi_record_open(RECORD_DIALOGS);
  1860. app->storage = furi_record_open(RECORD_STORAGE);
  1861. app->view_port = view_port_alloc();
  1862. app->event_queue = furi_message_queue_alloc(QUEUE_SIZE, sizeof(AppEvent));
  1863. app->timer = furi_timer_alloc(timer_tick_callback, FuriTimerTypePeriodic, app->event_queue);
  1864. view_port_draw_callback_set(app->view_port, render_callback, &app->state_mutex);
  1865. view_port_input_callback_set(app->view_port, input_callback, app->event_queue);
  1866. gui_add_view_port(app->gui, app->view_port, GuiLayerFullscreen);
  1867. notification_message_block(app->notification, &sequence_display_backlight_enforce_on);
  1868. swd_execute_script(app, ANY_PATH("swd/startup.swd"));
  1869. DOLPHIN_DEED(DolphinDeedPluginGameStart);
  1870. furi_timer_start(app->timer, furi_kernel_get_tick_frequency() / TIMER_HZ);
  1871. for(bool processing = true; processing;) {
  1872. //AppFSM* ctx = (AppFSM*)acquire_mutex_block(&app->state_mutex);
  1873. processing = swd_message_process(app);
  1874. view_port_update(app->view_port);
  1875. //release_mutex(&ctx->state_mutex, ctx);
  1876. bool beep = false;
  1877. if(app->detected_device && !app->detected_notified) {
  1878. app->detected_notified = true;
  1879. beep = true;
  1880. }
  1881. if(!app->detected_device && app->detected_notified) {
  1882. app->detected_notified = false;
  1883. }
  1884. if(beep) {
  1885. notification_message_block(app->notification, &seq_c_minor);
  1886. }
  1887. }
  1888. app_deinit(app);
  1889. // Wait for all notifications to be played and return backlight to normal state
  1890. notification_message_block(app->notification, &sequence_display_backlight_enforce_auto);
  1891. view_port_enabled_set(app->view_port, false);
  1892. gui_remove_view_port(app->gui, app->view_port);
  1893. furi_record_close(RECORD_GUI);
  1894. furi_record_close(RECORD_NOTIFICATION);
  1895. view_port_free(app->view_port);
  1896. furi_message_queue_free(app->event_queue);
  1897. delete_mutex(&app->state_mutex);
  1898. free(app);
  1899. return 0;
  1900. }