A friend and myself are working on creating a basic proof-of-concept decompiler that takes a string of hex values and returns a more readable version. Our code is listed below
testProgram = "00 00 FF 55 47 00"
# should look like this
# NOP
# NOP
# MOV 55 47
# NOP
pc = 0
output = ""
def byte(int):
return testProgram[3 * int:3 * int + 2]
def interpret():
currentByte = byte(pc)
if currentByte == "00":
pc += 1
return "NOP"
if currentByte == "FF":
returner = "MOV " + byte(pc + 1) + " " + byte(pc + 2)
pc += 3
return returner
while(byte(pc) != ""):
output += interpret() + "\n"
print(output)
however, running the code tells us this
Traceback (most recent call last):
File "BasicTest.py", line 62, in <module>
output += interpret() + "\n"
File "BasicTest.py", line 50, in interpret
currentByte = byte(pc)
UnboundLocalError: local variable 'pc' referenced before assignment
Because pc is a global variable, shouldn't it be usable from anywhere? Any and all help is appreciate - if you spot other errors, feel free to leave a comment pointing them out!
Been seeing this a lot lately. When you do
if currentByte == "00":
pc += 1 # <----------
return "NOP"
You're assigning to the local variable pc, but pc isn't declared yet in the local scope. If you want to modify the global pc you need to declare that explicitly at the top of the function
global pc
Related
this is the original repo i'm trying to run in my computer: https://github.com/kreamkorokke/cs244-final-project
import os
import matplotlib.pyplot as plt
import argparse
from attacker import check_attack_type
IMG_DIR = "./plots"
def read_lines(f, d):
lines = f.readlines()[:-1]
for line in lines:
typ, time, num = line.split(',')
if typ == 'seq':
d['seq']['time'].append(float(time))
d['seq']['num'].append(float(num))
elif typ == 'ack':
d['ack']['time'].append(float(time))
d['ack']['num'].append(float(num))
else:
raise "Unknown type read while parsing log file: %s" % typ
def main():
parser = argparse.ArgumentParser(description="Plot script for plotting sequence numbers.")
parser.add_argument('--save', dest='save_imgs', action='store_true',
help="Set this to true to save images under specified output directory.")
parser.add_argument('--attack', dest='attack',
nargs='?', const="", type=check_attack_type,
help="Attack name (used in plot names).")
parser.add_argument('--output', dest='output_dir', default=IMG_DIR,
help="Directory to store plots.")
args = parser.parse_args()
save_imgs = args.save_imgs
output_dir = args.output_dir
attack_name = args.attack
if save_imgs and attack_name not in ['div', 'dup', 'opt'] :
print("Attack name needed for saving plot figures.")
return
normal_log = {'seq':{'time':[], 'num':[]}, 'ack':{'time':[], 'num':[]}}
attack_log = {'seq':{'time':[], 'num':[]}, 'ack':{'time':[], 'num':[]}}
normal_f = open('log.txt', 'r')
attack_f = open('%s_attack_log.txt' % attack_name, 'r')
read_lines(normal_f, normal_log)
read_lines(attack_f, attack_log)
if attack_name == 'div':
attack_desc = 'ACK Division'
elif attack_name == 'dup':
attack_desc = 'DupACK Spoofing'
elif attack_name == 'opt':
attack_desc = 'Optimistic ACKing'
else:
raise 'Unknown attack type: %s' % attack_name
norm_seq_time, norm_seq_num = normal_log['seq']['time'], normal_log['seq']['num']
norm_ack_time, norm_ack_num = normal_log['ack']['time'], normal_log['ack']['num']
atck_seq_time, atck_seq_num = attack_log['seq']['time'], attack_log['seq']['num']
atck_ack_time, atck_ack_num = attack_log['ack']['time'], attack_log['ack']['num']
plt.plot(norm_seq_time, norm_seq_num, 'b^', label='Regular TCP Data Segments')
plt.plot(norm_ack_time, norm_ack_num, 'bx', label='Regular TCP ACKs')
plt.plot(atck_seq_time, atck_seq_num, 'rs', label='%s Attack Data Segments' % attack_desc)
plt.plot(atck_ack_time, atck_ack_num, 'r+', label='%s Attack ACKs' % attack_desc)
plt.legend(loc='upper left')
x = max(max(norm_seq_time, norm_ack_time),max(atck_seq_time, atck_ack_time))
y = max(max(norm_seq_num, norm_ack_num),max(atck_seq_num, atck_ack_num))
plt.xlim(0, x)
plt.ylim(0,y)
plt.xlabel('Time (s)')
plt.ylabel('Sequence Number (Bytes)')
if save_imgs:
# Save images to figure/
if not os.path.exists(output_dir):
os.makedirs(output_dir)
plt.savefig(output_dir + "/" + attack_name)
else:
plt.show()
normal_f.close()
attack_f.close()
if __name__ == "__main__":
main()
after running this i get this error
Traceback (most recent call last):
File "plot.py", line 85, in <module>
main()
File "plot.py", line 66, in main
plt.xlim(0, a)
File "/usr/lib/python3/dist-packages/matplotlib/pyplot.py", line 1427, in xlim
ret = ax.set_xlim(*args, **kwargs)
File "/usr/lib/python3/dist-packages/matplotlib/axes/_base.py", line 3267, in set_xlim
reverse = left > right
TypeError: '>' not supported between instances of 'int' and 'list'
Done! Please check ./plots for all generated plots.
how can i solve this problem? or better yet if there is another way of running this project? i installed matplotlib via pip3 install matplotlib command (same with scapy) and my main python version is python2 right now but i run the project with python3, could the issue be about this? what am i missing? or is it about mininet itself?
The problem is in this line
x = max(max(norm_seq_time, norm_ack_time),max(atck_seq_time, atck_ack_time))
IIUC, you wanna assign to x the maximum value among all those four lists. However, when you pass two lists to the max function, such as max(norm_seq_time, norm_ack_time), it will return the list it considers the greater one, and not the highest value considering both lists.
Instead, you can do something like:
x = max(norm_seq_time + norm_ack_time + atck_seq_time + atck_ack_time)
This will concatenate the four lists into a single one. Then, the function will return the highest value among all of them. You might wanna do that to the calculation of y as well.
If this is not what you wanted, or if you have any further issues, please let us know.
with the help of a friend we solved this problem by changing a part in code into this:
max_norm_seq_time = max(norm_seq_time) if len(norm_seq_time) > 0 else 0
max_norm_ack_time = max(norm_ack_time) if len(norm_ack_time) > 0 else 0
max_atck_seq_time = max(atck_seq_time) if len(atck_seq_time) > 0 else 0
max_atck_ack_time = max(atck_ack_time) if len(atck_ack_time) > 0 else 0
x = max((max_norm_seq_time, max_norm_ack_time,\
max_atck_seq_time, max_atck_ack_time))
plt.xlim([0,x])
max_norm_seq_num = max(norm_seq_num) if len(norm_seq_num) > 0 else 0
max_norm_ack_num = max(norm_ack_num) if len(norm_ack_num) > 0 else 0
max_atck_seq_num = max(atck_seq_num) if len(atck_seq_num) > 0 else 0
max_atck_ack_num = max(atck_ack_num) if len(atck_ack_num) > 0 else 0
plt.ylim([0, max((max_norm_seq_num, max_norm_ack_num,\
max_atck_seq_num, max_atck_ack_num))])
```
writing here just in case anyone else needs it.
While the following line is accepted on Python 3.6, On Python 3.4 I am getting a syntax error:
struct.pack_into('q' * len(GeoFence_lat_list)*2,buff,264,*GeoFence_lat_list, *GeoFence_lon_list)
Where GeoFence_lon_list is an array declared as:
Geo_Fence_list = []
GeoFence_lat_list = []
GeoFence_lon_list = []
Here is more code to review:
if (Polygon_available_size == 0):
buff = ctypes.create_string_buffer(workzone_size)
struct.pack_into('q' * 33, buff, 0, Speed_limit, Speed_Zone_lat, Speed_Zone_longi, Speed_Zone_heading_radians,
Speed_Zone_ITIS_CODE, Speed_Zone_2_lat, Speed_Zone_2_longi, Speed_Zone_2_heading_radians, Speed_Zone_2_ITIS_CODE,G20_lat, G20_longi,
G20_heading_radians, G20_ITIS_CODE,W20_lat, W20_longi, W20_heading_radians ,W20_ITIS_CODE,W21_5BR_lat,W21_5BR_longi, W21_5BR_heading_radians,
W21_5BR_ITIS_CODE,W21_5AR_lat,W21_5AR_longi, W21_5AR_heading_radians, W21_5AR_ITIS_CODE,First_Taper_lat,First_Taper_longi,
Last_Taper_lat, Last_Taper_longi, 2020, 2456,60, Polygon_available_size)
elif (int(Polygon_available_size) > 0):
geo_fence_size = struct.calcsize('q' * len(GeoFence_lat_list)*2)
#print("geo_fence_size", geo_fence_size)
workzone_size = workzone_size + geo_fence_size
buff = ctypes.create_string_buffer(workzone_size)
struct.pack_into('q' * 33, buff, 0, Speed_limit, Speed_Zone_lat, Speed_Zone_longi, Speed_Zone_heading_radians,
Speed_Zone_ITIS_CODE, Speed_Zone_2_lat, Speed_Zone_2_longi, Speed_Zone_2_heading_radians, Speed_Zone_2_ITIS_CODE,G20_lat, G20_longi,
G20_heading_radians, G20_ITIS_CODE,W20_lat, W20_longi, W20_heading_radians ,W20_ITIS_CODE,W21_5BR_lat,W21_5BR_longi, W21_5BR_heading_radians,
W21_5BR_ITIS_CODE,W21_5AR_lat,W21_5AR_longi, W21_5AR_heading_radians, W21_5AR_ITIS_CODE,First_Taper_lat,First_Taper_longi,
Last_Taper_lat, Last_Taper_longi, 2020, 2456,60, Polygon_available_size)
struct.pack_into('q', * len(GeoFence_lat_list)*2,buff,264,*GeoFence_lat_list, *GeoFence_lon_list)
GeoFence_lat_list.clear()
GeoFence_lon_list.clear()
packed_flag = 1
Python 3.4 only allows one unpacked argument per call.
Your original code is using multiple unpackings simply to append multiple lists into the byte buffer. You can achieve the same thing simply by calling struct.pack_into() multiple times, with appropriate offsets for each part.
start = 264
struct.pack_into(str(len(GeoFence_lat_list)) + 'q', buff, start, *GeoFence_lat_list);
start += 8 * len(GeoFence_lat_list)
struct.pack_into(str(len(GeoFence_lon_list)) + 'q', buff, start, *GeoFence_lon_list);
Hi I know there is alot of the same question out here already but I tried every single one of them and can't seem to get why it won't work.
Here is my code
Private Sub CallbackProcessAsync(sender As Object, args As System.Diagnostics.DataReceivedEventArgs)
Console.WriteLine(args.Data)
Me.Invoke(Sub() statusRichText.AppendText(args.Data & Environment.NewLine))
End Sub
Sub SuperUpload()
Dim oProcess As New Process()
AddHandler oProcess.ErrorDataReceived, AddressOf CallbackProcessAsync
AddHandler oProcess.OutputDataReceived, AddressOf CallbackProcessAsync
Dim oStartInfo As New ProcessStartInfo("C:\Users\RKjetski\AppData\Local\Programs\Python\Python37\python.exe", "test.py " + vInfoIframe.Text + " " + vInfoID.Text)
oStartInfo.UseShellExecute = False
oStartInfo.CreateNoWindow = True
oStartInfo.RedirectStandardError = True
oStartInfo.RedirectStandardOutput = True
oProcess.EnableRaisingEvents = True
oProcess.StartInfo = oStartInfo
oProcess.Start()
oProcess.BeginErrorReadLine()
oProcess.BeginOutputReadLine()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnSuperUpload.Click
Dim thread = New System.Threading.Thread(AddressOf SuperUpload)
thread.Start()
End Sub
The python file
import time
x = 0
while x < 5:
print(x)
time.sleep(2)
x = x +1
I get the following output but it's not live / in real time, the rich text box is empty until it read the program and then it prints everything instantly.
0
1
2
3
4
I am making a basic device using Python and I ran into this issue:
File "/home/pi/Adafruit_Python_SSD1306/PyOS_V0.py", line 178, in <module>
gameMenuApp()
File "/home/pi/Adafruit_Python_SSD1306/PyOS_V0.py", line 92, in gameMenuApp
draw.text((0, 32), gameMenuText, font=StartupFinishFont,
UnboundLocalError: local variable 'gameMenuText' referenced before assignment
This doesn't make sense because I assigned the variable at the beginning the file. I also put the code into a python linter online but I did not receive an error. Also, I removed most of the code to try to make it easier to read so if something doesn't make sense, don't worry about it. I posted the code on Github as well. https://github.com/raspiuser6969/PyOS
gameMenuText = " "
gameMenuSelect = int(1)
gameMenu = [' Pong ',' RPS ']
gameMenuSelect = int(1)
def pong():
def rps():
def gameMenuApp():
while GPIO.input(A_pin):
draw.rectangle((0,0,128,64), outline=0, fill=0)
draw.text((0,32), gameMenuText, font=StartupFinishFont, fill=255)
disp.image(image)
disp.display()
if not(GPIO.input(D_pin)):
gameMenuSelect = gameMenuSelect + 1
draw.rectangle((0,0,128,64), outline=0, fill=0)
disp.image(image)
disp.display()
print(gameMenuSelect)
if not(GPIO.input(U_pin)):
gameMenuSelect = gameMenuSelect - 1
draw.rectangle((0,0,128,64), outline=0, fill=0)
disp.image(image)
disp.display()
print(gameMenuSelect)
if gameMenuSelect == 1:
gameMenuText = gameMenu[gameMenuSelect - 1]
shutdownApp()
time.sleep(0.1)
if gameMenuSelect == 2:
gameMenuText = gameMenu[gameMenuSelect - 1]
rps()
time.sleep(0.1)
if 2 < gameMenuSelect:
gameMenuSelect = gameMenuSelect - 1
if 1 > gameMenuSelect:
gameMenuSelect = gameMenuSelect + 1
gameMenuText is defined in your file, but not in your function. You should either pass it as argument:
def gameMenuApp(gameMenuText, gameMenuSelect, gameMenu, gameMenuSelect):
or use it as global:
def gameMenuApp():
global gameMenuText, gameMenuSelect, gameMenu, gameMenuSelect
Same for your other globals, that's why I already added them.
How to debug "NameError: global name 'X' is not defined" in Python? I am pretty much new in Python. I am using jupyter_notebook with Python 2.7 to execute code. I am facing following error.
My code:
logFile = "NASAlog.txt"
def parseLogs():
parsed_logs=(sc
.textFile(logFile)
.map(parseApacheLogLine)
.cache())
access_logs = (parsed_logs
.filter(lambda s: s[1] == 1)
.map(lambda s: s[0])
.cache())
failed_logs = (parsed_logs
.filter(lambda s: s[1] == 0)
.map(lambda s: s[0]))
failed_logs_count = failed_logs.count()
if failed_logs_count > 0:
print 'Number of invalid logline: %d' % failed_logs.count()
for line in failed_logs.take(20):
print 'Invalid logline: %s' % line
print 'Read %d lines, successfully parsed %d lines, failed to parse %d lines' % (parsed_logs.count(), access_logs.count(), failed_logs.count())
return parsed_logs, access_logs, failed_logs
parsed_logs, access_logs, failed_logs = parseLogs()
ERROR
> NameError Traceback (most recent call last)
> <ipython-input-18-b365aa793252> in <module>()
> 24 return parsed_logs, access_logs, failed_logs
> 25
> ---> 26 parsed_logs, access_logs, failed_logs = parseLogs()
>
> <ipython-input-18-b365aa793252> in parseLogs()
> 2
> 3 def parseLogs():
> ----> 4 parsed_logs=(sc
> 5 .textFile(logFile)
> 6 .map(parseApacheLogLine)
>
> NameError: global name 'sc' is not defined
The problem is that you did never define sc. Therefore python can't find it. (Makes sense, doesn't it?)
Now there are several possible reasons:
- python is case-sensitive. Did you somewhere define SC instead of sc? ... Or Sc instead of sc?
You defined sc in another function (-> you defined it in a function outside parseLogs()). If you only define it there the variable will be local and just be available to the code inside the function. Add the line global sc to the first line of your function to make it accessible everywhere in you whole code.
You simply did not define sc.