inital commit 1

This commit is contained in:
mxdyeah committed 2026-07-08 19:25:32 +08:00
commit 07738cacaf
76 files changed
+9477

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016 Yanghe Sun
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+28
View File
@@ -0,0 +1,28 @@
# Makefile for Judger's lua binding
CC = gcc
LDFLAGS ?= -pthread -lseccomp -fPIC -shared
LUAVER ?= 5.3
LUAVERPURE ?= $(subst .,,${LUAVER})
CFLAGS ?= -Wall -Werror -O3 -std=c99 -fPIC -I/usr/include/lua${LUAVER} -DLUA${LUAVERPURE}
JUDGER_OBJECTS = child.o killer.o logger.o runner.o rules/c_cpp.o rules/general.o
OBJECTS = $(addprefix ../../src/,${JUDGER_OBJECTS}) judger.o
.PHONY: all test install clean
all: judger.so
judger.so: ${OBJECTS}
${CC} ${OBJECTS} ${LDFLAGS} -o judger.so
install: all
@mkdir -p /usr/local/lib/lua/${LUAVER}/
@cp -f judger.so /usr/local/lib/lua/${LUAVER}/
clean:
@rm -f ${OBJECTS} judger.so
%.o: %c
${CC} ${CFLAGS} -o $@ -c $<
+220
View File
@@ -0,0 +1,220 @@
/*
Lua Binding:
The MIT License (MIT)
Copyright (c) <2016> <avaicode>
Judger:
The Star And Thank Author License (SATA)
Copyright (c) <Qingdao University Online Judge Dev Team> <[email protected]>
*/
/*
Usage:
In Lua: require "judger"
In C: luaL_requiref(L, "judger", luaopen_judger, 1)
*/
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <lua.h>
#include <lauxlib.h>
#include "../../src/runner.h"
typedef struct ConfItem {
const char* name;
int value;
} ConfItem;
static ConfItem conf_item[] = {
{"_VERSION", VERSION},
{"_UNLIMITED", UNLIMITED},
{"_RESULT_WRONG_ANSWER", WRONG_ANSWER},
{"_RESULT_SUCCESS", SUCCESS},
{"_RESULT_CPU_TIME_LIMIT_EXCEEDED", CPU_TIME_LIMIT_EXCEEDED},
{"_RESULT_REAL_TIME_LIMIT_EXCEEDED", REAL_TIME_LIMIT_EXCEEDED},
{"_RESULT_MEMORY_LIMIT_EXCEEDED", MEMORY_LIMIT_EXCEEDED},
{"_RESULT_RUNTIME_ERROR", RUNTIME_ERROR},
{"_RESULT_SYSTEM_ERROR", SYSTEM_ERROR},
{"_ERROR_INVALID_CONFIG", INVALID_CONFIG},
{"_ERROR_FORK_FAILED", FORK_FAILED},
{"_ERROR_PTHREAD_FAILED", PTHREAD_FAILED},
{"_ERROR_WAIT_FAILED", WAIT_FAILED},
{"_ERROR_ROOT_REQUIRED", ROOT_REQUIRED},
{"_ERROR_LOAD_SECCOMP_FAILED", LOAD_SECCOMP_FAILED},
{"_ERROR_SETRLIMIT_FAILED", SETRLIMIT_FAILED},
{"_ERROR_DUP2_FAILED", DUP2_FAILED},
{"_ERROR_SETUID_FAILED", SETUID_FAILED},
{"_ERROR_EXECVE_FAILED", EXECVE_FAILED},
{"_ERROR_SPJ_ERROR", SPJ_ERROR}
};
static const int conf_item_size = sizeof(conf_item) / sizeof(ConfItem);
typedef struct ArgMask {
const char* name;
int t; //Should be lua_type
int nil_accept;
} ArgMask;
static ArgMask arg_mask[] = {
{"max_cpu_time", LUA_TNUMBER, 0},
{"max_real_time", LUA_TNUMBER, 0},
{"max_memory", LUA_TNUMBER, 0},
{"max_process_number", LUA_TNUMBER, 0},
{"max_output_size", LUA_TNUMBER, 0},
{"exe_path", LUA_TSTRING, 0},
{"input_path", LUA_TSTRING, 0},
{"output_path", LUA_TSTRING, 0},
{"error_path", LUA_TSTRING, 0},
{"log_path", LUA_TSTRING, 0},
{"seccomp_rule_name", LUA_TSTRING, 1},
{"args", LUA_TTABLE, 0},
{"env", LUA_TTABLE, 0},
{"uid", LUA_TNUMBER, 0},
{"gid", LUA_TNUMBER, 0}
};
static const int arg_mask_size = sizeof(arg_mask) / sizeof(ArgMask);
static int global_judge(lua_State* L);
static const struct luaL_Reg judger[] = {
{"run", global_judge},
{NULL, NULL}
};
static char* _strdup(const char* s) {
char* t = NULL;
if (s && (t = (char*)malloc(strlen(s) + 1)))
strcpy(t, s);
return t;
}
static void destory_config(struct config* config) {
int i = 0;
free(config->exe_path);
free(config->input_path);
free(config->output_path);
free(config->error_path);
free(config->log_path);
free(config->seccomp_rule_name);
for (; i < 256; ++i) {
free(config->args[i]);
free(config->env[i]);
}
}
static int lua_checkstringtable(lua_State* L, char** dst, int max_size, int* dst_size) {
int table_index = lua_gettop(L);
int table_size = 0;
lua_pushnil(L);
while (0 != lua_next(L, table_index)) {
if (lua_type(L, -1) != LUA_TSTRING)
return 0;
if (lua_type(L, -2) != LUA_TNUMBER)
return 0;
if (table_size == max_size)
return 0;
dst[table_size] = _strdup(lua_tostring(L, -1));
table_size++;
lua_pop(L, 1);
}
if (dst_size != NULL)
*dst_size = table_size;
return 1;
}
static int global_judge(lua_State* L) {
int i = 0, table_size = 0;
struct config config;
struct result result;
void* arg_refs[arg_mask_size];
arg_refs[0] = &config.max_cpu_time;
arg_refs[1] = &config.max_real_time;
arg_refs[2] = &config.max_memory;
arg_refs[3] = &config.max_process_number;
arg_refs[4] = &config.max_output_size;
arg_refs[5] = &config.exe_path;
arg_refs[6] = &config.input_path;
arg_refs[7] = &config.output_path;
arg_refs[8] = &config.error_path;
arg_refs[9] = &config.log_path;
arg_refs[10] = &config.seccomp_rule_name;
arg_refs[11] = &config.args;
arg_refs[12] = &config.env;
arg_refs[13] = &config.uid;
arg_refs[14] = &config.gid;
memset(&config, 0, sizeof(config));
luaL_checktype(L, 1, LUA_TTABLE);
for (; i < arg_mask_size; ++i) {
lua_pushstring(L, arg_mask[i].name);
lua_gettable(L, -2);
if (lua_type(L, -1) != arg_mask[i].t && !(arg_mask[i].nil_accept && lua_type(L, -1) == LUA_TNIL))
return destory_config(&config), luaL_error(L, "bad argument %s", arg_mask[i].name);
switch (lua_type(L, -1)) {
case LUA_TNUMBER:
*(int*)arg_refs[i] = lua_tointeger(L, -1);
break;
case LUA_TSTRING:
*(char**)arg_refs[i] = _strdup(lua_tostring(L, -1));
break;
case LUA_TTABLE:
if (lua_checkstringtable(L, (char**)arg_refs[i], 256 - 1, &table_size) == 0) {
destory_config(&config);
return luaL_error(L, "bad argument %s (item must be a string)", arg_mask[i].name);
}
*((char**)arg_refs[i] + table_size) = NULL;
break;
case LUA_TNIL:
*(char**)arg_refs[i] = NULL;
break;
}
lua_pop(L, 1);
}
run(&config, &result);
lua_newtable(L);
lua_pushstring(L, "cpu_time"); lua_pushnumber(L, result.cpu_time); lua_rawset(L, -3);
lua_pushstring(L, "real_time"); lua_pushnumber(L, result.real_time); lua_rawset(L, -3);
lua_pushstring(L, "memory"); lua_pushnumber(L, result.memory); lua_rawset(L, -3);
lua_pushstring(L, "signal"); lua_pushnumber(L, result.signal); lua_rawset(L, -3);
lua_pushstring(L, "exit_code"); lua_pushnumber(L, result.exit_code); lua_rawset(L, -3);
lua_pushstring(L, "error"); lua_pushnumber(L, result.error); lua_rawset(L, -3);
lua_pushstring(L, "result"); lua_pushnumber(L, result.result); lua_rawset(L, -3);
assert(lua_gettop(L) == 2);
destory_config(&config);
return 1;
}
int luaopen_judger(lua_State* L) {
int i = 0;
#ifdef LUA51
luaL_register(L, "judger", judger);
#else
luaL_newlib(L, judger);
#endif
for (; i < conf_item_size; ++i) {
lua_pushstring(L, conf_item[i].name);
lua_pushnumber(L, conf_item[i].value);
lua_rawset(L, -3);
}
return 1;
}
+9
View File
@@ -0,0 +1,9 @@
{
"targets": [
{
"target_name": "judger",
'cflags_cc!': [ '-std=c++11','-O2' ],
"sources": [ "judger.cc"],
}
]
}
+234
View File
@@ -0,0 +1,234 @@
#include "node.h"
#include <cstdio>
#include <cstring>
#include <string>
#include <cstdlib>
#include <sys/wait.h>
#include <unistd.h>
namespace demo {
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::JSON;
using v8::Local;
using v8::Int32;
using v8::Array;
using v8::Integer;
using v8::Uint32;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Value;
using v8::MaybeLocal;
using v8::Exception;
using v8::Context;
/* 转成数字 */
bool ToNumber(Isolate * isolate,Local<Value> &args,char * key,std::string &str){
Local<Context> context= isolate->GetCurrentContext();
Local<Value> val = args->ToObject()->Get(context,String::NewFromUtf8(isolate,key)).ToLocalChecked();
if(val->IsNullOrUndefined())
return true;
else if( val->IsNumber()){
Local<Integer> num = val->ToInteger(context).ToLocalChecked();
str+=" --";
str+=std::string(key);
str+="=";
str+=std::to_string(num->Value());
return true;
}
else {
isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate,"typeof argument must be Object!")));
return false;
}
}
char * _ToCharPTR(Local<Value> &val,Local<Context> &context,char * str_content){
String::Utf8Value str_val( val->ToString(context).ToLocalChecked());
strcpy(str_content,*str_val);
return str_content;
}
/* 转成字符串 */
bool ToCStr(Isolate * isolate,Local<Value> &args,char * key,std::string &str){
char str_content[255]={0};
Local<Context> context= isolate->GetCurrentContext();
Local<Value> val;
if(args->IsObject())
val = args->ToObject()->Get(context,String::NewFromUtf8(isolate,key)).ToLocalChecked();
else
val = args;
if(val->IsNullOrUndefined())
return true;
else if(val->IsString()){
_ToCharPTR(val,context,str_content);
str+=" --";
str+=std::string(key);
str+="=";
str+=std::string(str_content);
return true;
}
else {
char ret[100];
sprintf(ret,"typeof %s must be String!",key);
isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate,ret)));
return false;
}
}
/**
* 参数:
* {
* max_cpu_time
* max_real_time
* max_memory
* memory_limit_check_only ??
* max_stack
* max_process
* max_output_size
* exe_path
* input_path
* output_path
* error_path
* args:[]
* env:[]
* }
* 返回值
* {
* cpu_time
* real_time
* memory
* signal
* exit_code
* result
* error:
* }
*/
void Method(const FunctionCallbackInfo<Value>& args)
{
Isolate* isolate = args.GetIsolate();
Local<Context> context= isolate->GetCurrentContext();
std::string _args = "/usr/lib/judger/libjudger.so";
if( !args[0]->IsObject()){
isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate,"typeof argument must be Object!")));
}
Local<Value> argument = args[0];
std::string int_vars[] = { "max_cpu_time","max_real_time","max_memory","memory_limit_check_only","max_stack","max_process_number","max_output_size","uid","gid"};
std::string str_vars[] = { "input_path","output_path","error_path","exe_path","log_path","seccomp_rule_name"};
for( auto var :int_vars){
if( ! ToNumber(isolate,argument,(char *)var.c_str(),_args))
return;
}
for( auto var : str_vars){
if( !ToCStr(isolate,argument,(char *)var.c_str(),_args))
return;
}
/* args */
Local<Value> margs= argument->ToObject()->Get(context,String::NewFromUtf8(isolate,"args")).ToLocalChecked();
if( margs->IsNullOrUndefined()){
;
}
else if( margs->IsArray()){
Local<Array> args = margs.As<Array>();
int len = args->Length();
int i;
for(i=0;i<len;i++){
Local<Value> in = args->Get(i);
if( !ToCStr(isolate,in,(char *)"args",_args))
return;
}
}
else { //not array
isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate,"args must be a list")));
return;
}
Local<Value> menv= argument->ToObject()->Get(context,String::NewFromUtf8(isolate,"env")).ToLocalChecked();
if( menv->IsNullOrUndefined()){
;
}
else if( margs->IsArray()){
Local<Array> env = menv.As<Array>();
int len = env->Length();
int i;
for(i=0;i<len;i++){
Local<Value> in = env->Get(i);
if(!ToCStr(isolate,in,(char *)"env",_args))
return;
}
}
else { //not array
isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate,"env must be a list")));
return;
}
char buf[255];
FILE *_result_f;
std::string result;
if(( _result_f = popen(_args.c_str(),"r"))==NULL)
isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate,"run /usr/lib/judger/libjudger.so failed!")));
while(fgets(buf,sizeof(buf),_result_f)){
result += std::string(buf);
}
pclose(_result_f);
const char *pr = result.c_str();
int len = strlen(pr);
for(len--;len>=0;len--){
if( pr[len] == '{')
break;
}
if(len)
printf("%*.*s",len,len,pr); //输出 程序的输出
MaybeLocal<Value> mres = JSON::Parse(isolate,String::NewFromUtf8(isolate,pr+len));
args.GetReturnValue().Set(mres.ToLocalChecked());
}
void init(Local<Object> exports)
{
v8::Isolate* isolate = v8::Isolate::GetCurrent();
NODE_SET_METHOD(exports, "run", Method);
exports->Set( String::NewFromUtf8(isolate,"UNLIMITED"),Integer::New(isolate, -1));
exports->Set(String::NewFromUtf8(isolate,"VERSION"),Integer::New(isolate, 0x020101));
exports->Set(String::NewFromUtf8(isolate,"RESULT_SUCCESS"),Integer::New(isolate, 0));
exports->Set(String::NewFromUtf8(isolate,"RESULT_WRONG_ANSWER"),Integer::New(isolate, -1));
exports->Set(String::NewFromUtf8(isolate,"RESULT_CPU_TIME_LIMIT_EXCEEDED"),Integer::New(isolate, 1));
exports->Set(String::NewFromUtf8(isolate,"RESULT_REAL_TIME_LIMIT_EXCEEDED"),Integer::New(isolate, 2));
exports->Set(String::NewFromUtf8(isolate,"RESULT_MEMORY_LIMIT_EXCEEDED"),Integer::New(isolate, 3));
exports->Set(String::NewFromUtf8(isolate,"RESULT_RUNTIME_ERROR"),Integer::New(isolate, 4));
exports->Set(String::NewFromUtf8(isolate,"RESULT_SYSTEM_ERROR"),Integer::New(isolate, 5));
exports->Set(String::NewFromUtf8(isolate,"ERROR_INVALID_CONFIG"),Integer::New(isolate, -1));
exports->Set(String::NewFromUtf8(isolate,"ERROR_FORK_FAILED"),Integer::New(isolate, -2));
exports->Set(String::NewFromUtf8(isolate,"ERROR_PTHREAD_FAILED"),Integer::New(isolate, -3));
exports->Set(String::NewFromUtf8(isolate,"ERROR_WAIT_FAILED"),Integer::New(isolate, -4));
exports->Set(String::NewFromUtf8(isolate,"ERROR_ROOT_REQUIRED"),Integer::New(isolate, -5));
exports->Set(String::NewFromUtf8(isolate,"ERROR_LOAD_SECCOMP_FAILED"),Integer::New(isolate, -6));
exports->Set(String::NewFromUtf8(isolate,"ERROR_SETRLIMIT_FAILED"),Integer::New(isolate, -7));
exports->Set(String::NewFromUtf8(isolate,"ERROR_DUP2_FAILED"),Integer::New(isolate, -8));
exports->Set(String::NewFromUtf8(isolate,"ERROR_SETUID_FAILED"),Integer::New(isolate, -9));
exports->Set(String::NewFromUtf8(isolate,"ERROR_EXECVE_FAILED"),Integer::New(isolate, -10));
exports->Set(String::NewFromUtf8(isolate,"ERROR_SPJ_ERROR"),Integer::New(isolate, -11));
}
NODE_MODULE(addon, init)
}
+16
View File
@@ -0,0 +1,16 @@
{
"name": "judger",
"version": "1.0.0",
"description": "judger for online system",
"main": "./build/Release/judger.node",
"scripts": {
"build": "node-gyp rebuild",
"test": "sudo ./node_modules/.bin/mocha -t 5000 ../../tests/Nodejs_and_core"
},
"author": "virusdefender,rainboy",
"license": "GPL",
"devDependencies": {
"mocha": "^6.1.4",
"node-gyp": "^4.0.0"
}
}
+15
View File
@@ -0,0 +1,15 @@
## 安装
先安装`judger`,然后
```
npm install
npm run build
npm run test
```
## 已知bug
#### bug_1
`freopen("data.out","w",stdout)`,不能产生"data.out",这个应该是judger代码的锅,:cry:
+3
View File
@@ -0,0 +1,3 @@
dist/
build/
*.egg-info/
+84
View File
@@ -0,0 +1,84 @@
import json
import subprocess
UNLIMITED = -1
VERSION = 0x020101
RESULT_SUCCESS = 0
RESULT_WRONG_ANSWER = -1
RESULT_CPU_TIME_LIMIT_EXCEEDED = 1
RESULT_REAL_TIME_LIMIT_EXCEEDED = 2
RESULT_MEMORY_LIMIT_EXCEEDED = 3
RESULT_RUNTIME_ERROR = 4
RESULT_SYSTEM_ERROR = 5
ERROR_INVALID_CONFIG = -1
ERROR_FORK_FAILED = -2
ERROR_PTHREAD_FAILED = -3
ERROR_WAIT_FAILED = -4
ERROR_ROOT_REQUIRED = -5
ERROR_LOAD_SECCOMP_FAILED = -6
ERROR_SETRLIMIT_FAILED = -7
ERROR_DUP2_FAILED = -8
ERROR_SETUID_FAILED = -9
ERROR_EXECVE_FAILED = -10
ERROR_SPJ_ERROR = -11
def run(max_cpu_time,
max_real_time,
max_memory,
max_stack,
max_output_size,
max_process_number,
exe_path,
input_path,
output_path,
error_path,
args,
env,
log_path,
seccomp_rule_name,
uid,
gid,
memory_limit_check_only=0):
str_list_vars = ["args", "env"]
int_vars = ["max_cpu_time", "max_real_time",
"max_memory", "max_stack", "max_output_size",
"max_process_number", "uid", "gid", "memory_limit_check_only"]
str_vars = ["exe_path", "input_path", "output_path", "error_path", "log_path"]
proc_args = ["/usr/lib/judger/libjudger.so"]
for var in str_list_vars:
value = vars()[var]
if not isinstance(value, list):
raise ValueError("{} must be a list".format(var))
for item in value:
if not isinstance(item, str):
raise ValueError("{} item must be a string".format(var))
proc_args.append("--{}={}".format(var, item))
for var in int_vars:
value = vars()[var]
if not isinstance(value, int):
raise ValueError("{} must be a int".format(var))
if value != UNLIMITED:
proc_args.append("--{}={}".format(var, value))
for var in str_vars:
value = vars()[var]
if not isinstance(value, str):
raise ValueError("{} must be a string".format(var))
proc_args.append("--{}={}".format(var, value))
if not isinstance(seccomp_rule_name, str) and seccomp_rule_name is not None:
raise ValueError("seccomp_rule_name must be a string or None")
if seccomp_rule_name:
proc_args.append("--seccomp_rule={}".format(seccomp_rule_name))
proc = subprocess.Popen(proc_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = proc.communicate()
if err:
raise ValueError("Error occurred while calling judger: {}".format(err))
return json.loads(out.decode("utf-8"))
+3
View File
@@ -0,0 +1,3 @@
[build-system]
requires = ["setuptools"]
build-backend = "setuptools.build_meta"
+7
View File
@@ -0,0 +1,7 @@
[metadata]
name = judger
version = 2.2.0
description = python wrapper of libjudger
[options]
packages = find: