swd_probe_app.c 85 KB

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