-
Notifications
You must be signed in to change notification settings - Fork 2
/
bd_shell.ps1
2894 lines (2652 loc) · 107 KB
/
bd_shell.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
###############################################################################
# bd_shell.ps1 (C) Copyright 2014 Kevin M. Hubbard - All rights reserved.
# This software is released under the GNU GPLv2 license.
# [ ChangeLog ]
# khubbard 02.28.14 : Ported from sump.ps1
# khubbard 03.10.14 : Lots of new features added.
# khubbard 03.12.14 : Fix read num_dwords offset problem.
# khubbard 03.13.14 : Create empty file if vi on new filename. diff,python
# khubbard 03.14.14 : Fixed read issues with USB interface.
# Fixed grep pattern being off by 1 character
# Fixed base_addr showing up in read output address.
# Fixed | grep to single read locking up.
# Added popup_select dialog box.
# Added popup_openfile.
# Added assigning variable to command results in ()
# Variable replacement cleanup ( do once now )
# khubbard 03.17.14 : Fixed 'configure' not working with USB interface.
# khubbard 03.18.14 : Fixed Win8 PowerShell3 problem with "$server:$port"
# khubbard 05.29.14 : Added timeout protection for socket_send()
# khubbard 06.02.14 : Increase socket_send() timeout from 1s to 5s.
# khubbard 06.02.14 : Added command history command.
# khubbard 06.27.14 : Added SPI PROM support
# khubbard 06.27.14 : Improved "ls" UNIX command to support wildcards
# khubbard 06.27.14 : Removed PROM Erase timeouts. Added PROM unlocking.
# khubbard 06.28.14 : Added prom_vers command for reading UNIX timestamps.
# khubbard 06.30.14 : Changed prom_boot
# khubbard 07.17.14 : Added "!!" for prom_boot to unlock Poke after reconfig.
# khubbard 07.18.14 : Added "rt" for register test and increased socket_send
# timeout from 5s to 10s to support new command.
# khubbard 07.22.14 : Safety check for zero length bd_shell.ini file
# khubbard 07.27.14 : Added PROM Slot feature for prom_load and prom_boot
# khubbard 08.25.14 : Added prom_root,prom_bist commands
# khubbard 09.18.14 : Replaced convert with int2hex and hex2int commands
# Change to popup_select to display var names not values
# Added unix mv command
# khubbard 10.30.14 : prom_load change to strip 1st 88 bytes for Spartan6
# khubbard 11.01.14 : Aliased uart_load to configure command
# khubbard 01.15.15 : Adding FTDI 2XX DLL support. No configure for DLL yet.
# khubbard 01.21.15 : Adding timestamp command.
# khubbard 01.22.15 : Do a try catch for spawning python
# khubbard 05.28.15 : Added -c command line option (non-GUI)
# khubbard 10.01.15 : Lattice support for PROM release DeepPower and prom_load
# khubbard 10.11.15 : Starting Mesa Bus support
# khubbard 10.30.15 : Send single chars instead of line for Arduino fix
# khubbard 11.16.15 : Support for new MesaBus Ro headers on readback
# khubbard 03.18.16 : mesa_id command added
#
#
# WARNING: prom_load requires bd_server socket connection. Direct doesnt work.
###############################################################################
# This is a PowerShell script. Microsoft makes writing PowerShell scripts very
# easy - but running them extremely difficult. More details available at:
# http://technet.microsoft.com/en-us/gg261722.aspx
# This script has been compiled into a .NET executable ( much like C# ) by
# using the PS2EXE ( PS2EXE v0.4.0.0 http://ps2exe.codeplex.com ) script
# written by: Ingo Karstein (http://blog.karstein-consulting.com)
# Build instructions:
# call "callPS2EXE.bat" "bd_shell.ps1" "bd_shell.exe" -noconsole
###############################################################################
# Running as a script:
# Right-Click and 'Run with Powershell' to Execute this Script
# 'Set-ExecutionPolicy RemoteSigned' as Admin if script won't run
###############################################################################
# WARNING : By default, all comparison operators are case-insensitive.
# To make a comparison operator case-sensitive, precede the operator name with
# a "c". For example, the case-sensitive version of "-eq" is "-ceq"
###############################################################################
[void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void][Reflection.Assembly]::LoadWithPartialName("System.Drawing")
set-strictmode -version 2.0;# Forces vars to be init before use
###############################################################################
# --------------------------------------------------------------------------- #
# Window Management Library
# create_form() : Create the Windows Form with specified pulldown menu
function create_form( $obj_menu )
{
$obj_form = new-object System.Windows.Forms.form;
$obj_form.clientsize = new-object System.Drawing.Size(640,480);
$obj_form.text = ("bd_shell $vers");
#$obj_form.controls.add( $obj_menu );
#$obj_form.mainmenustrip = $obj_menu;
$obj_form.add_formclosing( { event_close_form $obj_form } )
$obj_form.add_shown( {$obj_form.activate()} )
$obj_form.add_resizeend( { event_resize("") } );# Note: Called on Win Move also
$obj_form.add_gotfocus( { event_gotfocus("") } );
$obj_form.Location = New-Object Drawing.Point(0,0);
$obj_form.StartPosition = "Manual"; # vs "CenterScreen"
#$obj_form.TopMost = $true;
$obj_form_h = 800;
$obj_form_w = 800;
#$obj_form_w = 70 * ( $obj_font.Size );# Width
$w = (hash_get(@($var_hash,"window_width")));
$h = (hash_get(@($var_hash,"window_height")));
if ( $w -ne "" ) { $obj_form_w = str2int( $w ); }
if ( $h -ne "" ) { $obj_form_h = str2int( $h ); }
$obj_form.Size = New-Object Drawing.Point( $obj_form_w, $obj_form_h );
return $obj_form;
}
function apply_font( $args_array )
{
( $font_name, $font_size ) = $args_array;
$global:obj_font = New-Object System.Drawing.Font( $font_name, $font_size,
[System.Drawing.FontStyle]::Regular);
}
function str2int( $_ ) { return ( [convert]::toint32( $_,10) ); }
function hex2int( $_ )
{
try { $rts = ( [convert]::toint32( $_,16) ); }
catch { $rts = 0; }
return $rts;
}
function int2hex( $_ ) { return ( "{0:x8}" -f $_ ); }
function int2str( $_ ) { return ( "{0:d0}" -f $_ ); }
function bin2int( $_ ) { return ( [convert]::toint32( $_,2 ) ); }
function event_gotfocus
{
$obj_form.Opacity = 100;
}
####################################################
# Anything to Console Print also goes to log file
function print( $_ )
{
$print_log_en = "1";
if ( $print_log_en -eq "1" )
{
Write-Host $_;
# $_ >> $log_file;
}
}# print()
####################################################
# Log stuff to a file
function log2file( $_ )
{
$_ >> $log_file;
}# log2fil()
####################################################
# one-line status bar at the bottom of form
function create_obj_status()
{
$private:obj = New-Object Windows.Forms.StatusBar;
$obj.TabStop = $false;
$obj.Text = "StatusBar";
return $obj;
}
####################################################
# Place single text line in the status bar at bottom
function status( $_ )
{
print $_;
$nl = [Environment]::NewLine
$obj_rtb.AppendText( ($_ + $nl) );
event_refresh;
}
function event_close_form($Sender,$e) { ($_).Cancel= $False; event_exit }
function event_exit
{
# print ( "event_exit()" );
$w = (int2str( $obj_form.Size.Width ));
$h = (int2str( $obj_form.Size.Height ));
replace_param( @($ini_file,"window_width", $w ));
replace_param( @($ini_file,"window_height", $h ));
# print("Bye");
$obj_form.Dispose(); # This will close the form window
[Environment]::Exit(0);# This will close the console window
}
################################################################################
# Allow user to resize entire window and recalculate
################################################################################
function event_resize( )
{
$obj_rtb.Refresh();
$obj_form.Refresh();
$obj_rtb.AppendText("");
$obj_rtb.ScrollToCaret();
$foo = $obj_rtb.Focus();
#return;
}# event_resize()
#############################################################################
# event_refresh() : refreshes form
function event_refresh( )
{
$obj_form.Refresh();
}# event_refresh()
############################################################
# Configure a widget to be on a grid of 75x23 units + margin
function cfg_obj( $args_array )
{
( $obj, $text, $x, $y, $w, $h ) = $args_array;
$bh = 23;
# $bw = 75;
# $bw = 50;
$bw = 60;
$m = 1;
$uh = $bh + $m;
$uw = $bw + $m;
$bx = $m/2 + ($uw * $x );
$by = $m/2 + ($uh * $y );
$bw = ( $uw * $w ) - $m;
$bh = ( $uh * $h ) - $m;
# Attempt to align labels with buttons by offsetting Y and making narrow
if ( $obj.GetType() -eq [System.Windows.Forms.Label] )
{
$by = $by + 2;
$bh = $bh - 3;
$bw = $bw * 1;
}
$obj.Location = New-Object System.Drawing.Size($bx,$by);
$obj.Size = New-Object System.Drawing.Size($bw,$bh);
$obj.TabStop = $true;
$obj.Text = $text;
}# cfg_obj()
# End of Window Library
# --------------------------------------------------------------------------- #
###############################################################################
function create_manual( $args_array )
{
( $filename ) = $args_array;
if ( Test-Path( $filename ) ) { return; }
$a = @();
$a+=" BD_SHELL.exe for Windows ";
$a+=(" BD_SHELL Version "+$vers+" by "+$author);
$a+=" ";
$a+="1.0 Scope ";
$a+=" This document describes the BD_SHELL.exe executable for Windows. ";
$a+=" ";
$a+="2.0 Software Architecture ";
$a+=" BD_SHELL.exe is a Windows .NET WinForms application for: ";
$a+=" 1) Interactively reading and writing to FPGA hardware. ";
$a+=" 2) Running command scripts for accessing FPGA hardware. ";
$a+=" 3) Basic operating system file access. ";
$a+=" The application is written in Windows PowerShell language and ";
$a+=" the script is then compiled into a .NET executable ( much like C# ) ";
$a+=" by using the PS2EXE ( v0.4.0.0 http://ps2exe.codeplex.com ) script ";
$a+=" written by: Ingo Karstein (http://blog.karstein-consulting.com) ";
$a+=" Build instructions: ";
$a+=" call 'callPS2EXE.bat' 'bd_shell.ps1' 'bd_shell.exe' -noconsole ";
$a+=" ";
$a+="3.0 User Interface ";
$a+=" The default User Interface to BD_SHELL.exe is a resizable WinForms ";
$a+=" form containing a WinForms RichTextBox. The UI is modeled after ";
$a+=" the open-source GNU Bash shell used in the Linux operating system. ";
$a+=" Commands are typed in a resizable text window at a command prompt ";
$a+=" and the results are scrolled onto the screen. BD_SHELL may also be ";
$a+=" optionally ran without the GUI direct from a MS-DOS command line ";
$a+=" by using the -c argument followed by a BD_SHELL command. Example: ";
$a+=" Example: C:\bd_shell.exe -c 'source foo.txt' ";
$a+=" ";
$a+="4.0 Commands ";
$a+=" 4.1 Backdoor Commands ";
$a+=" w addr data : Write Data to Address";
$a+=" r addr : Read Address";
$a+=" bs addr data : Bit Set";
$a+=" bc addr data : Bit Clear";
$a+=" w addr data data data : Write Multiple DWORDs";
$a+=" r addr dwords : Read Multiple DWORDs";
$a+=" r addr dwords > file : Read Multiple and dump to file";
$a+=" r addr dwords >> file : Read Multiple and append to file";
$a+=" rt addr iterations : Register Test at addr for iterations";
$a+=" addr : data : Write to Addr";
#$a+=" Loop Writes";
#$a+=" i = 100 : Load Loop Address with 100";
#$a+=" 4{w i AA} : Write AA to 100,104,108,10c";
$a+=" 4.2 FPGA Configuration Commands ";
$a+=" timestamp : Query TIMESTAMP of FPGA design";
$a+=" UART XC3S400 Spartan3 Hubbard Board ";
$a+=" uart_load top.bit : Send top.bit to Spartan3 board";
$a+=" SPI PROM Nano3 or Nano6 Boards";
$a+=" prom_id : Query SPI PROM ID at prom_addr";
$a+=" prom_vers : Query TIMESTAMP of FPGA design";
$a+=" prom_load top.bit slot : Load PROM with top.bit to slot";
$a+=" prom_dump addr : Dump 256 Bytes from PROM at addr";
$a+=" prom_boot slot : Reboot (PROG_L) FPGA from PROM at slot";
$a+=" prom_root : Allow overwriting BootLoader";
$a+=" prom_bist : Issue BIST Request to FPGA";
$a+=" 4.3 Linux-ish Commands ";
$a+=" pwd : Display current directory path ";
$a+=" cd path : Change directory, source bd_shell.ini ";
$a+=" cp file1 file1 : Copy file1 to file2 ";
$a+=" mv file1 file1 : Move file1 to file2 ";
$a+=" diff file1 file1 : Compare file1 to file2 ";
$a+=" mkdir path : Make new directory path ";
$a+=" ls : List Contents of current directory ";
$a+=" vi file : Open file with default opener ";
$a+=" more file : Display contents of file ";
$a+=" 4.4 Shell Commands ";
$a+=" clear : Clear the display ";
$a+=" clear_vars : Clear vars and reload ~\bd_shell.ini ";
$a+=" print some text : Display some text ";
$a+=" var_name = value : Assign value to variable var_name ";
$a+=" var_name : Display value of var_name ";
$a+=" env : list all variables ";
#$a+=" conv,convert : Convert hex to int and vice versa ";
$a+=" hex2int : Convert hex to int . Replaces conv ";
$a+=" int2hex : Convert int to hex . Replaces conv ";
$a+=" sleep n : Sleep n seconds ";
$a+=" sleep_ms n : Sleep n msecs ";
$a+=" ?,h,help : Display help screen ";
$a+=" man,manual : Display this manual ";
$a+=" # : Comment line ";
$a+=" 4.5 Output Redirects ";
$a+=" > file : Pipe output to new file ";
$a+=" >> file : Pipe output to existing file ";
$a+=" | grep filter : Filter output on filter string ";
$a+=" ";
$a+="5.0 Numbers ";
$a+=" Numbers for Backdoor commands are all in hexadecimal. Zero padding ";
$a+=" is optional and no leading 0x0 is permitted. ";
$a+=" The hex2int and int2hex commands may be used for type conversions. ";
$a+=" Example: ";
$a+=" bd>bar = 100 ";
$a+=" bd>foo = ( hex2int bar ) ";
$a+=" bd>print foo ";
$a+=" 256 ";
$a+=" ";
$a+="6.0 Variables ";
$a+=" Variables are used for both bd_shell configuration and for address ";
$a+=" and data in Backdoor commands. An example use for variables would ";
$a+=" be to create a text file containing register names assigned to ";
$a+=" their PCI address and bitfield names like this: ";
$a+=" fpga_int_status = 00000050 ";
$a+=" bit_overtemp_in = 0800 ";
$a+=" A cryptic backdoor command like: ";
$a+=" bd>bs 00000050 0800 ";
$a+=" Can then be replaced by: ";
$a+=" bd>bs fpga_int_status bit_overtemp_int ";
$a+=" base_addr is a special variable. The value of base_addr is always ";
$a+=" added to the address of any Backdoor command. ";
$a+=" Variables may also be assigned to results from commands such as: ";
$a+=" bd>status_val = (rd fpga_int_status ) ";
$a+=" ";
$a+="7.0 Backdoor Scripting ";
$a+=" The 'source' command supports both single level and nested scripting";
$a+=" of Backdoor commands. An example use case would be to create many ";
$a+=" scripts containing Backdoor commands and then create a top level ";
$a+=" script that sources selected bottom level scripts. Any line ";
$a+=" beginning with a '#' in a script is ignored ( comment line ). ";
$a+=" The script bd_shell.ini is auto sourced after a 'cd' command if it ";
$a+=" exists in the new directory. ";
$a+=" ";
$a+="8.0 Python Scripting ";
$a+=" BD_SHELL is designed to use Python for advanced scripting needs. ";
$a+=" The following is a simple example of using python within BD_SHELL ";
$a+=" to modify a RAM table by adding +1 to every location. ";
$a+=" Example: ";
$a+=" bd>read_format = addr_data ";
$a+=" bd>r 0 20 > ram_in.txt # Dump RAM to file ";
$a+=" bd>python convert.py ram_in.txt ram_out.txt # Modify file ";
$a+=" bd>source ram_out.txt # Load RAM from file ";
$a+=" [ convert.py ] ";
$a+=" import sys; ";
$a+=" file_in = open ( sys.argv[1] , 'rt' ); ";
$a+=" file_out = open ( sys.argv[2] , 'wt' ); ";
$a+=" file_list = file_in.readlines();# Conv file to list ";
$a+=" for line in file_list: ";
$a+=" words = line.strip().split()+[None]*4;# Avoid IndexError ";
$a+=" if ( words[0] != None ): ";
$a+=" addr = words[0]; ";
$a+=" data = int( words[2], 16 ) + 1; ";
$a+=" print( addr ); ";
$a+=" file_out.write( addr + ' : %08x' % data + '\n' ); ";
$a+=" ";
$a+=" Using the Backdoor class in bd_client.py it is also possible to ";
$a+=" write and read registers directly from inside Python. ";
$a+=" Example: ";
$a+=" [ bd_client.py ] ";
$a+=" bd = Backdoor();# Establish a TCP Socket Connection to bd_server.py ";
$a+=" bd.wr( 0x0, [0x00000000] );# Write single DWORD ";
$a+=" bd.bs( 0x0, [0x00000001] );# BitSet DWORD ";
$a+=" dword_list = bd.rd( 0x0, 1 );# Read Single Dword ";
$a+=" print dword_list[0]; ";
$a+=" bd.wr( 0x0, [0x00000010,0x00000020] );# Burst Write ";
$a+=" dword_list = bd.rd( 0x0, 2 );# Burst Read ";
$a+=" for dword in dword_list: ";
$a+=" print '%08x' % dword; # '00000010','00000020' ";
$a+=" bd.close(); ";
$a+=" ";
$a+="9.0 Output Redirects ";
$a+=" Output Redirects to files and grep filter can be extremely useful. ";
$a+=" Examples: ";
$a+=" bd>env | grep int_reg : Find variable name containing 'int_reg'";
$a+=" bd>ls | grep foo : Find file with 'foo' in its name ";
$a+=" bd>r 0 10 | grep 0055 : Find 0055 in a memory read ";
$a+=" bd>more file | grep 0055 : Find 0055 in file ";
$a+=" ";
$a+="10.0 Read Format ";
$a+=" The variable read_format determines Backdoor output read format. ";
$a+=" By changing read_format, the output may either be data only or ";
$a+=" address and data with up to 8 dwords of data per line. ";
$a+=" read_format = data : Output is single dword of data per line ";
$a+=" read_format = addr_data : Output is 'addr : data' pair per line. ";
$a+=" read_format = name_data : Output is 'name : data' pair per line. ";
$a+=" read_format = columns : Output is 'addr : data data data ..' ";
$a+=" All modes except 'data' support dumping a read to a file and then ";
$a+=" sourcing that file to write the data back into memory. This supports";
$a+=" activities like dumping a large table, editing that table with vi ";
$a+=" and then loading that table back into memory. ";
$a+=" ";
$a+="11.0 Popup Dialog Boxes ";
$a+=" For advanced scripting it may be desirable to pause for human ";
$a+=" response and to prompt for values. BD_SHELL provides two popup ";
$a+=" dialog boxes. The return variable rts from popup_getvalue and ";
$a+=" popup_select may be used as a filename for source or python commands";
$a+=" or it may be used as a Backdoor variable for address or data. ";
$a+=" popup_message message : A dialog box with message and [OK] button.";
$a+=" to enter a variable value. ";
$a+=" popup_default : Default value for entry ";
$a+=" rts : Response value after [OK] ";
$a+=" popup_select items : A dialog box with a pulldown selection of ";
$a+=" specified items. If the variable ";
$a+=" popup_select_txt is set, it will be shown.";
$a+=" The variable rts will contain the selected";
$a+=" item after [OK] is pressed. ";
$a+=" popup_openfile : A file select dialog box. Result will be ";
$a+=" sourced or run with python. ";
$a+=" beep : Makes a beep. ";
$a+=" ";
$a+=" ";
$a+="12.0 Hardware Interface ";
$a+=" BD_SHELL.exe communicates either to a FTDI USB connection or via ";
$a+=" TCP Sockets to the BD_SERVER.PY Python script. The variable ";
$a+=" bd_connection is assigned either to 'usb' or 'tcp' to select. ";
$a+=" ";
$a+="13.0 License ";
$a+=" This software is released under the GNU GPLv2 license. ";
$a+=" Full license is available at http://www.gnu.org/ ";
$a+=" ";
$a+="[EOF] ";
if ( Test-Path $filename ) { Clear-content $filename; }
Add-Content $filename -value $a;
}# create_manual
###############################################################################
# replace_param() : Look for param in file and replace with new value
function replace_param( $args_array )
{
( $file, $param, $value ) = $args_array;
$lines = Get-Content $file;
$new_lines = @();
foreach ( $line in $lines )
{
if ( ($line.TrimStart(" ")[0] -ne "#") -and ( $line -ne "" ) )
{
$words = ($line -replace("\s+"," ")).split(" ");# Word split
if ( $words[0] -eq $param ) { $line = ( $param + " = " + $value); }
}
$new_lines += $line;
}
if ( Test-Path $file ) { Clear-content $file; }
Add-Content $file -value $new_lines;
}# replace_param()
###############################################################################
# load_ini_file() : Load var_hash from ini_file
# Format is: var_name = var_value
function load_ini_file( $args_array )
{
( $filename ) = $args_array;
$cwd_path = get-location;
if ( $filename -and ( Test-Path( $filename )) )
{
# print(("load_ini_file( $filename )"));
$ini_lines = Get-Content $filename;
foreach ( $line in $ini_lines )
{
if ( $line.TrimStart(" ")[0] -ne "#" )
{
$line = ($line -replace("="," = "));
$words = ($line -replace("\s+"," ")).split(" ")+@("","","","");
if ( $words[0] -eq "source" )
{
load_ini_file( @( $words[1] ) );# Read another ini file - Recursion
}
elseif ( $words[1] -eq "=" )
{
$key = $words[0];
$val = $words[2];
# print "hash_set() $key $val";
# Normal is "foo=bar" but mesa_slot is an exception as there
# may be multiples for various slots.
if ( $key -ne "mesa_slot" )
{
hash_set( @( $var_hash,$key, $val ) );
}
else
{
$words = ($val.split("#"));# Ignore comments at end of lines
$words = ($words[0].split(","));# Parse slot,min,max
$key = $words[0]; # Mesa Slot Number
$val = @( $words[1],$words[2] ); # Mesa Min,Max PCI addr for Slot
hash_set( @( $mesa_slot_hash,$key,$val ) );
# foreach ($h in $mesa_slot_hash.GetEnumerator())
# {
# print( "$($h.Name) : $($h.Value)" );
# }
# foreach( $each in $words )
# {
# print( $each );
# }
# display_results( $words );
# hash_set( @( $mesa_slot_hash,$key, $val ) );
}
}
}
}
set_ini_globals("");# Assign globals (argh) we need
}
}# load_ini_file()
###############################################################################
# --------------------------------------------------------------------------- #
# Backdoor library of commands
# create_bd() : Create a Backdoor ( opening USB COM Port, unlock Poke )
# bd_cmd() : Send a Command and wait for a response
# bd_configure() : Send a FPGA bitstream to Spartan3 board
function create_bd( $args_array )
{
# ( $usb_port ) = $args_array;
# [System.IO.Ports.SerialPort]::getportnames();# Displays all COM ports
$global:bd_connection = (hash_get(@($var_hash,"bd_connection")));#
$global:bd_protocol = (hash_get(@($var_hash,"bd_protocol" )));#
if ( $bd_connection -eq $False )
{
status( "`nERROR: Invalid bd_connection : Please check bd_shell.ini file" );
return $false;
}
if ( $bd_connection -eq "tcp" )
{
$port = [int](hash_get(@($var_hash,"tcp_port"))); # ie 21567
$server = (hash_get(@($var_hash,"tcp_ip_addr"))); # is "127.0.0.1"
try
{
$global:socket = new-object System.Net.Sockets.TcpClient($server, $port)
if ( $socket -eq $null )
{ print("ERROR: Can't Connect");throw("Can't Connect"); return ""; }
$global:stream = $socket.GetStream();
return $stream;
}
catch
{
status( "`nConnect Failed $bd_connection $server : $port" );
return $false;
}
}# if ( $bd_connection -eq "tcp" )
try
{
$usb_port = (hash_get(@($var_hash,"usb_port")));
if ( $usb_port -ne "DLL" )
{
$baud="921600";
# $baud="115200";# Needed for Bluetooth ?
$port=new-Object System.IO.Ports.SerialPort($usb_port,$baud,"None","8","1");
# $port.ReadTimeout = 1000;
$port.ReadTimeout = 5000;
$port.open();
if ( $bd_protocol -eq "poke" )
{
$port.WriteLine("!!"); # Unlock Backdoor in case its locked
}
if ( $bd_protocol -eq "mesa" )
{
$port.WriteLine("`n"); # Mesa Autobauds to LF after reset
}
}
else
{
if ( $dll_loaded -eq $False )
{
$dll_file = "FTD2XX_NET.dll"; # DLL file from FTDI
$dll_path = join-path -path $org_path -childpath $dll_file;
# print( "Loading $dll_path" );
if ( Test-Path( $dll_path ) )
{ [void][Reflection.Assembly]::LoadFile( $dll_path ); }
else
{ status( "`nERROR: Unable to load $dll_path" ); }
$port = New-Object FTD2XX_NET.FTDI;
$num_dev = 0;
$rts = $port.GetNumberOfDevices( [ref] $num_dev );
if ( $rts -ne "FT_OK" ) { print("ERROR: GetNumberOfDevices() $rts"); }
$rts = $port.OpenByIndex( 0 );# Assuming only 1 FTDI Device, Index 0
if ( $rts -ne "FT_OK" ) { print("ERROR: OpenByIndex() $rts"); }
$rts = $port.SetBaudRate( 921600 ); # Set Serial Baud
if ( $rts -ne "FT_OK" ) { print("ERROR: SetBaudRate() $rts"); }
# Set Data Characteristics
# use "-as" operator to cast string to type to access .NET enumerations
$arg1 = "FTD2XX_NET.FTDI.FT_DATA_BITS.FT_BITS_8" -as [type];
$arg2 = "FTD2XX_NET.FTDI.FT_STOP_BITS.FT_STOP_BITS_1" -as [type];
$arg3 = "FTD2XX_NET.FTDI.FT_PARITY.FT_PARITY_NONE" -as [type];
$rts = $port.SetDataCharacteristics( $arg1, $arg2, $arg3 );
if ( $rts -ne "FT_OK" ) { print("ERROR: SetDataCharacteristics() $rts"); }
$rts = $port.SetTimeouts( 5000, 0 );# ReadTimeout=5s, Write=None
if ( $rts -ne "FT_OK" ) { print("ERROR: SetTimeouts() $rts"); }
# Set Flow Control
$arg1 = "FTD2XX_NET.FTDI.FT_FLOW_NONE" -as [type];
$rts = $port.SetFlowControl( $arg1, 0,0 );
if ( $rts -ne "FT_OK" ) { print("ERROR: SetFlowControl() $rts"); }
$bytes_written = 0;
if ( $bd_protocol -eq "poke" )
{
$tx_str = "!!"; # Unlock Backdoor
}
else
{
$tx_str = "`n"; # Mesa autobauds to LF
}
$rts = $port.Write( $tx_str, $tx_str.Length, [ref] $bytes_written );
if ( $rts -ne "FT_OK" ) { print("ERROR: Write() $rts"); }
$global:dll_loaded = $port;
}
else
{
$port = $dll_loaded;
}
}
}
catch
{
status( "`nConnect Failed $usb_port" );
return $false;
}
return $port;
}# create_bd()
function bd_cmd( $args_array )
{
if ( $bd_protocol -ne "mesa" )
{
return bd_poke_cmd( $args_array );
}
else
{
return bd_mesa_cmd( $args_array );
}
}
# Take $cmd,$addr,$data is poke speak and convert to MesaBus protocol
# "\n"..."FFFF"."(F0-12-34-04)[11223344]\n" :
# 0xFF = Bus Idle ( NULLs )
# Packet
# B0 0xF0 = New Bus Cycle to begin ( Nibble and bit orientation )
# B1 0x12 = Slot Number, 0xFF = Broadcast all slots, 0xFE = NULL Dest
# B2 0x3 = Sub-Slot within the chip (0-0xF)
# 0x4 = Command Nibble for Sub-Slot
# B3 0x04 = Number of Payload Bytes (0-255)
# Command Nibbles for Sub-Slot-0 LocalBus:
# 0x0 = Bus Write
# 0x1 = Bus Read
# 0x2 = Bus Write Repeat ( burst to single address )
# 0x3 = Bus Read Repeat ( burst read from single address )
# Poke:
# w : Write Single or Burst
# r : Read Single or Burst
# W : Write Multiple to Single Address
# k : Read Multiple from Single Address
# Note: Poke "\n" after each command ( Write or Read ) - which turns out to
# be very slow. Mesa only sends "\n" after a read.
#####################################################
function bd_mesa_cmd( $args_array )
{
( $cmd, $addr, $data ) = $args_array;
if ( $bd_connection -eq "tcp" )
{
print("ERROR: No MesaBus support for bd_server.py yet");
# $rts = socket_send( @($socket, ($cmd + " " + $addr + " " + $data ) ) );
# return $rts;
return "";
}
else
{
# If MesaBus - convert from Poke protocol to MesaBus protocol
# addr is 44bits, 8 for slot, 4 sub-slot, 32 for local bus.
# Payload size is 4 bytes for Address plus any write bytes.
if ( $cmd -ceq "r" )
{
$data = (int2hex( hex2int( $data )));# Make sure 8 nibbles
}
else
{
$data = ($data -replace(" ",""));# Change "11 22 33" to "112233"
}
# if ( $cmd -ne "W" )
if ( $False )
{
print("------ bd_mesa_cmd() -------");
print( $cmd );
print( $addr );
print( $data );
print( $data.length );
}
$num_data_bytes = ( $data.length / 2 );
$mesa_header = ( "F0"+ $addr.substring(0,3) );# PreAmble,Slot,Sub-Slot
if ( $cmd -ceq "w" )
{
$mesa_header += "0";# Sub-Slot Command
$payload_len = ( 4 + $num_data_bytes );# Addr + Data
}
elseif ( $cmd -ceq "r" )
{
$mesa_header += "1";# Sub-Slot Command
$data = (int2hex((hex2int($data))+1));# Undo Poke N-1 for num DWORD Reads
$payload_len = ( 4 + 4 );# Addr + numDwords to Read
}
elseif ( $cmd -ceq "W" )
{
$mesa_header += "2";# Sub-Slot Command
$payload_len = ( 4 + $num_data_bytes );# Addr + Data
}
elseif ( $cmd -ceq "k" )
{
$mesa_header += "3";# Sub-Slot Command
$data = (int2hex((hex2int($data))+1));# Undo Poke N-1 for num DWORD Reads
$payload_len = ( 4 + 4 );# Addr + numDwords to Read
}
else
{
$mesa_header += $cmd;# Sub-Slot Command
$addr = "___________";# Slot+Subslot which will get substr reduced to NULL
$data = "";
$payload_len = 0;
}
# HERE
# Create Header+Payload . Note: Length of Payload is in Header
# WARNING!! : Does not check for 127 byte payload limit FIX FIX FIX !!!!!
$payload_len = ((int2hex( $payload_len )).substring(6,2));# 00-FF
$mesa_header += $payload_len;
$addr = ( $addr.substring(3,8) );# Remove 3 Nibbles for Slot+SubSlot
if ( $addr -eq "________" ) { $addr = ""; }
# Note: HW doesn't require LF, but sometimes Windows Buffer uses for flush
$tx_str = ("`n" + "FFFFFFFF" + $mesa_header + $addr + $data + "`n" );
if ( $False )
{
print( $tx_str );
}
# print( $tx_str );
# print( $mesa_header );
# print( $data );
# return "";
# # HERE : MesaBus requires a mesa_slot_range be defined that describes a
# # range of 32bit PCI addresses to a Mesa Slot Number of 0-253
# # MesaBurstLimits. 0x00-0x7F = 0-127 1-Byte Units ( 127 Bytes Max )
# # 0x81-0xFF = 1-127 128-Byte Units ( ~16K Bytes Max )
# if ( $data -ne "" ) { $tx_str = ( $cmd+" "+$addr+" "+$data+"`n" ); }
# else { $tx_str = ( $cmd+" "+$addr +"`n" ); }
$rts = "";# Default for Writes
$usb_port = (hash_get(@($var_hash,"usb_port")));
if ( $usb_port -ne "DLL" )
{
# HERE9
# Iterate each character to fix Arduino USB Serial Port isse with Line corruption
foreach( $each in $tx_str.ToCharArray() )
{
$bd.Write( $each );
}
# Having issues with Arduino USB corrupting strings. Seems to work sending single chars
# $bd.WriteLine( $tx_str );
# $bd.Write( $tx_str.ToCharArray() );
# For MesaBus - only Reads will ACK with a "\n" back - writes are posted.
if ( $cmd -ceq "r" -or $cmd -ceq "k" -or $cmd -ceq "A" )
{
try
{
$rts = $bd.ReadLine();
}# try
catch { $rts = "TIMEOUT ERROR"; }
}
}
else
{
# FTDI DLL Interface for FTD2XX_NET
$bytes_written = 0;
$rts = $bd.Write( $tx_str, $tx_str.Length, [ref] $bytes_written );
if ( $rts -ne "FT_OK" ) { print("ERROR: Write() $rts"); }
# Receive a String
$bytes_to_rd = 0;
$bytes_read = 0;
$rx_str = "";
$rx_full = "";
$done = $False; $timeout = 0;
# Read until "\n" Received
# For MesaBus - only Reads will ACK with a "\n" back - writes are posted.
#if ( $cmd -eq "r" -or $cmd -eq "k" )
if ( $cmd -eq "r" -or $cmd -eq "k" -or $cmd -ceq "A" )
{
while ( $done -eq $False -or $timeout -eq 100 )
{
$rts = $bd.GetRxBytesAvailable( [ref] $bytes_to_rd );
if ( $rts -ne "FT_OK" ) { print("ERROR: GetRxBytesAvailable() $rts"); }
$rts = $bd.Read( [ref] $rx_str, $bytes_to_rd, [ref] $bytes_read );
if ( $rts -ne "FT_OK" ) { print("ERROR: Read() $rts"); }
$rx_full = ( $rx_full + $rx_str );
if ( $rx_str -ne "" -and $rx_str.Substring($rx_str.Length-1,1) -eq "`n" )
{ $done = $True; }
$timeout += 1;
}
$rts = $rx_full.Substring(0,$rx_full.Length-1);# Remove LF
}
}# COM vs DLL
# if read, need to strip Ro header
if ( $cmd -eq "r" -or $cmd -eq "k" -or $cmd -ceq "A" )
{
$rts = $rts.substring(8);
}
# if read, need to convert "00000000aa55aa55" to "0000000 aa55aa55"
if ( ( $cmd -eq "r" -or $cmd -ceq "A" ) -and ( $rts.length -gt 8 ) )
{
$new_rts = "";
while ( $rts.length -ge 8 )
{
$new_rts += $rts.substring(0,8) + " ";
$rts = $rts.substring(8);
}
$rts = $new_rts;
}# if
return $rts;
}# if tcp vs usb
}# bd_mesa_cmd()
function bd_poke_cmd( $args_array )
{
( $cmd, $addr, $data ) = $args_array;
if ( $cmd -eq "uart_load" ) { $cmd = "configure"; } # sub the alias
if ( $bd_connection -eq "tcp" )
{
$rts = socket_send( @($socket, ($cmd + " " + $addr + " " + $data ) ) );
return $rts;
}
else
{
if ( $cmd -eq "configure" )
{
bd_configure( $addr );# addr=top.bit
return "";
}
# If MesaBus - convert from Poke protocol to MesaBus protocol
# HERE : MesaBus requires a mesa_slot_range be defined that describes a
# range of 32bit PCI addresses to a Mesa Slot Number of 0-253
# MesaBurstLimits. 0x00-0x7F = 0-127 1-Byte Units ( 127 Bytes Max )
# 0x81-0xFF = 1-127 128-Byte Units ( ~16K Bytes Max )
# if ( $bd_protocol -eq "mesa" )
if ( $data -ne "" ) { $tx_str = ( $cmd+" "+$addr+" "+$data+"`n" ); }
else { $tx_str = ( $cmd+" "+$addr +"`n" ); }
$usb_port = (hash_get(@($var_hash,"usb_port")));
if ( $usb_port -ne "DLL" )
{
$bd.WriteLine( $tx_str );
try
{
$rts = $bd.ReadLine();
}# try
catch { $rts = "TIMEOUT ERROR"; }
}
else
{
# FTDI DLL Interface for FTD2XX_NET
$bytes_written = 0;
$rts = $bd.Write( $tx_str, $tx_str.Length, [ref] $bytes_written );
if ( $rts -ne "FT_OK" ) { print("ERROR: Write() $rts"); }
# Receive a String
$bytes_to_rd = 0;
$bytes_read = 0;
$rx_str = "";
$rx_full = "";
$done = $False; $timeout = 0;
# Read until "\n" Received
while ( $done -eq $False -or $timeout -eq 100 )
{
$rts = $bd.GetRxBytesAvailable( [ref] $bytes_to_rd );
if ( $rts -ne "FT_OK" ) { print("ERROR: GetRxBytesAvailable() $rts"); }
$rts = $bd.Read( [ref] $rx_str, $bytes_to_rd, [ref] $bytes_read );
if ( $rts -ne "FT_OK" ) { print("ERROR: Read() $rts"); }
$rx_full = ( $rx_full + $rx_str );
if ( $rx_str -ne "" -and $rx_str.Substring($rx_str.Length-1,1) -eq "`n" )
{ $done = $True; }
$timeout += 1;
}
$rts = $rx_full.Substring(0,$rx_full.Length-1);# Remove LF
}# COM vs DLL
# if read, need to convert "00000000aa55aa55" to "0000000 aa55aa55"
if ( ( $cmd -eq "r" ) -and ( $rts.length -gt 8 ) )
{
$new_rts = "";
while ( $rts.length -ge 8 )
{
$new_rts += $rts.substring(0,8) + " ";
$rts = $rts.substring(8);
}
$rts = $new_rts;
}# if
return $rts;
}# if tcp vs usb
}# bd_cmd()
function bd_configure( $filename )
{
print(( "bd_configure() " + $filename ));
status("FPGA Config");
$sw = [Diagnostics.Stopwatch]::StartNew();# Measure this whole process
$mod_ext = [System.IO.Path]::GetExtension( $filename );
$fs = new-object IO.FileStream($filename, [IO.FileMode]::Open);
if ( $mod_ext -eq ".bit" )
{
$bin_reader = new-object IO.BinaryReader($fs);# top.bit
}
else
{
$bin_reader = new-object IO.Compression.GZipStream( $fs ,
[IO.Compression.CompressionMode]::Decompress);# top.bit.gz
}
$byte_array = new-object byte[] 1024;
while ( ($bytes_read = $bin_reader.Read($byte_array, 0, 1024)) -gt 0 )
{
$bd.Write( $byte_array, 0, $bytes_read );
}
$bin_reader.Close();
$sw.Stop()
$duration = ([int] $sw.ElapsedMilliseconds)/1000;# ms to s conversion
print( (" bd_configure() () took " + $duration + "s"));
print("done");
start-sleep -s 1;# Sleep for 1 second
$bd.DiscardInBuffer();# Flush RX
$bd.Write( "!!" );# Unlock
status("Ready");
}# bd_configure()
###############################################################################
# Send a string to a receiving socket server and wait for a response.
# This makes a small packet in clear ASCII of Packet_Length+Packet_Payload.
# The length is necessary due to Nagle's algorithm that can delay TCP delivery. Starting a packet with the
# Sending length 1st tells the receiving end how much to wait for.
# Every client send will get a response, even if 0 length - it must handshake.
# The packet length is sent in hex as 8 nibbles in ASCII
# $port = 21567;
# $server = "127.0.0.1";
# $global:socket = new-object System.Net.Sockets.TcpClient($server, $port)
# if ( $socket -eq $null ) { throw("Can't Connect"); }
# $global:stream = $socket.GetStream();
# $global:cnt = 0;
function socket_send( $args_array )
{
( $socket, $tx_payload ) = $args_array;
$tx_packet_length = ( int2hex( $tx_payload.length ) );# ie "00000003"
$tx_payload = ($tx_packet_length + $tx_payload );# "foo" -> "00000003foo"
# Take the tx_payload string and convert it to a byte array for Sockets