#include #include #include #include #include "utl_call_stack.hpp" extern "C" { PG_FUNCTION_INFO_V1(utl_call_stack_backtrace_depth); PG_FUNCTION_INFO_V1(utl_call_stack_dynamic_depth); PG_FUNCTION_INFO_V1(utl_call_stack_error_depth); PG_FUNCTION_INFO_V1(utl_call_stack_backtrace_line); PG_FUNCTION_INFO_V1(utl_call_stack_backtrace_unit); PG_FUNCTION_INFO_V1(utl_call_stack_current_edition); PG_FUNCTION_INFO_V1(utl_call_stack_error_msg); PG_FUNCTION_INFO_V1(utl_call_stack_error_number); PG_FUNCTION_INFO_V1(utl_call_stack_lexical_depth); PG_FUNCTION_INFO_V1(utl_call_stack_owner); PG_FUNCTION_INFO_V1(utl_call_stack_unit_line); PG_FUNCTION_INFO_V1(utl_call_stack_subprogram); PG_FUNCTION_INFO_V1(utl_call_stack_concatenate_subprogram); PG_FUNCTION_INFO_V1(utl_call_stack_compose_subprogram); PG_FUNCTION_INFO_V1(utl_call_stack_get_version); /// @brief Версия RUDB пакета UTL_CALL_STACK (Oracle UTL_CALL_STACK пакет) #define RUDB_UTL_CALL_STACK_VERSION "1.0.0" } // ---------- frames ---------- struct Frame { std::string schema; std::string name; int line = 0; bool is_anonymous = false; bool is_sql_func = false; }; static inline std::string trim(const std::string &s){ size_t a=0,b=s.size(); while (aa && std::isspace((unsigned char)s[b-1])) --b; return s.substr(a,b-a); } static inline bool starts_with(const std::string& s, const char* p) { size_t n=strlen(p); return s.size()>=n && memcmp(s.data(),p,n)==0; } static inline bool contains(const std::string& s, const char* w) { return s.find(w)!=std::string::npos; } static void split_lines(const char* ctx, std::vector& out) { if (!ctx) return; const char* p=ctx; const char* st=p; for (; *p; ++p){ if (*p=='\n'){ out.emplace_back(st, p-st); st=p+1; } } if (st && *st) out.emplace_back(st); } static Frame parse_plpgsql_frame(const std::string& line){ Frame f; f.line=0; const char* key="PL/pgSQL function "; auto pos=line.find(key); if (pos==std::string::npos) return f; std::string tail=line.substr(pos+strlen(key)); if (starts_with(tail,"inline_code_block")){ f.is_anonymous=true; f.name="__anonymous_block"; auto p=tail.find(" line "); if (p!=std::string::npos){ p+=6; int n=0; while (p<(int)tail.size() && std::isdigit((unsigned char)tail[p])){ n=n*10+(tail[p]-'0'); ++p; } f.line=n; } return f; } auto lp=tail.find('('); std::string qual=(lp==std::string::npos)?tail:tail.substr(0,lp); qual=trim(qual); auto dot=qual.rfind('.'); if (dot!=std::string::npos){ f.schema=qual.substr(0,dot); f.name=qual.substr(dot+1); } else f.name=qual; auto p=tail.find(" line "); if (p!=std::string::npos){ p+=6; int n=0; while (p<(int)tail.size() && std::isdigit((unsigned char)tail[p])){ n=n*10+(tail[p]-'0'); ++p; } f.line=n; } return f; } static Frame parse_sqlfunc_frame(const std::string& line){ Frame f; f.is_sql_func=true; const char* key="SQL function "; auto pos=line.find(key); if (pos==std::string::npos) return f; std::string tail=line.substr(pos+strlen(key)); auto lp=tail.find('('); std::string qual=(lp==std::string::npos)?tail:tail.substr(0,lp); qual=trim(qual); auto dot=qual.rfind('.'); if (dot!=std::string::npos){ f.schema=qual.substr(0,dot); f.name=qual.substr(dot+1); } else f.name=qual; f.line=0; return f; } static bool is_our_utl_frame(const std::string& line) { return contains(line, "SQL function utl_call_stack_"); } static std::vector parse_context_frames(const char* context){ std::vector lines; split_lines(context, lines); std::vector frames; frames.reserve(lines.size()); for (auto &ln: lines){ std::string s=trim(ln); if (s.empty()) continue; if (is_our_utl_frame(s)) continue; if (starts_with(s,"PL/pgSQL function ")){ Frame f=parse_plpgsql_frame(s); if (!f.name.empty() || f.is_anonymous) frames.push_back(f); } else if (starts_with(s,"SQL function ")){ Frame f=parse_sqlfunc_frame(s); if (!f.name.empty()) frames.push_back(f); } } return frames; // inner→outer } static std::string make_unit_qualified(const Frame& f) { if (f.is_anonymous) return "__anonymous_block"; if (!f.schema.empty()) return f.schema + "." + f.name; return f.name; } // ---------- «последняя ошибка» через emit_log_hook ---------- struct LastErrorSnapshot { bool has=false; int sqlerrcode=0; std::string message; std::string context; }; static LastErrorSnapshot g_last_error; static emit_log_hook_type prev_emit_log_hook=nullptr; // --- snapshot для «тихого» пробника строки (CONTEXT из inline_code_block) --- struct LastProbeSnapshot { bool has = false; std::string context; }; static LastProbeSnapshot g_last_probe; static void utlcs_emit_log_hook(ErrorData *edata) { // Никаких исключений из хука try { if (edata) { const char* msg = edata->message ? edata->message : ""; // 1) ловим CONTEXT и глушим вывод if (strcmp(msg, "UTL_CALL_STACK$PROBE") == 0) { g_last_probe.has = true; g_last_probe.context.assign(edata->context ? edata->context : ""); edata->output_to_client = false; // ничего в клиент edata->output_to_server = false; // ничего в лог } // 2) Реальная ошибка — для ERROR_*/BACKTRACE_* (последняя ошибка сессии) else if (edata->elevel >= ERROR) { g_last_error.has = true; g_last_error.sqlerrcode = edata->sqlerrcode; g_last_error.message.assign(msg); g_last_error.context.assign(edata->context ? edata->context : ""); } } } catch (...) { // ignore } if (prev_emit_log_hook) prev_emit_log_hook(edata); } // ----------- GUC: включать/выключать внутренний пробник (по умолчанию ВЫКЛ) ----------- static bool guc_probe_enabled = false; extern "C" void _PG_init(void) { DefineCustomBoolVariable( "utl_call_stack.probe_enabled", "Enable internal error-probe to capture instantaneous call stack.", "Default false. When true, functions may raise/catch internal ERROR.", &guc_probe_enabled, false, PGC_SUSET, 0, nullptr, nullptr, nullptr ); prev_emit_log_hook = emit_log_hook; emit_log_hook = utlcs_emit_log_hook; } extern "C" void _PG_fini(void) { emit_log_hook = prev_emit_log_hook; } // --------- безопасный сбор «текущих» фреймов --------- // Если probe выключен — отдаём 1 кадр: анонимный блок + owner. static std::vector collect_now_frames_safe() { std::vector frames; Frame f; f.is_anonymous = true; f.name = "__anonymous_block"; f.line = 0; const char* user = GetUserNameFromId(GetUserId(), false); if (user) f.schema = user; // используем владельца как «owner» для совместимости frames.push_back(f); return frames; } // --------- сбор «текущих» кадров через тихий пробник ---------- static std::vector collect_now_frames_via_probe() { g_last_probe.has = false; g_last_probe.context.clear(); //ereport(WARNING, (errmsg("UTL_CALL_STACK$PROBE"))); if (!g_last_probe.has) return collect_now_frames_safe(); auto frames = parse_context_frames(g_last_probe.context.c_str()); if (frames.empty()) return collect_now_frames_safe(); return frames; } // --------- общая проверка глубины --------- static inline void check_depth_or_raise(int32 depth, int32 max) { if (depth < 1 || depth > max) UTL_CALL_STACK_RAISE_BAD_DEPTH(); } // ================== РЕАЛИЗАЦИИ ================== // ---- BACKTRACE_*: только по последней РЕАЛЬНОЙ ошибке (без внутренних ERROR) ---- Datum utl_call_stack_backtrace_depth(PG_FUNCTION_ARGS) { if (!g_last_error.has) PG_RETURN_INT32(0); auto frames = parse_context_frames(g_last_error.context.c_str()); PG_RETURN_INT32((int32)frames.size()); } Datum utl_call_stack_backtrace_line(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); int32 depth = PG_GETARG_INT32(0); /* Нет последней ошибки — нет бэктрейса: тихо вернуть NULL */ if (!g_last_error.has) PG_RETURN_NULL(); auto frames = parse_context_frames(g_last_error.context.c_str()); if (frames.empty()) PG_RETURN_NULL(); if (depth < 1 || depth > (int32)frames.size()) PG_RETURN_NULL(); PG_RETURN_INT32(frames[(size_t)depth - 1].line); } Datum utl_call_stack_backtrace_unit(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); int32 depth = PG_GETARG_INT32(0); if (!g_last_error.has) PG_RETURN_NULL(); auto frames = parse_context_frames(g_last_error.context.c_str()); if (frames.empty()) PG_RETURN_NULL(); if (depth < 1 || depth > (int32)frames.size()) PG_RETURN_NULL(); std::string s = make_unit_qualified(frames[(size_t)depth - 1]); PG_RETURN_TEXT_P(cstring_to_text(s.c_str())); } // ---- DYNAMIC_*: безопасные значения без зондирования ---- Datum utl_call_stack_dynamic_depth(PG_FUNCTION_ARGS) { /* реальный динамический стек */ auto frames = collect_now_frames_via_probe(); PG_RETURN_INT32((int32)frames.size()); } Datum utl_call_stack_lexical_depth(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); // В PG нет вложенных подпрограмм — всегда 0 для любой корректной глубины int32 depth = PG_GETARG_INT32(0); if (depth != 1) UTL_CALL_STACK_RAISE_BAD_DEPTH(); PG_RETURN_INT32(0); } Datum utl_call_stack_owner(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); int32 depth = PG_GETARG_INT32(0); if (depth != 1) UTL_CALL_STACK_RAISE_BAD_DEPTH(); const char* user = GetUserNameFromId(GetUserId(), false); PG_RETURN_TEXT_P(cstring_to_text(user ? user : "PUBLIC")); } Datum utl_call_stack_unit_line(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); int32 depth = PG_GETARG_INT32(0); // Берём реальные кадры через «тихий» пробник (без исключений/логов наружу) auto frames = collect_now_frames_via_probe(); check_depth_or_raise(depth, (int32)frames.size()); PG_RETURN_INT32(frames[(size_t)depth - 1].line); } Datum utl_call_stack_subprogram(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); int32 depth = PG_GETARG_INT32(0); if (depth != 1) UTL_CALL_STACK_RAISE_BAD_DEPTH(); LOCAL_FCINFO(fcinfo2, 2); text *subprogram_name = cstring_to_text("__anonymous_block"); InitFunctionCallInfoData(*fcinfo2, fcinfo->flinfo, 2, PG_GET_COLLATION(), fcinfo->context, NULL); fcinfo2->args[0].value = PointerGetDatum(subprogram_name); fcinfo2->args[0].isnull = false; fcinfo2->args[1].value = Int32GetDatum(0); fcinfo2->args[1].isnull = false; return utl_call_stack_compose_subprogram(fcinfo2); } Datum utl_call_stack_concatenate_subprogram(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); LOCAL_FCINFO(fcinfo2, 2); InitFunctionCallInfoData(*fcinfo2, fcinfo->flinfo, 2, PG_GET_COLLATION(), fcinfo->context, NULL); fcinfo2->args[0].value = fcinfo->args[0].value; fcinfo2->args[0].isnull = false; fcinfo2->args[1].value = Int32GetDatum(0); fcinfo2->args[1].isnull = false; return utl_call_stack_compose_subprogram(fcinfo2); } Datum utl_call_stack_compose_subprogram(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); text *in = PG_GETARG_TEXT_PP(0); int32 format_mask = PG_ARGISNULL(1) ? 0 : PG_GETARG_INT32(1); const int32 minimum_mask = -48; const int32 supported_mask = 0x03; bool canonicalize_empty_label; bool preserve_owner_hint; int32 normalized_mask; if (format_mask < minimum_mask) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("ORA-06502: invalid format mask"))); normalized_mask = format_mask & supported_mask; canonicalize_empty_label = (normalized_mask & 0x01) != 0; preserve_owner_hint = (normalized_mask & 0x02) != 0; if (canonicalize_empty_label && VARSIZE_ANY_EXHDR(in) == 0) PG_RETURN_TEXT_P(cstring_to_text("")); if (preserve_owner_hint) { /* Reserved for qualified labels assembled from future frame metadata. */ } PG_RETURN_TEXT_P(in); } Datum utl_call_stack_current_edition(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); int32 depth = PG_GETARG_INT32(0); if (depth != 1) UTL_CALL_STACK_RAISE_BAD_DEPTH(); PG_RETURN_TEXT_P(cstring_to_text("ORA$BASE")); } // ---- ERROR_*: по последней ошибке из emit_log_hook ---- static int parse_ora_number(const std::string& msg){ const char* p=strstr(msg.c_str(),"ORA-"); if (!p) return 0; p+=4; int n=0; while(*p && std::isdigit((unsigned char)*p)){ n=n*10+(*p-'0'); ++p; } return n; } Datum utl_call_stack_error_depth(PG_FUNCTION_ARGS) { PG_RETURN_INT32(g_last_error.has ? 1 : 0); } Datum utl_call_stack_error_number(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); int32 depth = PG_GETARG_INT32(0); if (!g_last_error.has || depth != 1) PG_RETURN_NULL(); int ora = 0; const char* p = strstr(g_last_error.message.c_str(), "ORA-"); if (p) { p += 4; while (*p && isdigit((unsigned char)*p)) { ora = ora * 10 + (*p - '0'); ++p; } } if (ora == 0) PG_RETURN_NULL(); PG_RETURN_INT32(ora); } Datum utl_call_stack_error_msg(PG_FUNCTION_ARGS) { if (PG_ARGISNULL(0)) PG_RETURN_NULL(); int32 depth = PG_GETARG_INT32(0); if (!g_last_error.has || depth != 1) PG_RETURN_NULL(); PG_RETURN_TEXT_P(cstring_to_text(g_last_error.message.c_str())); } /// @brief Возвращает версию RUDB пакета UTL_CALL_STACK (Oracle UTL_CALL_STACK пакет) extern "C" Datum utl_call_stack_get_version(PG_FUNCTION_ARGS) { PG_RETURN_TEXT_P(cstring_to_text(RUDB_UTL_CALL_STACK_VERSION)); }