use std::cell::Cell;
use std::ffi::{CStr, c_int, c_void};
use std::ptr::{self, NonNull};
use std::sync::atomic::{AtomicBool, Ordering};
use super::ffi;
const BACKTRACK_LIMIT: u32 = 1_000_000;
const RECURSION_LIMIT: u32 = 100_000;
const JIT_STACK_MIN: usize = 32 * 1024;
const JIT_STACK_MAX: usize = 192 * 1024;
const PREALLOC_PAIRS: u32 = 32;
pub(super) struct Code(NonNull<ffi::Code>);
unsafe impl Send for Code {}
unsafe impl Sync for Code {}
impl Drop for Code {
fn drop(&mut self) {
unsafe { ffi::pcre2_code_free_8(self.0.as_ptr()) }
}
}
pub(super) struct CompileError {
pub code: c_int,
pub offset: usize,
}
impl Code {
pub fn compile(pattern: &[u8], options: u32, extra: u32) -> Result<Code, CompileError> {
let mut code = 0;
let mut offset = 0;
let re = unsafe {
let ctx = if extra != 0 {
let ctx = ffi::pcre2_compile_context_create_8(ptr::null_mut());
if !ctx.is_null() {
ffi::pcre2_set_compile_extra_options_8(ctx, extra);
}
ctx
} else {
ptr::null_mut()
};
let re = ffi::pcre2_compile_8(pattern.as_ptr(), pattern.len(), options, &mut code, &mut offset, ctx);
if !ctx.is_null() {
ffi::pcre2_compile_context_free_8(ctx);
}
re
};
NonNull::new(re).map(Code).ok_or(CompileError { code, offset })
}
pub fn jit_compile(&mut self) -> Result<bool, c_int> {
let rc = unsafe { ffi::pcre2_jit_compile_8(self.0.as_ptr(), ffi::JIT_COMPLETE) };
if rc < 0 {
return Err(rc);
}
let mut size: usize = 0;
Ok(self.info(ffi::INFO_JITSIZE, &mut size as *mut usize as *mut c_void) == 0 && size > 0)
}
fn info(&self, what: u32, out: *mut c_void) -> c_int {
unsafe { ffi::pcre2_pattern_info_8(self.0.as_ptr(), what, out) }
}
pub fn capture_count(&self) -> u32 {
let mut n: u32 = 0;
self.info(ffi::INFO_CAPTURECOUNT, &mut n as *mut u32 as *mut c_void);
n
}
pub fn names(&self) -> Vec<(usize, Vec<u8>)> {
let mut count: u32 = 0;
let mut size: u32 = 0;
let mut table: *const u8 = ptr::null();
self.info(ffi::INFO_NAMECOUNT, &mut count as *mut u32 as *mut c_void);
if count == 0 {
return Vec::new();
}
self.info(ffi::INFO_NAMEENTRYSIZE, &mut size as *mut u32 as *mut c_void);
self.info(ffi::INFO_NAMETABLE, &mut table as *mut *const u8 as *mut c_void);
(0..count as usize)
.map(|i| {
unsafe {
let entry = table.add(i * size as usize);
let group = usize::from(*entry) << 8 | usize::from(*entry.add(1));
(group, CStr::from_ptr(entry.add(2).cast()).to_bytes().to_vec())
}
})
.collect()
}
}
pub(super) fn error_message(code: c_int) -> Vec<u8> {
let mut buf = [0u8; 256];
let n = unsafe { ffi::pcre2_get_error_message_8(code, buf.as_mut_ptr(), buf.len()) };
buf[..usize::try_from(n).unwrap_or(0)].to_vec()
}
pub(crate) fn is_letter_or_number(c: u32) -> bool {
unsafe { ffi::php_std_pcre2_is_letter_or_number(c) != 0 }
}
static JIT_STACK: AtomicBool = AtomicBool::new(true);
struct Thread {
mctx: NonNull<ffi::MatchContext>,
stack: NonNull<ffi::JitStack>,
stack_assigned: Cell<bool>,
mdata: Cell<*mut ffi::MatchData>,
}
impl Thread {
fn new() -> Thread {
unsafe {
let mctx = NonNull::new(ffi::pcre2_match_context_create_8(ptr::null_mut())).expect("PCRE2 match context");
ffi::pcre2_set_match_limit_8(mctx.as_ptr(), BACKTRACK_LIMIT);
ffi::pcre2_set_depth_limit_8(mctx.as_ptr(), RECURSION_LIMIT);
let stack = NonNull::new(ffi::pcre2_jit_stack_create_8(JIT_STACK_MIN, JIT_STACK_MAX, ptr::null_mut()))
.expect("PCRE2 JIT stack");
ffi::pcre2_jit_stack_assign_8(mctx.as_ptr(), None, stack.as_ptr().cast());
let mdata = ffi::pcre2_match_data_create_8(PREALLOC_PAIRS, ptr::null_mut());
Thread { mctx, stack, stack_assigned: Cell::new(true), mdata: Cell::new(mdata) }
}
}
}
impl Drop for Thread {
fn drop(&mut self) {
unsafe {
let mdata = self.mdata.get();
if !mdata.is_null() {
ffi::pcre2_match_data_free_8(mdata);
}
ffi::pcre2_match_context_free_8(self.mctx.as_ptr());
ffi::pcre2_jit_stack_free_8(self.stack.as_ptr());
}
}
}
thread_local! {
static THREAD: Thread = Thread::new();
}
pub(super) struct Session {
md: NonNull<ffi::MatchData>,
shared: bool,
mctx: *mut ffi::MatchContext,
}
impl Session {
pub fn new(code: &Code, capture_count: u32) -> Session {
THREAD.with(|t| {
let jit = JIT_STACK.load(Ordering::Relaxed);
if t.stack_assigned.get() != jit {
let stack: *mut c_void = if jit { t.stack.as_ptr().cast() } else { ptr::null_mut() };
unsafe { ffi::pcre2_jit_stack_assign_8(t.mctx.as_ptr(), None, stack) };
t.stack_assigned.set(jit);
}
let mctx = t.mctx.as_ptr();
let shared = t.mdata.replace(ptr::null_mut());
if let Some(md) = NonNull::new(shared) {
if capture_count < PREALLOC_PAIRS {
return Session { md, shared: true, mctx };
}
t.mdata.set(shared);
}
let md = unsafe { ffi::pcre2_match_data_create_from_pattern_8(code.0.as_ptr(), ptr::null_mut()) };
Session { md: NonNull::new(md).expect("PCRE2 match data"), shared: false, mctx }
})
}
pub fn run(&mut self, code: &Code, subject: &[u8], start: usize, options: u32, jit: bool) -> c_int {
if start > subject.len() {
return ffi::ERROR_BADOFFSET;
}
let f = if jit { ffi::pcre2_jit_match_8 } else { ffi::pcre2_match_8 };
let subject = if subject.is_empty() { &b"\0"[..0] } else { subject };
unsafe { f(code.0.as_ptr(), subject.as_ptr(), subject.len(), start, options, self.md.as_ptr(), self.mctx) }
}
pub fn ovector(&self, count: usize) -> &[usize] {
unsafe {
let n = (ffi::pcre2_get_ovector_count_8(self.md.as_ptr()) as usize).min(count);
std::slice::from_raw_parts(ffi::pcre2_get_ovector_pointer_8(self.md.as_ptr()), 2 * n)
}
}
pub fn mark<'c>(&self, _code: &'c Code) -> Option<&'c [u8]> {
unsafe {
let p = ffi::pcre2_get_mark_8(self.md.as_ptr());
if p.is_null() { None } else { Some(CStr::from_ptr(p.cast()).to_bytes()) }
}
}
}
impl Drop for Session {
fn drop(&mut self) {
let md = self.md.as_ptr();
if self.shared && THREAD.try_with(|t| t.mdata.set(md)).is_ok() {
return;
}
unsafe { ffi::pcre2_match_data_free_8(md) }
}
}