swd_probe_app.c 82 KB

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