fix memory

add tests
This commit is contained in:
virusdefender 2017-12-18 17:54:01 +08:00 committed by virusdefender
parent d7c8e51e1d
commit 72a387336a
10 changed files with 5620 additions and 205 deletions

View File

@ -2,16 +2,16 @@ cmake_minimum_required(VERSION 2.5)
project(judger C)
#set(CMAKE_VERBOSE_MAKEFILE ON)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/output)
set(BASE_CMAKE_C_FLAGS "-Wall -Werror -O3 -std=c99")
set(CMAKE_C_FLAGS "${BASE_CMAKE_C_FLAGS}")
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/output)
set(CMAKE_C_FLAGS "-g -Wall -Werror -O3 -std=c99 -pie -fPIC")
# make judger lib
file(GLOB SOURCE "src/*.c" "src/rules/*.c")
add_library(judger SHARED ${SOURCE})
target_link_libraries(judger pthread seccomp)
add_executable(libjudger.so ${SOURCE})
target_link_libraries(libjudger.so pthread seccomp)
install(DIRECTORY output/ DESTINATION /usr/lib/judger)
install(FILES output/libjudger.so
PERMISSIONS OWNER_EXECUTE OWNER_READ
DESTINATION /usr/lib/judger)

View File

@ -1,181 +0,0 @@
#include <unistd.h>
#include <dlfcn.h>
#include <sys/types.h>
#include <Python.h>
#include "../../src/runner.h"
#define RaiseValueError(msg)\
{ \
PyErr_SetString(PyExc_ValueError, msg); \
return NULL; \
}
#if PY_MAJOR_VERSION >= 3
#define PyString_Check PyUnicode_Check
#define PyString_AsString PyUnicode_AsUTF8
#endif
static PyObject *judger_run(PyObject *self, PyObject *args, PyObject *kwargs) {
struct config _config;
struct result _result = {0, 0, 0, 0, 0, 0, 0};
PyObject *args_list, *env_list, *rule_name, *args_iter, *env_iter, *next;
int count = 0, i = 0;
static char *kwargs_list[] = {"max_cpu_time", "max_real_time",
"max_memory", "max_stack",
"max_process_number", "max_output_size",
"exe_path", "input_path", "output_path",
"error_path", "args", "env", "log_path",
"seccomp_rule_name", "uid", "gid", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "iillilssssOOsOii", kwargs_list,
&(_config.max_cpu_time), &(_config.max_real_time),
&(_config.max_memory), &(_config.max_stack),
&(_config.max_process_number), &(_config.max_output_size),
&(_config.exe_path), &(_config.input_path), &(_config.output_path),
&(_config.error_path), &args_list, &env_list, &(_config.log_path),
&rule_name, &(_config.uid), &(_config.gid))) {
RaiseValueError("Invalid args and kwargs");
}
if (!PyList_Check(args_list)) {
RaiseValueError("args must be a list");
}
_config.args[count++] = _config.exe_path;
args_iter = PyObject_GetIter(args_list);
for(i = 0;i < ARGS_MAX_NUMBER;i++) {
next = PyIter_Next(args_iter);
if (!next) {
break;
}
if (!PyString_Check(next)) {
// free memory before the program exits.
Py_DECREF(next);
Py_DECREF(args_iter);
RaiseValueError("arg item must be a string");
}
_config.args[count] = PyString_AsString(next);
Py_DECREF(next);
count++;
}
_config.args[count] = NULL;
Py_DECREF(args_iter);
count = 0;
if (!PyList_Check(env_list)) {
RaiseValueError("env must be a list");
}
env_iter = PyObject_GetIter(env_list);
for(i = 0;i < ENV_MAX_NUMBER; i++) {
next = PyIter_Next(env_iter);
if (!next) {
break;
}
if (!PyString_Check(next)) {
Py_DECREF(next);
Py_DECREF(env_iter);
RaiseValueError("env item must be a string");
}
_config.env[count] = PyString_AsString(next);
count++;
Py_DECREF(next);
}
_config.env[count] = NULL;
Py_DECREF(env_iter);
if (PyString_Check(rule_name)) {
_config.seccomp_rule_name = PyString_AsString(rule_name);
}
else {
if (rule_name == Py_None) {
_config.seccomp_rule_name = NULL;
}
else {
RaiseValueError("seccomp_rule_name must be string or None");
}
}
run(&_config, &_result);
return Py_BuildValue("{s:i, s:l, s:i, s:i, s:i, s:i, s:i}",
"cpu_time", _result.cpu_time,
"memory", _result.memory,
"real_time", _result.real_time,
"signal", _result.signal,
"exit_code", _result.exit_code,
"error", _result.error,
"result", _result.result);
}
static PyMethodDef judger_methods[] = {
#if PY_MAJOR_VERSION >= 3
{"run", (PyCFunction) judger_run, METH_VARARGS | METH_KEYWORDS, NULL},
#else
{"run", (PyCFunction) judger_run, METH_KEYWORDS, NULL},
#endif
{NULL, NULL, 0, NULL}
};
static PyObject* moduleinit(void) {
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef judger_def = {
PyModuleDef_HEAD_INIT,
"_judger", /* m_name */
NULL, /* m_doc */
-1, /* m_size */
judger_methods, /* m_methods */
NULL, /* m_reload */
NULL, /* m_traverse */
NULL, /* m_clear */
NULL, /* m_free */
};
#endif
#if PY_MAJOR_VERSION >= 3
PyObject *module = PyModule_Create(&judger_def);
#else
PyObject *module = Py_InitModule3("_judger", judger_methods, NULL);
#endif
PyModule_AddIntConstant(module, "VERSION", VERSION);
PyModule_AddIntConstant(module, "UNLIMITED", UNLIMITED);
PyModule_AddIntConstant(module, "RESULT_WRONG_ANSWER", WRONG_ANSWER);
PyModule_AddIntConstant(module, "RESULT_SUCCESS", SUCCESS);
PyModule_AddIntConstant(module, "RESULT_CPU_TIME_LIMIT_EXCEEDED", CPU_TIME_LIMIT_EXCEEDED);
PyModule_AddIntConstant(module, "RESULT_REAL_TIME_LIMIT_EXCEEDED", REAL_TIME_LIMIT_EXCEEDED);
PyModule_AddIntConstant(module, "RESULT_MEMORY_LIMIT_EXCEEDED", MEMORY_LIMIT_EXCEEDED);
PyModule_AddIntConstant(module, "RESULT_RUNTIME_ERROR", RUNTIME_ERROR);
PyModule_AddIntConstant(module, "RESULT_SYSTEM_ERROR", SYSTEM_ERROR);
PyModule_AddIntConstant(module, "ERROR_INVALID_CONFIG", INVALID_CONFIG);
PyModule_AddIntConstant(module, "ERROR_FORK_FAILED", FORK_FAILED);
PyModule_AddIntConstant(module, "ERROR_PTHREAD_FAILED", PTHREAD_FAILED);
PyModule_AddIntConstant(module, "ERROR_WAIT_FAILED", WAIT_FAILED);
PyModule_AddIntConstant(module, "ERROR_ROOT_REQUIRED", ROOT_REQUIRED);
PyModule_AddIntConstant(module, "ERROR_LOAD_SECCOMP_FAILED", LOAD_SECCOMP_FAILED);
PyModule_AddIntConstant(module, "ERROR_SETRLIMIT_FAILED", SETRLIMIT_FAILED);
PyModule_AddIntConstant(module, "ERROR_DUP2_FAILED", DUP2_FAILED);
PyModule_AddIntConstant(module, "ERROR_SETUID_FAILED", SETUID_FAILED);
PyModule_AddIntConstant(module, "ERROR_EXECVE_FAILED", EXECVE_FAILED);
PyModule_AddIntConstant(module, "ERROR_SPJ_ERROR", SPJ_ERROR);
return module;
}
#if PY_MAJOR_VERSION >= 3
PyMODINIT_FUNC PyInit__judger(void)
{
return moduleinit();
}
#else
PyMODINIT_FUNC init_judger(void)
{
moduleinit();
}
#endif

View File

@ -0,0 +1,83 @@
import json
import subprocess
UNLIMITED = -1
VERSION = 0x020100
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):
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"]
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"))

View File

@ -1,9 +1,6 @@
# coding=utf-8
import platform
from distutils.core import setup, Extension
setup(name='_judger',
version='2.1',
ext_modules=[Extension('_judger',
sources=['_judger.c'],
extra_link_args=["-L", "/usr/lib/judger", "-l", "judger", "-Wl,-rpath=/usr/lib/judger"])])
packages=["_judger"])

5017
src/argtable3.c Normal file

File diff suppressed because it is too large Load Diff

305
src/argtable3.h Normal file
View File

@ -0,0 +1,305 @@
/*******************************************************************************
* This file is part of the argtable3 library.
*
* Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
* <sheitmann@users.sourceforge.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of STEWART HEITMANN nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#ifndef ARGTABLE3
#define ARGTABLE3
#include <stdio.h> /* FILE */
#include <time.h> /* struct tm */
#ifdef __cplusplus
extern "C" {
#endif
#define ARG_REX_ICASE 1
/* bit masks for arg_hdr.flag */
enum
{
ARG_TERMINATOR=0x1,
ARG_HASVALUE=0x2,
ARG_HASOPTVALUE=0x4
};
typedef void (arg_resetfn)(void *parent);
typedef int (arg_scanfn)(void *parent, const char *argval);
typedef int (arg_checkfn)(void *parent);
typedef void (arg_errorfn)(void *parent, FILE *fp, int error, const char *argval, const char *progname);
/*
* The arg_hdr struct defines properties that are common to all arg_xxx structs.
* The argtable library requires each arg_xxx struct to have an arg_hdr
* struct as its first data member.
* The argtable library functions then use this data to identify the
* properties of the command line option, such as its option tags,
* datatype string, and glossary strings, and so on.
* Moreover, the arg_hdr struct contains pointers to custom functions that
* are provided by each arg_xxx struct which perform the tasks of parsing
* that particular arg_xxx arguments, performing post-parse checks, and
* reporting errors.
* These functions are private to the individual arg_xxx source code
* and are the pointer to them are initiliased by that arg_xxx struct's
* constructor function. The user could alter them after construction
* if desired, but the original intention is for them to be set by the
* constructor and left unaltered.
*/
struct arg_hdr
{
char flag; /* Modifier flags: ARG_TERMINATOR, ARG_HASVALUE. */
const char *shortopts; /* String defining the short options */
const char *longopts; /* String defiing the long options */
const char *datatype; /* Description of the argument data type */
const char *glossary; /* Description of the option as shown by arg_print_glossary function */
int mincount; /* Minimum number of occurences of this option accepted */
int maxcount; /* Maximum number of occurences if this option accepted */
void *parent; /* Pointer to parent arg_xxx struct */
arg_resetfn *resetfn; /* Pointer to parent arg_xxx reset function */
arg_scanfn *scanfn; /* Pointer to parent arg_xxx scan function */
arg_checkfn *checkfn; /* Pointer to parent arg_xxx check function */
arg_errorfn *errorfn; /* Pointer to parent arg_xxx error function */
void *priv; /* Pointer to private header data for use by arg_xxx functions */
};
struct arg_rem
{
struct arg_hdr hdr; /* The mandatory argtable header struct */
};
struct arg_lit
{
struct arg_hdr hdr; /* The mandatory argtable header struct */
int count; /* Number of matching command line args */
};
struct arg_int
{
struct arg_hdr hdr; /* The mandatory argtable header struct */
int count; /* Number of matching command line args */
int *ival; /* Array of parsed argument values */
};
struct arg_dbl
{
struct arg_hdr hdr; /* The mandatory argtable header struct */
int count; /* Number of matching command line args */
double *dval; /* Array of parsed argument values */
};
struct arg_str
{
struct arg_hdr hdr; /* The mandatory argtable header struct */
int count; /* Number of matching command line args */
const char **sval; /* Array of parsed argument values */
};
struct arg_rex
{
struct arg_hdr hdr; /* The mandatory argtable header struct */
int count; /* Number of matching command line args */
const char **sval; /* Array of parsed argument values */
};
struct arg_file
{
struct arg_hdr hdr; /* The mandatory argtable header struct */
int count; /* Number of matching command line args*/
const char **filename; /* Array of parsed filenames (eg: /home/foo.bar) */
const char **basename; /* Array of parsed basenames (eg: foo.bar) */
const char **extension; /* Array of parsed extensions (eg: .bar) */
};
struct arg_date
{
struct arg_hdr hdr; /* The mandatory argtable header struct */
const char *format; /* strptime format string used to parse the date */
int count; /* Number of matching command line args */
struct tm *tmval; /* Array of parsed time values */
};
enum {ARG_ELIMIT=1, ARG_EMALLOC, ARG_ENOMATCH, ARG_ELONGOPT, ARG_EMISSARG};
struct arg_end
{
struct arg_hdr hdr; /* The mandatory argtable header struct */
int count; /* Number of errors encountered */
int *error; /* Array of error codes */
void **parent; /* Array of pointers to offending arg_xxx struct */
const char **argval; /* Array of pointers to offending argv[] string */
};
/**** arg_xxx constructor functions *********************************/
struct arg_rem* arg_rem(const char* datatype, const char* glossary);
struct arg_lit* arg_lit0(const char* shortopts,
const char* longopts,
const char* glossary);
struct arg_lit* arg_lit1(const char* shortopts,
const char* longopts,
const char *glossary);
struct arg_lit* arg_litn(const char* shortopts,
const char* longopts,
int mincount,
int maxcount,
const char *glossary);
struct arg_key* arg_key0(const char* keyword,
int flags,
const char* glossary);
struct arg_key* arg_key1(const char* keyword,
int flags,
const char* glossary);
struct arg_key* arg_keyn(const char* keyword,
int flags,
int mincount,
int maxcount,
const char* glossary);
struct arg_int* arg_int0(const char* shortopts,
const char* longopts,
const char* datatype,
const char* glossary);
struct arg_int* arg_int1(const char* shortopts,
const char* longopts,
const char* datatype,
const char *glossary);
struct arg_int* arg_intn(const char* shortopts,
const char* longopts,
const char *datatype,
int mincount,
int maxcount,
const char *glossary);
struct arg_dbl* arg_dbl0(const char* shortopts,
const char* longopts,
const char* datatype,
const char* glossary);
struct arg_dbl* arg_dbl1(const char* shortopts,
const char* longopts,
const char* datatype,
const char *glossary);
struct arg_dbl* arg_dbln(const char* shortopts,
const char* longopts,
const char *datatype,
int mincount,
int maxcount,
const char *glossary);
struct arg_str* arg_str0(const char* shortopts,
const char* longopts,
const char* datatype,
const char* glossary);
struct arg_str* arg_str1(const char* shortopts,
const char* longopts,
const char* datatype,
const char *glossary);
struct arg_str* arg_strn(const char* shortopts,
const char* longopts,
const char* datatype,
int mincount,
int maxcount,
const char *glossary);
struct arg_rex* arg_rex0(const char* shortopts,
const char* longopts,
const char* pattern,
const char* datatype,
int flags,
const char* glossary);
struct arg_rex* arg_rex1(const char* shortopts,
const char* longopts,
const char* pattern,
const char* datatype,
int flags,
const char *glossary);
struct arg_rex* arg_rexn(const char* shortopts,
const char* longopts,
const char* pattern,
const char* datatype,
int mincount,
int maxcount,
int flags,
const char *glossary);
struct arg_file* arg_file0(const char* shortopts,
const char* longopts,
const char* datatype,
const char* glossary);
struct arg_file* arg_file1(const char* shortopts,
const char* longopts,
const char* datatype,
const char *glossary);
struct arg_file* arg_filen(const char* shortopts,
const char* longopts,
const char* datatype,
int mincount,
int maxcount,
const char *glossary);
struct arg_date* arg_date0(const char* shortopts,
const char* longopts,
const char* format,
const char* datatype,
const char* glossary);
struct arg_date* arg_date1(const char* shortopts,
const char* longopts,
const char* format,
const char* datatype,
const char *glossary);
struct arg_date* arg_daten(const char* shortopts,
const char* longopts,
const char* format,
const char* datatype,
int mincount,
int maxcount,
const char *glossary);
struct arg_end* arg_end(int maxerrors);
/**** other functions *******************************************/
int arg_nullcheck(void **argtable);
int arg_parse(int argc, char **argv, void **argtable);
void arg_print_option(FILE *fp, const char *shortopts, const char *longopts, const char *datatype, const char *suffix);
void arg_print_syntax(FILE *fp, void **argtable, const char *suffix);
void arg_print_syntaxv(FILE *fp, void **argtable, const char *suffix);
void arg_print_glossary(FILE *fp, void **argtable, const char *format);
void arg_print_glossary_gnu(FILE *fp, void **argtable);
void arg_print_errors(FILE* fp, struct arg_end* end, const char* progname);
void arg_freetable(void **argtable, size_t n);
/**** deprecated functions, for back-compatibility only ********/
void arg_free(void **argtable);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -50,7 +50,7 @@ void log_write(int level, const char *source_filename, const int line, const FIL
int count = snprintf(buffer, log_buffer_size,
"%s [%s] [%s:%s]%s\n",
LOG_LEVEL_NOTE[level], datetime, source_filename, line_str, log_buffer);
fprintf(stdout, "%s", buffer);
// fprintf(stderr, "%s", buffer);
int log_fd = fileno((FILE *) log_fp);
if (flock(log_fd, LOCK_EX) == 0) {
if (write(log_fd, buffer, (size_t) count) < 0) {

185
src/main.c Normal file
View File

@ -0,0 +1,185 @@
#include "argtable3.h"
#include "runner.h"
#define INT_PLACE_HOLDER "<n>"
#define STR_PLACE_HOLDER "<str>"
struct arg_lit *verb, *help, *version;
struct arg_int *max_cpu_time, *max_real_time, *max_memory, *max_stack,
*max_process_number, *max_output_size, *uid, *gid;
struct arg_str *exe_path, *input_path, *output_path, *error_path, *args, *env, *log_path, *seccomp_rule_name;
struct arg_end *end;
int main(int argc, char *argv[]) {
void *arg_table[] = {
help = arg_litn(NULL, "help", 0, 1, "Display This Help And Exit"),
version = arg_litn(NULL, "version", 0, 1, "Display Version Info And Exit"),
max_cpu_time = arg_intn(NULL, "max_cpu_time", INT_PLACE_HOLDER, 0, 1, "Max CPU Time (ms)"),
max_real_time = arg_intn(NULL, "max_real_time", INT_PLACE_HOLDER, 0, 1, "Max Real Time (ms)"),
max_memory = arg_intn(NULL, "max_memory", INT_PLACE_HOLDER, 0, 1, "Max Memory (byte)"),
max_stack = arg_intn(NULL, "max_stack", INT_PLACE_HOLDER, 0, 1, "Max Stack (byte, default 16M)"),
max_process_number = arg_intn(NULL, "max_process_number", INT_PLACE_HOLDER, 0, 1, "Max Process Number"),
max_output_size = arg_intn(NULL, "max_output_size", INT_PLACE_HOLDER, 0, 1, "Max Output Size (byte)"),
exe_path = arg_str1(NULL, "exe_path", STR_PLACE_HOLDER, "Exe Path"),
input_path = arg_strn(NULL, "input_path", STR_PLACE_HOLDER, 0, 1, "Input Path"),
output_path = arg_strn(NULL, "output_path", STR_PLACE_HOLDER, 0, 1, "Output Path"),
error_path = arg_strn(NULL, "error_path", STR_PLACE_HOLDER, 0, 1, "Error Path"),
args = arg_strn(NULL, "args", STR_PLACE_HOLDER, 0, 255, "Arg"),
env = arg_strn(NULL, "env", STR_PLACE_HOLDER, 0, 255, "Env"),
log_path = arg_strn(NULL, "log_path", STR_PLACE_HOLDER, 0, 1, "Log Path"),
seccomp_rule_name = arg_strn(NULL, "seccomp_rule_name", STR_PLACE_HOLDER, 0, 1, "Seccomp Rule Name"),
uid = arg_intn(NULL, "uid", INT_PLACE_HOLDER, 0, 1, "UID (default 65534)"),
gid = arg_intn(NULL, "gid", INT_PLACE_HOLDER, 0, 1, "GID (default 65534)"),
end = arg_end(10),
};
int exitcode = 0;
char name[] = "libjudger.so";
int nerrors = arg_parse(argc, argv, arg_table);
if (help->count > 0) {
printf("Usage: %s", name);
arg_print_syntax(stdout, arg_table, "\n\n");
arg_print_glossary(stdout, arg_table, " %-25s %s\n");
goto exit;
}
if (version->count > 0) {
printf("Version: %d.%d.%d\n", (VERSION >> 16) & 0xff, (VERSION >> 8) & 0xff, VERSION & 0xff);
goto exit;
}
if (nerrors > 0) {
arg_print_errors(stdout, end, name);
printf("Try '%s --help' for more information.\n", name);
exitcode = 1;
goto exit;
}
struct config _config;
struct result _result = {0, 0, 0, 0, 0, 0, 0};
if (max_cpu_time->count > 0) {
_config.max_cpu_time = *max_cpu_time->ival;
} else {
_config.max_cpu_time = UNLIMITED;
}
if (max_real_time->count > 0) {
_config.max_real_time = *max_real_time->ival;
} else {
_config.max_real_time = UNLIMITED;
}
if (max_memory->count > 0) {
_config.max_memory = (long) *max_memory->ival;
} else {
_config.max_memory = UNLIMITED;
}
if (max_stack->count > 0) {
_config.max_stack = (long) *max_stack->ival;
} else {
_config.max_stack = 16 * 1024 * 1024;
}
if (max_process_number->count > 0) {
_config.max_process_number = *max_process_number->ival;
} else {
_config.max_process_number = UNLIMITED;
}
if (max_output_size->count > 0) {
_config.max_output_size = (long) *max_output_size->ival;
} else {
_config.max_output_size = UNLIMITED;
}
_config.exe_path = (char *)*exe_path->sval;
if (input_path->count > 0) {
_config.input_path = (char *)input_path->sval[0];
} else {
_config.input_path = "/dev/stdin";
}
if (output_path->count > 0) {
_config.output_path = (char *)output_path->sval[0];
} else {
_config.output_path = "/dev/stdout";
}
if (error_path->count > 0) {
_config.error_path = (char *)error_path->sval[0];
} else {
_config.error_path = "/dev/stderr";
}
_config.args[0] = _config.exe_path;
int i = 1;
if (args->count > 0) {
for (; i < args->count + 1; i++) {
_config.args[i] = (char *)args->sval[i - 1];
}
}
_config.args[i] = NULL;
i = 0;
if (env->count > 0) {
for (; i < env->count; i++) {
_config.env[i] = (char *)env->sval[i];
}
}
_config.env[i] = NULL;
if (log_path->count > 0) {
_config.log_path = (char *)log_path->sval[0];
} else {
_config.log_path = "judger.log";
}
if (seccomp_rule_name->count > 0) {
_config.seccomp_rule_name = (char *)seccomp_rule_name->sval[0];
} else {
_config.seccomp_rule_name = NULL;
}
if (uid->count > 0) {
_config.uid = (uid_t)*(uid->ival);
}
else {
_config.uid = 65534;
}
if(gid->count > 0) {
_config.gid = (gid_t)*(gid->ival);
}
else {
_config.gid = 65534;
}
run(&_config, &_result);
printf("{\n"
" \"cpu_time\": %d,\n"
" \"real_time\": %d,\n"
" \"memory\": %ld,\n"
" \"signal\": %d,\n"
" \"exit_code\": %d,\n"
" \"error\": %d,\n"
" \"result\": %d\n"
"}",
_result.cpu_time,
_result.real_time,
_result.memory,
_result.signal,
_result.exit_code,
_result.error,
_result.result);
exit:
arg_freetable(arg_table, sizeof(arg_table) / sizeof(arg_table[0]));
return exitcode;
}

View File

@ -5,7 +5,7 @@
#include <stdio.h>
// (ver >> 16) & 0xff, (ver >> 8) & 0xff, ver & 0xff -> real version
#define VERSION 0x020001
#define VERSION 0x020100
#define UNLIMITED -1

View File

@ -1,9 +1,10 @@
# coding=utf-8
from __future__ import print_function
import sys
import _judger
import signal
import os
import resource
import _judger
from .. import base
@ -19,11 +20,6 @@ class IntegrationTest(base.BaseTestCase):
def _compile_cpp(self, src_name):
return super(IntegrationTest, self)._compile_cpp("../../test_src/integration/" + src_name)
def test_args_validation(self):
with self.assertRaisesRegexp(ValueError, "Invalid args and kwargs"):
_judger.run()
_judger.run(a=1, c=3)
def test_args_must_be_list(self):
with self.assertRaisesRegexp(ValueError, "args must be a list"):
_judger.run(max_cpu_time=1000, max_real_time=2000,
@ -42,7 +38,7 @@ class IntegrationTest(base.BaseTestCase):
seccomp_rule_name="1.so", uid=0, gid=0)
def test_args_item_must_be_string(self):
with self.assertRaisesRegexp(ValueError, "arg item must be a string"):
with self.assertRaisesRegexp(ValueError, "args item must be a string"):
_judger.run(max_cpu_time=1000, max_real_time=2000,
max_memory=1024 * 1024 * 128, max_stack=32 * 1024 * 1024,
max_process_number=200, max_output_size=10000, exe_path="1.out",
@ -50,7 +46,7 @@ class IntegrationTest(base.BaseTestCase):
args=["1234", 1234], env=["a=b"], log_path="1.log",
seccomp_rule_name="1.so", uid=0, gid=0)
with self.assertRaisesRegexp(ValueError, "arg item must be a string"):
with self.assertRaisesRegexp(ValueError, "args item must be a string"):
_judger.run(max_cpu_time=1000, max_real_time=2000,
max_memory=1024 * 1024 * 128, max_stack=32 * 1024 * 1024,
max_process_number=200, max_output_size=10000, exe_path="1.out",
@ -62,7 +58,7 @@ class IntegrationTest(base.BaseTestCase):
args = ["哈哈哈".encode("utf-8")]
else:
args = [u"哈哈哈"]
with self.assertRaisesRegexp(ValueError, "arg item must be a string"):
with self.assertRaisesRegexp(ValueError, "args item must be a string"):
_judger.run(max_cpu_time=1000, max_real_time=2000,
max_memory=1024 * 1024 * 128, max_stack=32 * 1024 * 1024,
max_process_number=200, max_output_size=10000, exe_path="1.out",
@ -211,6 +207,17 @@ class IntegrationTest(base.BaseTestCase):
self.assertEqual(result["result"], _judger.RESULT_SUCCESS)
self.assertTrue(result["memory"] >= 102400000 * 4)
def test_memory4(self):
"""parent process memory should not affect child process"""
a = ["test" for i in range(2000000)]
# get self maxrss
max_rss = resource.getrusage(resource.RUSAGE_SELF)[2]
self.assertTrue(max_rss > 28000)
result = _judger.run(**self.base_config)
self.assertEqual(result["result"], _judger.RESULT_SUCCESS)
self.assertTrue(result["memory"] < 3000000)
del a
def test_re1(self):
config = self.base_config
config["exe_path"] = self._compile_c("re1.c")
@ -283,7 +290,9 @@ class IntegrationTest(base.BaseTestCase):
config["exe_path"] = self._compile_c("output_size.c")
config["max_output_size"] = 1000 * 10
result = _judger.run(**config)
self.assertEqual(result["exit_code"], 2)
self.assertEqual(result["result"], _judger.RESULT_RUNTIME_ERROR)
with open("/tmp/fsize_test", "r") as f:
self.assertEqual(len(f.read()), 10000)
def test_stack_size(self):
config = self.base_config
@ -307,4 +316,4 @@ class IntegrationTest(base.BaseTestCase):
config["output_path"] = config["error_path"] = self.output_path()
result = _judger.run(**config)
self.assertEqual(result["result"], _judger.RESULT_SUCCESS)
self.assertEqual(result["result"], _judger.RESULT_SUCCESS)