Compare commits

...

10 Commits

Author SHA1 Message Date
036d64c035 防止编译失败时脚本无法退出 2025-06-28 13:30:57 +08:00
a0a0454a6d 编译时打印存储使用信息 2025-06-28 11:33:24 +08:00
b91c6b908d 编译时使用cpu核心个进程 2025-06-28 10:18:18 +08:00
5bf41295cf 有子进程失败时停止所有子进程 2025-06-26 21:08:34 +08:00
f86099aaf5 使用多进程加快编译速度 2025-06-26 19:24:21 +08:00
e8d9f26c5c 优化编译脚本 2025-06-26 17:54:49 +08:00
262d5d3f90 meke.py 使用命令行传入源文件 2025-06-26 16:15:07 +08:00
8928998479 消除一些编译警告 2025-06-26 00:33:08 +08:00
5411714133 添加try catch 原理注释 2025-06-25 19:10:40 +08:00
2cfdb4a84f 信号槽使用mythread 2025-06-25 11:29:06 +08:00
18 changed files with 324 additions and 311 deletions

View File

@@ -87,7 +87,6 @@ def create_lambda(text:str):
# 生成lambda展开后的文件 返回新的源文件列表
def search_lambda(src_list:list) -> list:
file_index=0
for index,item in enumerate(src_list):
with open(item,encoding='utf-8') as f:
d=f.read()
@@ -98,18 +97,20 @@ def search_lambda(src_list:list) -> list:
if(lam_index!=0 and d[lam_index-1]!='\n'):
continue
# 获取lambda文件名
dst_file_name=f"lambda_{file_index}_"+ os.path.basename(item)
file_index+=1
dst_path=os.path.join(TMP_DIR,dst_file_name)
src_list[index]=dst_path
base_path=os.path.join(TMP_DIR,os.path.dirname(item))
if not os.path.exists(base_path):
os.makedirs(base_path)
dst_file_name=os.path.join(base_path, os.path.basename(item))
src_list[index]=dst_file_name
# 不需要重新生成lambda文件
if(not check_rebuild(dst_path,[item])):
if(not check_rebuild(dst_file_name,[item])):
continue
lam_list=calc_lambda_text(d)
lambda_funs=[]
for lam in lam_list:
lambda_funs.append(create_lambda(lam))
with open(dst_path,mode='w+',encoding='utf-8') as f:
print(f"生成 {dst_file_name}")
with open(dst_file_name,mode='w+',encoding='utf-8') as f:
lambda_funs_text=""
for lam,fun in zip(lam_list,lambda_funs):
lambda_funs_text+=f"static {fun.return_type} {fun.name}({','.join(fun.params)}){'{'}{fun.body}{'}'}\n"

View File

@@ -122,14 +122,21 @@ void {signal_fun}({','.join(pars)}){'{'}
# 生成一个槽函数描述
def def_slot_fun_str(slot_fun:str,pars:list):
pars_str=""
for index,item in enumerate(get_pars_names(pars)):
pars_names=get_pars_names(pars)
for index,item in enumerate(pars_names):
if(index<len(pars)-1):
pars_str+=f"a->{item},"
pars_str+=f"self->{item},"
else:
pars_str+=f"a->{item}"
pars_str+=f"self->{item}"
unsued_pars=""
for item in pars_names:
unsued_pars+=f" (void){item};\n"
slot_fun_str=f"""
__attribute__((weak)) void {slot_fun}({','.join(pars)}){'{'}
{unsued_pars}{'}'}
static void {slot_fun}_caller(void *args){'{'}
{slot_fun}_args *a = args;
{slot_fun}_args *self = args;
{slot_fun}({pars_str});
{'}'}
"""
@@ -189,7 +196,7 @@ def def_slot_fun(line:str):
def gen_slot_fun_array(slot_fun_list:list) -> str:
item_list=[]
for item in slot_fun_list:
item_list.append(f" .func = {item.name}_caller,\n .name=\"{item.name}\"\n")
item_list.append(f" .func = {item.name}_caller,\n .name = \"{item.name}\"\n")
table_str="""
// 定义一个数据结构来保存槽封装函数与槽函数的关系
typedef struct {
@@ -256,6 +263,7 @@ def moc_file_create(out_file_path,scan_path_list):
# 不需要重新生成
if(not check_rebuild(out_file_path,list_file)):
return
print(f"生成 {out_file_path}")
with open(out_file_path,"w+") as f:
f.write("#include \"stdlib.h\"\n")
f.write("#include \"string.h\"\n")

44
main.c
View File

@@ -24,26 +24,21 @@ const char g_str[] =
__attribute__((weak)) int thread_fun(void* t) {
DBG_INFO("run in thread_fun.\n");
DBG_LOG("run in default thread_fun.\n");
// lex_analysis(g_str , strlen(g_str));
return 0;
}
int g_argc;
// char* g_argv[100];
char** g_argv;
void set_argv(int argc, char* argv[]) {
g_argc = argc;
// for (int i = 0;i < argc;i++) {
// g_argv[i] = argv[i];
// }
g_argv = argv;
}
int get_argv(char** argv[]) {
// *argv = *(char ***)(g_argv);
*argv = (g_argv);
return g_argc;
}
@@ -56,45 +51,12 @@ int main(int argc, char* argv[]) {
DBG_INFO("hello world.%ld\n", (size_t)pthread_self());
myth_create(thread_fun, NULL);
myth_create(thread_fun, NULL,"main_thread");
myth_join( );
myth_join();
}
#define func_def(...)
#define SLOT_FUN_RUN(fun,param) \
((slot_fun_def)(fun))(param[0],param[1],param[2],\
param[3],param[4],param[5],param[6],param[7])
typedef void (*slot_fun_def)(size_t a,size_t b,size_t c,size_t d,size_t e,size_t f,size_t g,size_t h);
void funptr_test(){
DBG_INFO("print from funptr_test fun.\n");
}
void add_test(int a,int b,void (*f)()){
DBG_INFO("add_fun:%d+%d=%d\n",a,b,a+b);
f();
}
void SystemInit()
{
func_def(int (int a,int b){
int a;
return;
});
size_t pars[8]={4,5,(size_t)funptr_test};
SLOT_FUN_RUN(add_test,pars);
}

148
make.py
View File

@@ -6,6 +6,8 @@
import os
import sys
import time
import dataclasses
from multiprocessing import Process,Queue,Value,cpu_count
from create_lambda_fun import search_lambda
from create_signal_fun import moc_file_create
@@ -18,14 +20,8 @@ from create_signal_fun import moc_file_create
CC = 'gcc'
# CC = 'C:\\ARM_GCC\\bin\\arm-none-eabi-gcc'
# AS = CC + ' -x assembler-with-cpp'
# HEX = 'C:\\ARM_GCC\\bin\\arm-none-eabi-objcopy' + ' -O ihex'
# BIN = 'C:\\ARM_GCC\\bin\\arm-none-eabi-objcopy' + ' -O binary -S'
CSRC = ["main.c","test/riscv_test.c","test/signal_test.c"]
CSRC = ["main.c"]
CINC = ['-Isoft',"-Iriscv_cpu", "-I./","-Itest"]
@@ -75,17 +71,15 @@ gcc -MM main.c -o build/main.d
def tran_path(path:str):
p=path.replace('\\','/')
p=p.replace('/','_')
if(p[0]=='.'):
return p[1:]
else:
return p
path=os.path.normpath(os.path.join(BUILD_DIR,path))
base_path=os.path.dirname(path)
if not os.path.exists(base_path):
os.makedirs(base_path)
return path
# 判断是否需要重新生成
def check_rebuild(dst:str,src:list):
# print(f"src:{src}")
if(not os.path.exists(dst)):
return True
dst_time=os.path.getmtime(dst)
@@ -95,9 +89,6 @@ def check_rebuild(dst:str,src:list):
src_time.sort()
if(src_time[-1]>dst_time):
return True
# for item in src_time:
# if(item>dst_time):
# return True
return False
@@ -115,57 +106,95 @@ def read_depend_files(name:str):
t+=line
t=t.split(':')[-1].strip()
t=t.split(' ')
# print(f"依赖列表{t}")
return t
@dataclasses.dataclass
class cmd_item_t:
cmd:str
info:str
def run_cmd(cmd_queue:Queue,cpu_index:int,return_list:Queue,failed_num):
while(not cmd_queue.empty()):
if(failed_num.value>0):
return
try:
cmd=cmd_queue.get_nowait()
except Exception:
return_list.put((cpu_index,True))
return
print(f"[{cpu_index}] {cmd.info}")
ret=os.system(cmd.cmd)
if(ret):
return_list.put((cpu_index,False))
failed_num.value+=1
return
return_list.put((cpu_index,True))
def run_cmd_queue(cmd_queue:Queue,cpu_num:int=cpu_count()):
if(cmd_queue.empty()):
return
process_list = []
return_list=Queue()
failed_num=Value('i',0)
for i in range(cpu_num):
p = Process(target=run_cmd,args=(cmd_queue,i,return_list,failed_num,))
p.start()
process_list.append(p)
for i in process_list:
i.join()
# 消耗掉所有数据防止进程无法退出
while not cmd_queue.empty():
cmd_queue.get()
while not return_list.empty():
i=return_list.get()
if(not i[1]):
print(f"子进程 [{i[0]}] 运行失败")
sys.exit(-1)
# 保证目标都存在
def check_exists(src:list):
for item in src:
for i in range(10):
if(os.path.exists(item)):
break
time.sleep(0.1)
# 生成依赖关系
def build_depend(src:list):
CmdQueue=Queue()
dst_list=[]
flags=f"{' '.join(CINC)} {' '.join(CDEF)} {' '.join(CFLAG)}"
for i in src:
name=tran_path(i).split('.')[0]
name=os.path.splitext(tran_path(i))[0]
dst='.'.join([name,'d'])
dst=os.path.join(BUILD_DIR,dst)
if(check_rebuild(dst,[i])):
cmd=f"{CC} -MM {i} -o {dst} {flags}"
print(cmd)
ret=os.system(cmd)
if(ret):
exit()
else:
# print(f"{i} 没有更新源文件")
pass
CmdQueue.put(cmd_item_t(cmd,f"更新 {dst}"))
dst_list.append(dst)
run_cmd_queue(CmdQueue)
# 生成中间文件
def build_object(src:list):
CmdQueue=Queue()
dst_list=[]
flags=f"{' '.join(CINC)} {' '.join(CDEF)} {' '.join(CFLAG)}"
for i in src:
name_l=tran_path(i).split('.')
name=name_l[0]
file_type=name_l[-1]
name_t=os.path.splitext(tran_path(i))
name=name_t[0]
file_type=name_t[-1]
dst='.'.join([name,'o'])
dst=os.path.join(BUILD_DIR,dst)
cd='.'.join([name,'d'])
cmd = ''
if(file_type in ['c','.C']):
cd=os.path.join(BUILD_DIR,cd)
if(file_type in ['.c','.C']):
if(check_rebuild(dst,read_depend_files(cd))):
cmd=f"{CC} -c {i} -o {dst} {flags}"
else:
# print(f"{i} 没有更新依赖关系")
pass
elif(file_type in ['s','S','asm','ASM']):
if(check_rebuild(dst,[i])):
# cmd=f"{AS} -c {i} -o {dst} {flags}"
pass
else:
# print(f"{i} 没有更新依赖关系")
pass
if(len(cmd)>0):
print(cmd)
ret=os.system(cmd)
if(ret):
exit()
CmdQueue.put(cmd_item_t(cmd,f"编译 {dst}"))
dst_list.append(dst)
run_cmd_queue(CmdQueue)
# 生成可执行文件
@@ -173,18 +202,15 @@ def build_target(src:list):
flags=f"{' '.join(CINC)} {' '.join(CDEF)} {' '.join(CFLAG)}"
obj_list=[]
for i in src:
name=tran_path(i).split('.')[0]
obj_list.append(BUILD_DIR+'/'+'.'.join([name,'o']))
name=os.path.splitext(tran_path(i))[0]
obj_list.append('.'.join([name,'o']))
dst=os.path.join(BUILD_DIR,TARGET)
if(check_rebuild(dst,obj_list)):
cmd=f"{CC} {' '.join(obj_list)} -o {dst} {flags}"
print(cmd)
print(f"链接 {dst}")
ret=os.system(cmd)
if(ret):
exit()
else:
# print(f"{dst} 没有更新的链接文件")
pass
sys.exit(-1)
def main():
@@ -192,22 +218,24 @@ def main():
global ASRC
if(not os.path.exists(BUILD_DIR)):
os.makedirs(BUILD_DIR)
# 在命令行中传入的源文件
CSRC+=sys.argv[1:]
CSRC+=find_type('soft',['c','C'])
CSRC+=find_type('riscv_cpu',['c','C'])
CSRC=search_lambda(CSRC)
moc_file_create(f"{BUILD_DIR}/moc_tmp.c",list(item[2:] for item in CINC))
CSRC.append(f"{BUILD_DIR}/moc_tmp.c")
# ASRC+=find_type('./',['s','S','asm','ASM'])
build_depend(CSRC)
build_object(CSRC)
# build_object(ASRC)
build_target(CSRC+ASRC)
if __name__ == "__main__":
main()
tick_start=time.time()
main()
tick_end=time.time()
print(f"cost: {tick_end-tick_start}")

View File

@@ -3,6 +3,8 @@ import os
import sys
import time
import shutil
import dataclasses
from multiprocessing import Process,Queue,Value,cpu_count
@@ -12,7 +14,7 @@ OBJCPY="riscv64-unknown-elf-objcopy"
OBJDUMP="riscv64-unknown-elf-objdump"
CFLAG=[
"-march=rv32i",
"-march=rv32i_zicsr",
"-mabi=ilp32",
"-ffunction-sections",
"-fdata-sections",
@@ -75,7 +77,7 @@ SRC=[
"riscv/rtthread/components/drivers/core/device.c"
]
LD_FILE="riscv.ld"
LD_FILE="riscv/riscv.ld"
TARGET="riscv"
@@ -84,17 +86,15 @@ OUTPUT="output"
def tran_path(path:str):
p=path.replace('\\','/')
p=p.replace('/','_')
if(p[0]=='.'):
return p[1:]
else:
return p
path=os.path.normpath(os.path.join(OUTPUT,path))
base_path=os.path.dirname(path)
if not os.path.exists(base_path):
os.makedirs(base_path)
return path
# 判断是否需要重新生成
def check_rebuild(dst:str,src:list):
# print(f"src:{src}")
if(not os.path.exists(dst)):
return True
dst_time=os.path.getmtime(dst)
@@ -104,9 +104,6 @@ def check_rebuild(dst:str,src:list):
src_time.sort()
if(src_time[-1]>dst_time):
return True
# for item in src_time:
# if(item>dst_time):
# return True
return False
@@ -124,56 +121,97 @@ def read_depend_files(name:str):
t+=line
t=t.split(':')[-1].strip()
t=t.split(' ')
# print(f"依赖列表{t}")
return t
@dataclasses.dataclass
class cmd_item_t:
cmd:str
info:str
def run_cmd(cmd_queue:Queue,cpu_index:int,return_list:Queue,failed_num):
while(not cmd_queue.empty()):
if(failed_num.value>0):
return
try:
cmd=cmd_queue.get_nowait()
except Exception:
return_list.put((cpu_index,True))
return
print(f"[{cpu_index}] {cmd.info}")
ret=os.system(cmd.cmd)
if(ret):
return_list.put((cpu_index,False))
failed_num.value+=1
return
return_list.put((cpu_index,True))
def run_cmd_queue(cmd_queue:Queue,cpu_num:int=cpu_count()):
if(cmd_queue.empty()):
return
process_list = []
return_list=Queue()
failed_num=Value('i',0)
for i in range(cpu_num):
p = Process(target=run_cmd,args=(cmd_queue,i,return_list,failed_num,))
p.start()
process_list.append(p)
for i in process_list:
i.join()
# 消耗掉所有数据防止进程无法退出
while not cmd_queue.empty():
cmd_queue.get()
while not return_list.empty():
i=return_list.get()
if(not i[1]):
print(f"子进程 [{i[0]}] 运行失败")
sys.exit(-1)
# 保证目标都存在
def check_exists(src:list):
for item in src:
for i in range(10):
if(os.path.exists(item)):
break
time.sleep(0.1)
# 生成依赖关系
def build_depend(src:list):
CmdQueue=Queue()
dst_list=[]
flags=f"{' '.join(INC)} {' '.join(DEF)} {' '.join(CFLAG)}"
for i in src:
name=tran_path(i).split('.')[0]
name=os.path.splitext(tran_path(i))[0]
dst='.'.join([name,'d'])
dst=os.path.join(OUTPUT,dst)
if(check_rebuild(dst,[i])):
cmd=f"{CC} -MM {i} -o {dst} {flags}"
print(cmd)
ret=os.system(cmd)
if(ret):
exit()
else:
# print(f"{i} 没有更新源文件")
pass
CmdQueue.put(cmd_item_t(cmd,f"更新 {dst}"))
dst_list.append(dst)
run_cmd_queue(CmdQueue)
# 生成中间文件
def build_object(src:list):
CmdQueue=Queue()
dst_list=[]
flags=f"{' '.join(INC)} {' '.join(DEF)} {' '.join(CFLAG)}"
for i in src:
name_l=tran_path(i).split('.')
name=name_l[0]
file_type=name_l[-1]
name_t=os.path.splitext(tran_path(i))
name=name_t[0]
file_type=name_t[-1]
dst='.'.join([name,'o'])
dst=os.path.join(OUTPUT,dst)
cd='.'.join([name,'d'])
cmd = ''
if(file_type in ['c','.C']):
cd=os.path.join(OUTPUT,cd)
if(file_type in ['.c','.C']):
if(check_rebuild(dst,read_depend_files(cd))):
cmd=f"{CC} -c {i} -o {dst} {flags}"
else:
# print(f"{i} 没有更新依赖关系")
pass
elif(file_type in ['s','S','asm','ASM']):
if(check_rebuild(dst,[i])):
elif(file_type in ['.s','.S','.asm','.ASM']):
if(check_rebuild(dst,read_depend_files(cd))):
cmd=f"{CC} -c {i} -o {dst} {flags}"
else:
# print(f"{i} 没有更新依赖关系")
pass
if(len(cmd)>0):
print(cmd)
ret=os.system(cmd)
if(ret):
exit()
CmdQueue.put(cmd_item_t(cmd,f"编译 {dst}"))
dst_list.append(dst)
run_cmd_queue(CmdQueue)
# 生成可执行文件
@@ -181,18 +219,17 @@ def build_target(src:list):
flags=f"{' '.join(INC)} {' '.join(DEF)} {' '.join(CFLAG)}"
obj_list=[]
for i in src:
name=tran_path(i).split('.')[0]
obj_list.append(OUTPUT+'/'+'.'.join([name,'o']))
name=os.path.splitext(tran_path(i))[0]
obj_list.append('.'.join([name,'o']))
dst=os.path.join(OUTPUT,TARGET)+".elf"
if(check_rebuild(dst,obj_list)):
cmd=f"{CC} {' '.join(obj_list)} -o {dst} {flags} -T{LD_FILE} -Wall -Wextra -nostartfiles -Wl,-Map,\"{OUTPUT}/{TARGET}.map\""
print(cmd)
cmd=f"{CC} {' '.join(obj_list)} -o {dst} {flags} -T{LD_FILE} \
-Wall -Wextra -nostartfiles -Wl,-Map,\"{OUTPUT}/{TARGET}.map\" \
-Wl,-print-memory-usage"
print(f"链接 {dst}")
ret=os.system(cmd)
if(ret):
exit()
else:
# print(f"{dst} 没有更新的链接文件")
pass
sys.exit()
@@ -212,4 +249,7 @@ def main():
if __name__ == "__main__":
tick_start=time.time()
main()
tick_end=time.time()
print(f"cost: {tick_end-tick_start}")

View File

@@ -67,7 +67,7 @@ const keywork_item_def g_keyword_table[ ] = {
TOKEN_DEF(continue,TOKEN_CONTINUE),
TOKEN_DEF(const,TOKEN_CONST),
TOKEN_DEF(static,TOKEN_STATIC),
TOKEN_DEF(unisgned,TOKEN_UNSIGNED),
TOKEN_DEF(unsigned,TOKEN_UNSIGNED),
TOKEN_DEF(typedef,TOKEN_TYPEDEF),
TOKEN_DEF(struct,TOKEN_STRUCT),
TOKEN_DEF(enum,TOKEN_ENUM),
@@ -238,7 +238,7 @@ int lex_print_token_list(lex_def* lex) {
token_list_node_def* t;
t = l->head;
while (t) {
printf("%4d[%3d,%3d],token=%4d \"%s\"\n" , t->token.line , t->token.pos ,
DBG_LOG("%4d[%3d,%3d],token=%4d \"%s\"\n" , t->token.line , t->token.pos ,
t->token.used , t->token.token, t->token.buff );
t = t->next;
}
@@ -512,7 +512,7 @@ int par_find_closed(token_def* t_list , int len , int token_s , int token_e) {
// 解析形参列表
int par_var_def( ) {
return 0;
}
@@ -522,7 +522,6 @@ int par_var_def( ) {
// 这个函数在 TOKEN_NAME 的时候调用 保证第一个token_def 为 TOKEN_NAME
// 返回 消耗的token 数
int par_var_fun_def(par_def* par , token_def* t_list , int len) {
token_def* t_start = t_list;
if (len < 2) {
throw_("缺少后续token在 %d 行,%d 位置" , t_list [0].line , t_list [0].pos);
}
@@ -551,6 +550,7 @@ int par_var_fun_def(par_def* par , token_def* t_list , int len) {
throw_("意外的token在 %d 行,%d 位置" , t_list [close_len + 1].line , t_list [close_len + 1].pos);
}
}
return 0;
}
@@ -604,20 +604,20 @@ int par_statement(par_def* p) {
break;
}
}
return 0;
}
// 输入token数组和长度
int par_parser(token_def* token_list , int len) {
int in_loop = 1;
int index = 0;
par_def* par = mem_calloc(1 , sizeof(par_def));
par->type = TTYPE_NONE;
par->attribute = 0;
par->token_list = token_list;
par->token_list_len = len;
par_statement(par);
return 0;
}

View File

@@ -7,91 +7,35 @@
#include <sys/sem.h>
#include <sys/types.h>
#include "errno.h"
#include "pthread.h"
#include "lambda.h"
#define CONSOLEBUF_SIZE 1024
#ifdef LINUX
union semun{
int val; /* Value for SETVAL */
struct semid_ds *buf; /* Buffer for IPC_STAT, IPC_SET */
unsigned short *array; /* Array for GETALL, SETALL */
struct seminfo *__buf; /* Buffer for IPC_INFO
(Linux-specific) */
};
void _sem_take(int semid)//得到钥匙
{
struct sembuf sop;
sop.sem_num = 0;//控制第一个信号量
sop.sem_op = -1;//钥匙数量减一6
sop.sem_flg = SEM_UNDO;
semop(semid,&sop,1);
}
void _sem_relase(int semid)//放回钥匙
{
struct sembuf sop;
sop.sem_num = 0;
sop.sem_op = 1;
sop.sem_flg = SEM_UNDO;
semop(semid,&sop,1);
}
int _sem_init(){
key_t key;
int mutex;
key = ftok(".",5345);
// printf("sem init, key=%llu\n",key);
mutex = semget(key,1,IPC_CREAT);//创建信号量
// printf("sem init, mutex=%d\n",mutex);
if(mutex<=0){
// printf("%d\n",errno);
}
union semun set;
set.val = 1;//钥匙数量为0
semctl(mutex,0,SETVAL,set);
return mutex;
}
#endif
#ifdef RT_THREAD
#include "rtthread.h"
#endif
typedef struct{
int inited;
int print_context;
#ifdef RT_THREAD
struct rt_mutex mutex;
#endif
#ifdef LINUX
int mutex;
#endif
pthread_mutex_t mutex; /* 互斥锁定义 */
dbg_dev *dev;
}self_def;
static self_def g_data;
lambda_use
static int dev_init(){
return 0;
}
static int dev_write(const uint8_t *data,size_t len){
size_t rb;
rb=fwrite(data,sizeof(uint8_t),len,stdout);
return (int)rb;
}
static dbg_dev g_dev_default={
.init=dev_init,
.write=dev_write,
static dbg_dev g_dev_default = {
.init = lambda(int() {
return 0;
}),
.write = lambda(int(const uint8_t * data,size_t len) {
size_t rb;
rb=fwrite(data,sizeof(uint8_t),len,stdout);
return (int)rb;
})
};
@@ -105,17 +49,12 @@ int debug_init(dbg_dev *dev)
}
if(self->inited==0)
{
#ifdef RT_THREAD
rt_mutex_init(&self->mutex,"debug_mutex",RT_IPC_FLAG_FIFO);
#endif
#ifdef LINUX
self->mutex=_sem_init();
#endif
pthread_mutex_init(&self->mutex, NULL);
self->dev=dev;
self->dev->init();
self->dev->write((const uint8_t *)"\r\n",2);
self->inited = 1;
debug_print_context(1);
debug_print_context(0);
DBG_LOG("debug inited.\r\n");
}
return 0;
@@ -136,12 +75,7 @@ void debug_log(const char *file,const char *fun,int line,int level,const char *f
static const char *level_str[]={"[info] ","[log] ","[warn] ","[err] "};
static int level_str_len[]={7,6,7,6};
if(level<DBG_LEVEL_INFO||level>DBG_LEVEL_ERR) return;
#ifdef RT_THREAD
rt_mutex_take(&self->mutex,RT_WAITING_FOREVER);
#endif
#ifdef LINUX
_sem_take(self->mutex);
#endif
pthread_mutex_lock(&self->mutex);
memcpy(log_buf,level_str[level],level_str_len[level]);
length = level_str_len[level];
if (self->print_context) {
@@ -159,12 +93,8 @@ void debug_log(const char *file,const char *fun,int line,int level,const char *f
}
log_buf[length]=0;
self->dev->write((const uint8_t *)log_buf,length);
#ifdef RT_THREAD
rt_mutex_release(&self->mutex);
#endif
#ifdef LINUX
_sem_relase(self->mutex);
#endif
pthread_mutex_unlock(&self->mutex);
}

View File

@@ -66,13 +66,16 @@ typedef struct{
}\
}
/*
try 的时候保存当前回溯点如果setjmp返回不为0 则已经产生异常回溯了,
这时最后一个回溯点的使命已经完成,所以删除最后一个回溯点
*/
#define __try(){\
exception_def *f=exception();\
jmp_fram **h=&f->jmp_head;\
int ret;\
jmp_next(h);\
ret= setjmp(((*h)->fram));\
ret = setjmp(((*h)->fram));\
if(ret){\
jmp_clear(h);\
}\
@@ -80,6 +83,11 @@ typedef struct{
}
#define try_ __try();if(exception()->ret==0){
/*
如果try一直执行到这里则不会产生回溯了最后一个回溯点的使命也已经完成了
所以这里删除最后一个回溯点
*/
#define catch_ {\
exception_def *f=exception();\
jmp_fram **h=&f->jmp_head;\

View File

@@ -8,18 +8,19 @@
#include "stdio.h"
#include "errno.h"
#include <semaphore.h>
#include "exception.h"
#include "mythread.h"
#include "debug.h"
static void* _thread(void* arg) {
static int _thread(void* arg) {
mythread_t* self = arg;
slot_list_with_pars *slot_p;
while (1) {
slot_p = NULL;
sem_wait(&self->sem);
pthread_mutex_lock(&self->lock);
printf("sem take\n");
DBG_INFO("sem take\n");
// 把槽列表里的函数取出来
if (self->slot_head) {
slot_p = self->slot_head;
@@ -28,14 +29,14 @@ static void* _thread(void* arg) {
pthread_mutex_unlock(&self->lock);
if (slot_p) {
if (slot_p->func) {
printf("args_p=%p\n", slot_p);
DBG_INFO("args_p=%p\n", slot_p);
slot_p->func(slot_p);
}
// 槽函数执行完之后释放
free(slot_p);
}
}
return NULL;
return 0;
}
@@ -52,7 +53,7 @@ void send_slot_fun(mythread_t *self, slot_list_with_pars* slot_p) {
}
pthread_mutex_unlock(&self->lock);
sem_post(&self->sem);
printf("add_slot_fun\n");
DBG_INFO("add_slot_fun\n");
}
@@ -79,11 +80,12 @@ void _connect(void* sig_obj, void* sig_fun, mythread_t* thread, void* slot_obj,
}
mythread_t *sigthread_init() {
mythread_t *sigthread_init(const char *name) {
mythread_t* self = calloc(1, sizeof(mythread_t));
pthread_mutex_init(&self->lock, NULL);
sem_init(&self->sem, 0, 0);
pthread_create(&self->tid, NULL, _thread, self);
// pthread_create(&self->tid, NULL, _thread, self);
self->tid = myth_create(_thread, self, name);
return self;
}

View File

@@ -20,7 +20,7 @@ typedef struct {
typedef struct {
pthread_mutex_t lock; /* 互斥锁定义 */
sem_t sem;
pthread_t tid;
pthread_t *tid;
slot_list_with_pars *slot_head;
} mythread_t;
@@ -41,7 +41,7 @@ typedef struct {
void send_slot_fun(mythread_t* self, slot_list_with_pars* slot_p);
mythread_t* sigthread_init();
mythread_t* sigthread_init(const char* name);
void _connect(void* sig_obj, void* sig_fun, mythread_t* thread, void* slot_obj, const char* slot_fun);

View File

@@ -6,6 +6,7 @@
#include "exception.h"
#include "stdio.h"
#include "debug.h"
#include "string.h"
@@ -30,9 +31,9 @@ static void *p_thread(void *t){
throw_("th->func was null.");
}
th->func(th->arg);
}catch_{
DBG_WARN("func:%08lx failed.\n",(size_t)th->func);
DBG_WARN("file=%s,line=%d,err=%s\n",exception()->file,exception()->line,exception()->log);
}catch_ {
DBG_WARN("thread(%s)=%08lx failed.\n",th->name,(size_t)th->func);
DBG_WARN("%s:%d err(%s)\n",exception()->file,exception()->line,exception()->log);
}
DBG_INFO("func:%08lx end.\n",(size_t)th->func);
th->end=1;
@@ -42,11 +43,13 @@ static void *p_thread(void *t){
int myth_create(int (*func)(void *t),void *t){
pthread_t* myth_create(int (*func)(void *t),void *t,const char *name){
myth_def *m=calloc(sizeof(myth_def),1);
m->func=func;
m->arg=t;
pthread_create(&m->th,NULL,p_thread,m);
m->arg = t;
if(name)
strncpy(m->name, name, FUNC_NAME_LEN - 1);
pthread_create(&m->th, NULL, p_thread, m);
{
self_def *s=&g_self;
if(s->head==NULL){
@@ -60,7 +63,7 @@ int myth_create(int (*func)(void *t),void *t){
m->last=myth;
}
}
return m->id;
return &m->th;
}
@@ -90,7 +93,7 @@ myth_def *myth_self(){
}
myth=myth->next;
}
printf("can not find myth.\n");
DBG_WARN("can not find myth.\n");
return NULL;
}

View File

@@ -6,6 +6,10 @@
#include "exception.h"
#define FUNC_NAME_LEN 20
typedef struct _myth_def{
struct _myth_def *next;
struct _myth_def *last;
@@ -14,14 +18,15 @@ typedef struct _myth_def{
size_t id;
size_t end;
int (*func)(void *);
void *arg;
void* arg;
char name[FUNC_NAME_LEN];
}myth_def;
int myth_create(int (*func)(void *t),void *t);
pthread_t* myth_create(int (*func)(void *t),void *t,const char *name);
int myth_join();
myth_def *myth_self();

View File

@@ -6,6 +6,7 @@
#include "string.h"
#include "main.h"
#include "lambda.h"
#include "debug.h"
typedef struct test_struct{
int a;
@@ -24,7 +25,7 @@ lambda_use
void run_callback(int (*fun)(int a, int b)) {
int a = fun(1, 2);
printf("a = %d\n", a);
DBG_LOG("a = %d\n", a);
}
@@ -50,30 +51,30 @@ int thread_fun(void* t)
{
void (*fun1)(int a, int b);
fun1 = lambda(void(int a, int b) {
printf("a = %d, b = %d\n", a, b);
DBG_LOG("a = %d, b = %d\n", a, b);
});
fun1(1, 2);
void (*fun2)(int a, int b);
fun2 = lambda(void(int a, int b) {
printf("a = %d, b = %d a*b=%d\n", a, b, a * b);
DBG_LOG("a = %d, b = %d a*b=%d\n", a, b, a * b);
});
fun2(3, 4);
void (*fun3)(void);
fun3 = lambda(void(void) {
int a = 3;
int b = 4;
printf("a = %d, b = %d a*b=%d\n", a, b, a * b);
DBG_LOG("a = %d, b = %d a*b=%d\n", a, b, a * b);
});
fun3();
void (*fun4)();
fun4 = lambda(void() {
int a = 5, b = 6;
printf("a = %d, b = %d a*b=%d\n", a, b, a * b);
DBG_LOG("a = %d, b = %d a*b=%d\n", a, b, a * b);
});
fun4();
unsigned int (*fun5)(int a, int b);
fun5 = lambda(unsigned int (int a,int b) {
printf("a = %d, b = %d a*b=%d\n", a, b, a * b);
DBG_LOG("a = %d, b = %d a*b=%d\n", a, b, a * b);
return 6;
});
fun5(3, 4);
@@ -85,9 +86,9 @@ int thread_fun(void* t)
return a * b * 10;
}));
printf("test_struct_var.sub(1,2) = %d\n", test_struct_var.sub(1, 2));
printf("test_struct_var.add(1,2) = %d\n", test_struct_var.add(1, 2));
printf("test_struct_var.sum(&test_struct_var) = %d\n", test_struct_var.sum(&test_struct_var));
DBG_LOG("test_struct_var.sub(1,2) = %d\n", test_struct_var.sub(1, 2));
DBG_LOG("test_struct_var.add(1,2) = %d\n", test_struct_var.add(1, 2));
DBG_LOG("test_struct_var.sum(&test_struct_var) = %d\n", test_struct_var.sum(&test_struct_var));
return 0;
}

View File

@@ -3,6 +3,7 @@
#include "errno.h"
#include "stdlib.h"
#include "string.h"
#include "debug.h"
#include "../main.h"
#include "../riscv_cpu/riscv.h"
@@ -16,19 +17,19 @@ long get_file_size(FILE *stream)
long file_size = -1;
long cur_offset = ftell(stream); // 获取当前偏移位置
if (cur_offset == -1) {
printf("ftell failed :%s\n", strerror(errno));
DBG_LOG("ftell failed :%s\n", strerror(errno));
return -1;
}
if (fseek(stream, 0, SEEK_END) != 0) { // 移动文件指针到文件末尾
printf("fseek failed: %s\n", strerror(errno));
DBG_LOG("fseek failed: %s\n", strerror(errno));
return -1;
}
file_size = ftell(stream); // 获取此时偏移值,即文件大小
if (file_size == -1) {
printf("ftell failed :%s\n", strerror(errno));
DBG_LOG("ftell failed :%s\n", strerror(errno));
}
if (fseek(stream, cur_offset, SEEK_SET) != 0) { // 将文件指针恢复初始位置
printf("fseek failed: %s\n", strerror(errno));
DBG_LOG("fseek failed: %s\n", strerror(errno));
return -1;
}
return file_size;
@@ -50,15 +51,15 @@ int thread_fun(void* t)
bin_name=argv[1];
}
printf("riscv start\n");
DBG_LOG("riscv start\n");
FILE *file=fopen(bin_name, "rb" );
if(file==NULL)
{
printf("open file %s error\n",bin_name);
DBG_LOG("open file %s error\n",bin_name);
return -1;
}
riscv.rom_size = get_file_size(file);
printf("rom size: %d\n", riscv.rom_size);
DBG_LOG("rom size: %d\n", riscv.rom_size);
riscv.rom = calloc((riscv.rom_size + 3) / 4, 4);
fread(riscv.rom, 1, riscv.rom_size, file);
fclose(file);

View File

@@ -7,6 +7,7 @@
#include "stdio.h"
#include "string.h"
#include "exception.h"
#include "debug.h"
#include "signal_test.h"
@@ -36,8 +37,8 @@
// // 封装函数用来调用实际的槽函数
// static void test_slot_caller(void* args) {
// test_slot_args* a = args;
// printf("test_slot_caller: %d %d\n", a->a, a->b);
// printf("args_p=%p\n", a);
// DBG_LOG("test_slot_caller: %d %d\n", a->a, a->b);
// DBG_LOG("args_p=%p\n", a);
// test_slot(a->self, a->a, a->b);
// }
@@ -103,27 +104,51 @@ static void mdelay(unsigned long mSec){
// 定义槽函数
slot test_slot(test_sig_obj2* obj, int a, int b) {
printf("test_slot var=%d\n", obj->test_var);
DBG_LOG("test_slot var=%d\n", obj->test_var);
obj->test_var = a + b;
printf("test_slot var=%d\n", obj->test_var);
DBG_LOG("test_slot var=%d\n", obj->test_var);
}
slot test_slot3(test_sig_obj3* obj, int a, int b) {
printf("test_slot3 a=%d, b=%d\n", a, b);
printf("obj->v1=%d, obj->v2=%d\n", obj->test_var, obj->test_var2);
DBG_LOG("test_slot3 a=%d, b=%d\n", a, b);
DBG_LOG("obj->v1=%d, obj->v2=%d\n", obj->test_var, obj->test_var2);
}
slot test_slot3_2(test_sig_obj3* obj, int a, int b, const char* c) {
printf("test_slot3_2 a=%d, b=%d, c=%s\n", a, b, c);
DBG_LOG("test_slot3_2 a=%d, b=%d, c=%s\n", a, b, c);
throw_("test_slot3_2 err");
}
static test_sig_obj g_sig_obj = { .test_var = 1, };
static test_sig_obj2 g_sig_obj2 = { .test_var = 2, };
static test_sig_obj3 g_sig_obj3;
int thread_fun_s(void* t) {
mythread_t* th = sigthread_init();
printf("thread_fun start\n");
void try_catch_test() {
try_ {
DBG_LOG("进入第一个try");
DBG_LOG("抛出异常");
throw_("第一个try抛出的异常");
}catch_ {
DBG_LOG("进入第一个catch");
try_ {
DBG_LOG("进入第二个try");
throw_("第二个try抛出的异常");
}catch_ {
DBG_LOG("进入第二个catch");
throw_("第二个catch抛出的异常");
}
}
}
int thread_fun(void* t) {
mythread_t* th = sigthread_init("signal_thread");
DBG_LOG("thread_fun start\n");
connect(&g_sig_obj, test_signal, th, &g_sig_obj2, test_slot);
connect(&g_sig_obj, test_signal, th, &g_sig_obj3, test_slot3);
connect(&g_sig_obj, test_signal2, th, &g_sig_obj3, test_slot3_2);
@@ -132,8 +157,8 @@ int thread_fun_s(void* t) {
mdelay(1000);
emit test_signal2(&g_sig_obj, 5, 6,"hello world");
mdelay(1000);
printf("test end\n");
throw_("my err");
DBG_LOG("test end\n");
try_catch_test();
return 0;
}

View File

@@ -7,7 +7,6 @@
const uint32_t iot_crc32_table[256] =
{
0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F,

View File

@@ -104,15 +104,15 @@ int thread_fun(void* t)
tmp[i] = bitmap[i];
}
ret = gpio_find_first_int((uint8_t*)tmp, sizeof(tmp), 0);
printf("ret=%d\n", ret - 1);
DBG_LOG("ret=%d\n", ret - 1);
ret = gpio_find_first_int((uint8_t*)tmp, sizeof(tmp), ret);
printf("ret=%d\n", ret - 1);
DBG_LOG("ret=%d\n", ret - 1);
for (int i = 0;i < sizeof(bitmap) / sizeof(bitmap[0]);i++) {
tmp[i] = bitmap[i];
}
ret = iot_bitmap_ffs_from((uint8_t*)tmp, sizeof(tmp), 0);
printf("ret=%d\n", ret - 1);
DBG_LOG("ret=%d\n", ret - 1);
ret = iot_bitmap_ffs_from((uint8_t*)tmp, sizeof(tmp), ret);
printf("ret=%d\n", ret - 1);
DBG_LOG("ret=%d\n", ret - 1);
}