単語ベクトルを変換する前に、ASTに変換してから単語ベクトルに変換する実現方法

実現のアイデア

周囲:

https://blog.csdn.net/lockhou/article/details/113883940の記事では、Winに一連のcファイルを実装して、対応するASTファイルを生成し、ASTファイルを介したノードマッチングを通じてテキストベクトルを生成しました。ファイルに抜け穴があるかどうかを判断するため、テキストベクトルを格納したtxtファイルに対応するASTを格納したtxtファイルに対応するacファイルと、対応する3つのファイルは同じ名前になります。

アイデア:

私たちの原則は、ファイルをTrain、Test、Validationに分類し、.cファイルを直接読み取って空の処理を行い、ワードプロセッシングを停止し、変換されたデータをピクルスファイルとして保存します。これは、後続のワードベクトル変換に使用されます。データモデルトレーニング、モデルテスト、およびモデル検証の要件。テキストベクトルを使用して構造情報を表すため、ファイルを直接読み取ることはできなくなりましたが、各cファイルの対応するテキストベクトルtxtファイルを直接読み取って同じ操作を実行し、次の単語ベクトル変換を提供します。モデルトレーニング、モデルテストでは、モデルによって検証されたデータには、作業を完了するための構造情報が含まれています。

勝利からLinuxプロセスへの移行

step1javaにjdkをインストールします

特定の手順については、記事を参照してください:https//blog.csdn.net/lockhou/article/details/113904085

step2movefiles.pyを変更します

最終的に、移動後にcファイルが配置されている各ディレクトリの同じレベルにフォルダを作成して、cファイルから抽出されたASTファイル(前処理済みフォルダに保存)と変換されたテキストベクターファイル(に保存)を保存することにしました。処理済みフォルダ))。したがって、Train、Test、Validationフォルダーとそれらの内部フォルダーを作成して、各組み合わせのNon_vulnerable_functionsフォルダーとVulnerable_functionsフォルダーの下に前処理および処理済みフォルダーを作成します。したがって、次のように46-55にコードを追加します。

saveDir = tempDir
        tempDir =  saveDir + '/'+ "Preprocessed"
        if not os.path.exists(tempDir):
            #Non_vulnerable_functions/Non_vulnerable_functions/Preprocessed
            os.mkdir(tempDir)
        tempDir =  saveDir + '/'+ "processed"
        if not os.path.exists(tempDir):
            #Non_vulnerable_functions/Non_vulnerable_functions/processed
            os.mkdir(tempDir)

step2ProcessCFilesWithCodeSensor.pyとProcessRawASTs_DFT.pyを変更します

これで、ASTとテキストベクトルを格納する場所ができたので、ProcessCFilesWithCodeSensor.pyファイルとProcessRawASTs_DFT.pyファイルを繰り返し呼び出すだけで済みます。したがって、呼び出しを容易にするために、2つのファイルを関数の形式に編成します。必要なパラメーターを形状として使用します。パラメーターは呼び出し時に渡されます。

ProcessCFilesWithCodeSensor.pyパラメーター:

1)CodeSensor_OUTPUT_PATH:各.cファイルを抽出し、ASTを.txtファイル
"G:\ thesis \ thesis \ ast \ function_representation_learningmaster \ FFmpeg \ Vulnerable_functions \ Preprocessed \"に保存されているアドレスとして保存します
。2)CodeSensor_PATH:コードセンサーの場所。 java
"D:\ codesensor \ CodeSensor.jar"(場所は固定されており、渡す必要はありません。つまり、パラメーターである必要はありません)
3)パス:.cファイルが保存されているディレクトリ
"G:\ thesis \ thesis \ ast \ function_representation_learning-master \ FFmpeg \ Vulnerable_functions"

ProcessRawASTs_DFT.pyパラメーター:

1)FILE_PATH:ASTのTXTが保存されているディレクトリ
"G:\ Thesis \ Thesis \ ast \ function_representation_learning-master \" + Project_Name + "\ Vulnerable_functions \ Preprocessed \"
2)Processed_FILE:txtファイル
"G:\テキストベクトル\ Thesis \ ast \ function_representation_learning-master \ "+ Project_Name +" \ Vulnerable_functions \ Processing \ "を格納するThesis"

上記のパラメータ要件に従って、ファイルの内容を次のように関数に編成します。

#ProcessCFilesWithCodeSensor.py

def codesensor(CodeSensor_OUTPUT_PATH,PATH):
	CodeSensor_PATH = "./Code/codesensor-codeSensor-0.2/CodeSensor.jar"
	Full_path = ""

	for fpathe,dirs,fs in os.walk(PATH):
  		for f in fs:
    			if (os.path.splitext(f)[1]=='.c'): # Get the .c files only
        			file_path = os.path.join(fpathe,f) # f is the .c file, which will be processed by CodeSensor
        
        # With each .c file open, CodeSensor will process the opened file and output all the processed files to a specified directory.
        # Full_path = CodeSensor_OUTPUT_PATH + "_" + f + ".txt"
        			Full_path = CodeSensor_OUTPUT_PATH + os.path.splitext(f)[0] + ".txt"
        			with open(Full_path, "w+") as output_file:
            				Popen(['/home/jdk1.8.0_65/bin/java', '-jar', CodeSensor_PATH, file_path], stdout=output_file, stderr=STDOUT)
            				output_file.close()



# ProcessRawASTs_DFT.py

def DepthFirstExtractASTs(file_to_process, file_name):
    
    lines = []
    subLines = ''
    
    f = open(file_to_process)
    try:
        original_lines = f.readlines()
        print(original_lines)
        #lines.append(file_name) # The first element is the file name.
        for line in original_lines:
            if not line.isspace(): # Remove the empty line.
                line = line.strip('\n')
                str_lines = line.split('\t')   
                #print (str_lines)
                if str_lines[0] != "water": # Remove lines starting with water.
                    #print (str_lines)
                    if str_lines[0] == "func":
                        # Add the return type of the function
                        subElement = str_lines[4].split() # Dealing with "static int" or "static void" or ...
                        if len(subElement) == 1:
                            lines.append(str_lines[4])
                        if subElement.count("*") == 0: # The element does not contain pointer type. If it contains pointer like (int *), it will be divided to 'int' and '*'.
                            if len(subElement) == 2:
                                lines.append(subElement[0])
                                lines.append(subElement[1]) 
                            if len(subElement) == 3:
                                lines.append(subElement[0])
                                lines.append(subElement[1])    
                                lines.append(subElement[2])
                        else:
                            lines.append(str_lines[4])
                        #lines.append(str_lines[5]) # Add the name of the function
                        lines.append("func_name") # Add the name of the function
                    if str_lines[0] == "params":
                        lines.append("params")                    
                    if str_lines[0] == "param":
                        subParamElement = str_lines[4].split() # Addd the possible type of the parameter
                        if len(subParamElement) == 1:
                            lines.append("param")
                            lines.append(str_lines[4]) # Add the parameter type
                        if subParamElement.count("*") == 0:
                            if len(subParamElement) == 2:
                                lines.append("param")
                                lines.append(subParamElement[0])
                                lines.append(subParamElement[1]) 
                            if len(subParamElement) == 3:
                                lines.append("param")
                                lines.append(subParamElement[0])
                                lines.append(subParamElement[1])    
                                lines.append(subParamElement[2])
                        else:
                            lines.append("param")
                            lines.append(str_lines[4]) # Add the parameter type                           
                    if str_lines[0] == "stmnts":
                        lines.append("stmnts")                    
                    if str_lines[0] == "decl":
                        subDeclElement = str_lines[4].split() # Addd the possible type of the declared veriable
                        #print (len(subDeclElement))
                        if len(subDeclElement) == 1:
                            lines.append("decl")
                            lines.append(str_lines[4]) # Add the type of the declared variable
                        if subDeclElement.count("*") == 0:
                            if len(subDeclElement) == 2:
                                lines.append("decl")
                                lines.append(subDeclElement[0])
                                lines.append(subDeclElement[1]) 
                            if len(subDeclElement) == 3:
                                lines.append("decl")
                                lines.append(subDeclElement[0])
                                lines.append(subDeclElement[1])    
                                lines.append(subDeclElement[2])
                        else:
                            lines.append("decl")
                            lines.append(str_lines[4]) # Add the type of the declared variable
                    if str_lines[0] == "op":
                        lines.append(str_lines[4])
                    if str_lines[0] == "call":
                        lines.append("call")
                        lines.append(str_lines[4])
                    if str_lines[0] == "arg":
                        lines.append("arg")
                    if str_lines[0] == "if":
                        lines.append("if")
                    if str_lines[0] == "cond":
                        lines.append("cond")
                    if str_lines[0] == "else":
                        lines.append("else")
                    if str_lines[0] == "stmts":
                        lines.append("stmts")
                    if str_lines[0] == "for":
                        lines.append("for") 	
                    if str_lines[0] == "forinit":
                        lines.append("forinit")
                    if str_lines[0] == "while":
                        lines.append("while")
                    if str_lines[0] == "return":
                        lines.append("return")
                    if str_lines[0] == "continue":
                        lines.append("continue")
                    if str_lines[0] == "break":
                        lines.append("break")
                    if str_lines[0] == "goto":
                        lines.append("goto")
                    if str_lines[0] == "forexpr":
                        lines.append("forexpr")
                    if str_lines[0] == "sizeof":
                        lines.append("sizeof")
                    if str_lines[0] == "do":
                        lines.append("do")   
                    if str_lines[0] == "switch":
                        lines.append("switch")   
                    if str_lines[0] == "typedef":
                        lines.append("typedef")
                    if str_lines[0] == "default":
                        lines.append("default")
                    if str_lines[0] == "register":
                        lines.append("register")
                    if str_lines[0] == "enum":
                        lines.append("enum")
                    if str_lines[0] == "union":
                        lines.append("union")
                    
        print(lines)
        subLines = ','.join(lines)
        subLines = subLines + "," + "\n"
    finally:
        f.close()
        return subLines
 
def text_vector(FILE_PATH,Processed_FILE):  
	big_line = []
	total_processed = 0

	for fpathe,dirs,fs in os.walk(FILE_PATH):
  		for f in fs:
    			if (os.path.splitext(f)[1]=='.txt'): # Get the .c files only
        			file_path = os.path.join(fpathe,f) # f is the .c file, which will be processed by CodeSensor
        			temp = DepthFirstExtractASTs(FILE_PATH + f, f)
        			print(temp)
        
        			f1 = open(Processed_FILE + os.path.splitext(f)[0]+".txt", "w")
        			f1.write(temp)
        			f1.close()
        			# big_line.append(temp)

       			#time.sleep(0.001)
        			total_processed = total_processed + 1

	print ("Totally, there are " + str(total_processed) + " files.")

step3movefiles.pyを変更します

これで、ASTファイルとテキストベクターファイルを保存する場所が確立されました。コードセンサー関数呼び出しを介してASTファイルを生成し、対応するディレクトリのPreprocessesフォルダーに保存するには、cファイルを含む各ディレクトリ内のすべてのcファイルを呼び出すだけです。 text_vector関数を呼び出すことにより、前処理されたディレクトリ内の各ASTファイルがテキストベクトルファイルに変換され、対応するディレクトリの続行フォルダーの下に保存されるため、movefiles.pyの最後、つまり作成後に次のコードを追加します。すべてのフォルダ:

from  ProcessCFilesWithCodeSensor import *
from  ProcessRawASTs_DFT import *

for i in range(len(FirstDir)):
    codesensor(Non_vul_func_trainDir[i]+"/Preprocessed/",Non_vul_func_trainDir[i])
    codesensor(Non_vul_func_testDir[i]+"/Preprocessed/",Non_vul_func_testDir[i])
    codesensor(Non_vul_func_validationDir[i]+"/Preprocessed/",Non_vul_func_validationDir[i])
    codesensor(Vul_func_trainDir[i]+"/Preprocessed/",Vul_func_trainDir[i])
    codesensor(Vul_func_testDir[i]+"/Preprocessed/",Vul_func_testDir[i])
    codesensor(Vul_func_validationDir[i]+"/Preprocessed/",Vul_func_validationDir[i])
    text_vector(Non_vul_func_trainDir[i]+"/Preprocessed/",Non_vul_func_trainDir[i]+"/processed/")
    text_vector(Non_vul_func_testDir[i]+"/Preprocessed/",Non_vul_func_testDir[i]+"/processed/")
    text_vector(Non_vul_func_validationDir[i]+"/Preprocessed/",Non_vul_func_validationDir[i]+"/processed/")
    text_vector(Vul_func_trainDir[i]+"/Preprocessed/",Vul_func_trainDir[i]+"/processed/")
    text_vector(Vul_func_testDir[i]+"/Preprocessed/",Vul_func_testDir[i]+"/processed/")
    text_vector(Vul_func_validationDir[i]+"/Preprocessed/",Vul_func_validationDir[i]+"/processed/")
    

step4removeComments_Blanks.pyファイルとLoadCFilesAsText.pyファイルを変更します

cファイルを生成されたテキストベクターファイルに置き換えたいため、removeComments_Blanks.pyファイルとLoadCFilesAsText.pyファイルでは、cファイルが直接読み取られ、ファイルの内容が削除されます。ピクルスファイルの場合。したがって、cファイルを生成されたテキストベクターファイルに置き換え、処理済みフォルダー内のテキストベクターファイルを読み取る必要があります。txtファイルを読み取るその他の操作は変更されません。
したがって、すべてのremoveComments_Blanks.pyファイルとLoadCFilesAsText.pyファイルのcファイルの読み取りを表すすべてのディレクトリを、cファイルと同じディレクトリの処理済みフォルダーに展開して、テキストベクトルファイルを読み取らせる必要があります。ファイルタイプcファイルを検索する代わりに、txtファイルを検索できます。

step5次に、単語ベクトルファイルとトレーニングファイルおよびテストファイルを通常どおり実行します。

おすすめ

転載: blog.csdn.net/lockhou/article/details/113921061