Compare commits

..
Author SHA1 Message Date
BotoX 313c555e2e Add "Restart Current Map" to sm_map menu. 2024-06-09 17:45:27 +02:00
BotoX e5fed0051b Fix GetClientCount(false) 2024-06-09 17:45:27 +02:00
BotoX c2a86c77fd Add damageCustom argument to SDKHooks_TakeDamage native. 2024-06-09 17:45:24 +02:00
BotoX 8c534e770b fix IsMapValid behavior change by a2246af121 2024-06-09 17:41:10 +02:00
BotoX 2c86e8099a Add OnEntitySpawned to SDKHooks. 2024-06-09 17:41:10 +02:00
BotoX 03eeb23ab3 Implement per-client randomized menus with MenuShufflePerClient native.
Add MenuSetClientMapping native.
2024-06-09 17:41:05 +02:00
BotoX a9c85d8842 Changes on sm_*say 2024-06-09 17:39:34 +02:00
BotoX 850ee60a18 Add GetClientIClient native. 2024-06-09 17:39:34 +02:00
Obuss 7cd130904b Logging changes to various base plugins. 2024-06-09 17:39:30 +02:00
BotoX 19019d3a4b Extend function calling API for natives and allow catching exceptions.
Change sourcepawn url.
2024-06-09 17:34:33 +02:00
BotoX b31375f087 Fix @spec not targeting clients in unassigned team. 2024-06-09 17:33:19 +02:00
BotoX 1d999c3984 Added hack to make plugins open a menu with all possible targets on ReplyToTargetError COMMAND_TARGET_AMBIGUOUS.
Explanation:
There are two clients in the server, one named gene, the other one "Ene ~special characters~".
An admin issues "sm_slay Ene" and gets following error message: More than one client matched the given pattern.
What this hack will do is: Use GetCmdArg(0, ...); to get the command name "sm_slay".
Use GetCmdArgString(...); to get the arguments supplied to the command.
Use GetLastProcessTargetString(...); (which was implemented in this commit) to retrieve the arguments that were passed to the last ProcessTargetString call.
It will then pass this data to the DynamicTargeting plugin through its AmbiguousMenu native.
The plugin will open up a menu on the client and list all targets which match the pattern that was supplied to ProcessTargetString.
If the client selects a menu entry, FakeClientCommand will be used to re-execute the command with the correct target.
2024-06-09 17:33:16 +02:00
BotoX fdcbdb6918 Add more macros to CDetour. 2024-06-09 17:32:32 +02:00
476 changed files with 40944 additions and 72168 deletions
+26
View File
@@ -0,0 +1,26 @@
# Help us help you
- [ ] I have checked that my issue [doesn't exist yet](https://github.com/alliedmodders/sourcemod/issues).
- [ ] I have tried my absolute best to reduce the problem-space and have provided the absolute smallest test-case possible.
- [ ] I can always reproduce the issue with the provided description below.
# Environment
* Operating System version:
* Game/AppID (with version if applicable):
* Current SourceMod version:
* Current SourceMod snapshot:
* Current Metamod: Source snapshot:
- [ ] I have updated SourceMod to the [latest version](https://www.sourcemod.net/downloads.php) and it still happens.
- [ ] I have updated SourceMod to the [latest snapshot](https://www.sourcemod.net/downloads.php?branch=dev) and it still happens.
- [ ] I have updated SourceMM to the [latest snapshot](https://sourcemm.net/downloads.php?branch=dev) and it still happens.
# Description
# Problematic Code (or Steps to Reproduce)
```
// TODO(you): code here to reproduce the problem
```
# Logs
* Please attach in separate files: game output, library logs, kernel logs, and any other supporting information.
* In case of a crash, please attach minidump or dump analyze output.
-116
View File
@@ -1,116 +0,0 @@
name: Bug Report
description: Create a report to help us improve
title: "[Bug]: "
labels: ["Bug"]
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to fill out this bug report! Please make sure you provide all the requested information to help us address the issue efficiently.
- type: checkboxes
id: prerequisites
attributes:
label: Prerequisites
description: Please confirm these before submitting your issue
options:
- label: I have checked that my issue doesn't exist yet in the [issue tracker](https://github.com/alliedmodders/sourcemod/issues)
required: true
- type: input
id: os-version
attributes:
label: Operating System and Version
description: What operating system and version are you using?
placeholder: "e.g., Windows 10 21H2, Ubuntu 22.04"
validations:
required: true
- type: input
id: game-version
attributes:
label: Game / AppID and Version
description: Which game and version are you using?
placeholder: "e.g., CS:GO (730) version 1.38.2.5"
validations:
required: true
- type: input
id: sourcemod-version
attributes:
label: SourceMod Version
description: On which version of SourceMod did you first observe this?
placeholder: "e.g., 1.11.0.6936"
validations:
required: true
- type: input
id: metamod-version
attributes:
label: Metamod:Source Version
description: On which version of Metamod:Source did you first observe this?
placeholder: "e.g., 1.11.0-git1145"
- type: checkboxes
id: version-checks
attributes:
label: Version Verification
description: Please confirm you've tested with the latest versions
options:
- label: I have updated SourceMod to the [latest version](https://www.sourcemod.net/downloads.php) and the issue persists
- label: I have updated SourceMod to the [latest snapshot](https://www.sourcemod.net/downloads.php?branch=dev) and the issue persists
- label: I have updated Metamod:Source to the [latest snapshot](https://sourcemm.net/downloads.php?branch=dev) and the issue persists
- type: input
id: sourcemod-version-latest
attributes:
label: Updated SourceMod Version
description: If you updated SourceMod to the latest version to confirm the issue persisted, which version was that?
placeholder: "e.g., 1.11.0.6936"
- type: input
id: metamod-version-latest
attributes:
label: Updated Metamod:Source Version
description: If you updated Metamod:Source to the latest version to confirm the issue persisted, which version was that?
placeholder: "e.g., 1.11.0-git1145"
- type: textarea
id: description
attributes:
label: Description
description: Please provide a clear and concise description of the bug
placeholder: What happened? What did you expect to happen?
validations:
required: true
- type: textarea
id: reproduction
attributes:
label: Steps to Reproduce
description: Please provide the code or steps needed to reproduce the issue
placeholder: |
*If possible, please include the smallest possible test-case to reproduce the issue.*
*Also, please make it clear whether or not you can consistently reproduce this issue with the provided description*
1. First step...
2. Second step...
3. ...
```sourcepawn
// Add your code here if applicable
```
- type: textarea
id: logs
attributes:
label: Relevant Log Output
description: |
Please provide any relevant log output. This will be automatically formatted into code, so no need for backticks.
Include:
- Game output
- Library logs
- Kernel logs
- Minidump or dump analyze output (in case of crashes)
render: shell
-8
View File
@@ -1,8 +0,0 @@
blank_issues_enabled: false
contact_links:
- name: Get Help on Discord
url: https://discord.gg/HUc67zN
about: For general help or assistance, join the AlliedModders Discord or Forums instead of filing a bug
- name: Get Help on the Forums
url: https://forums.alliedmods.net
about: For general help or assistance, join the AlliedModders Discord or Forums instead of filing a bug
-23
View File
@@ -1,23 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: Feature Request
assignees: ''
---
## Help us help you
- [ ] I have checked that my issue [doesn't exist yet](https://github.com/alliedmodders/sourcemod/issues).
## Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
## Describe the solution you'd like
A clear and concise description of what you want to happen.
## Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.
## Additional context
Add any other context or screenshots about the feature request here.
-249
View File
@@ -1,249 +0,0 @@
name: Build Release
on:
push:
branches:
- master
- '[0-9]+.[0-9]+-dev'
env:
ARCH: x86,x86_64
DUMP_SYMS_VERSION: '2.3.7'
# Used for caching
# TODO: Handle this better so that we don't have to update this in lockstep with checkout-deps
MARIADB_CONNECTOR_C_VERSION: '3.4.9'
MARIADB_CONNECTOR_C_RELEASE: '3.4.9-sm.5'
MMSOURCE_VERSION: '1.12'
jobs:
build:
permissions:
contents: write
strategy:
matrix:
include:
- platform: windows
os: windows-latest
os_short: win
- platform: linux
os: ubuntu-latest
os_short: linux
container_image: ghcr.io/alliedmodders/build-containers/debian11-clang22:latest
fail-fast: false
name: ${{ matrix.platform }}
runs-on: ${{ matrix.os }}
container:
image: ${{ matrix.container_image }}
steps:
- name: Checkout SourceMod
uses: actions/checkout@v7
with:
path: sourcemod
fetch-depth: 0
submodules: recursive
- name: Install Windows dependencies
if: startsWith(matrix.os, 'windows')
shell: pwsh
run: |
# Add DIA SDK bin directory to PATH for dump_syms
# vswhere.exe is pre-installed on GitHub Windows runners
$vsRoot = & vswhere -latest -property installationPath
$diaDir = Join-Path $vsRoot 'DIA SDK\bin'
$diaDir | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
$toolsDir = New-Item -Path '_tools' -ItemType Directory -Force
$toolsDir.FullName | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
Push-Location $toolsDir
$dumpsymsUrl = "https://github.com/mozilla/dump_syms/releases/download/v${{ env.DUMP_SYMS_VERSION }}/dump_syms-x86_64-pc-windows-msvc.zip"
curl -sSL -o dump_syms.zip $dumpsymsUrl
Expand-Archive -Path dump_syms.zip -DestinationPath .
Remove-Item dump_syms.zip
# Flatten if extracted into a subdirectory
Get-ChildItem -Recurse -Filter 'dump_syms.exe' | Move-Item -Destination . -ErrorAction SilentlyContinue
Pop-Location
# Largely a workaround for issue where github.workspace doesn't match $GITHUB_WORKSPACE
# in containerized jobs. See https://github.com/actions/runner/issues/2058
- name: Resolve paths
id: path_helper
shell: bash
run: |
echo "dependencies=$GITHUB_WORKSPACE/dependencies" >> $GITHUB_OUTPUT
- name: Generate SDK list
id: sdk_list
shell: bash
run: |
sdk_list=()
for file in sourcemod/hl2sdk-manifests/manifests/*.json; do
sdk=$(basename "$file" .json)
if [[ $sdk == "mock" ]]; then
# We don't need to ship a build for the mock SDK
continue
fi
platform=$(jq -r '.platforms.${{ matrix.platform }}' "$file")
if [[ -z $platform || $platform == "null" || ${#platform[@]} -eq 0 ]]; then
continue
fi
source2=$(jq -r '.source2' "$file")
if [[ $source2 == "null" || $source2 == "true" ]]; then
continue
fi
sdk_list+=("$sdk")
done
echo "sdk_list=$(printf '%s\n' "${sdk_list[@]}" | jq --raw-input . | jq --slurp --compact-output .)" >> $GITHUB_OUTPUT
- name: Cache dependencies
uses: actions/cache@v6
env:
cache-name: hl2sdk-mariadb-connector-c-mmsource
with:
path: ${{ steps.path_helper.outputs.dependencies }}
key: ${{ runner.os }}-build-${{ env.cache-name }}-mariadb${{ env.MARIADB_CONNECTOR_C_RELEASE }}-mmsource${{ env.MMSOURCE_VERSION }}-${{ join(fromJson(steps.sdk_list.outputs.sdk_list), '') }}
restore-keys: |
${{ runner.os }}-build-${{ env.cache-name }}-mariadb${{ env.MARIADB_CONNECTOR_C_RELEASE }}-mmsource${{ env.MMSOURCE_VERSION }}-
${{ runner.os }}-build-${{ env.cache-name }}-mariadb${{ env.MARIADB_CONNECTOR_C_RELEASE }}-
- name: Install dependencies
shell: bash
env:
MAXMIND_LICENSE_KEY: ${{ secrets.MAXMIND_LICENSE_KEY }}
run: |
mkdir -p '${{ steps.path_helper.outputs.dependencies }}'
cd '${{ steps.path_helper.outputs.dependencies }}'
# Satisfy checkout-deps requirement for a "sourcemod" folder.
mkdir -p sourcemod
../sourcemod/tools/checkout-deps.sh -s ${{ join(fromJson(steps.sdk_list.outputs.sdk_list), ',') }}
if [ -z "$MAXMIND_LICENSE_KEY" ]; then
echo "::error::MAXMIND_LICENSE_KEY secret is not configured."
exit 1
fi
geotmpdir=$(mktemp -d)
geotar="$geotmpdir/GeoLite2-City.tar.gz"
curl -fsSL "https://download.maxmind.com/app/geoip_download?edition_id=GeoLite2-City&license_key=$MAXMIND_LICENSE_KEY&suffix=tar.gz" -o "$geotar"
tar -xzf "$geotar" -C "$geotmpdir"
geommdb=$(find "$geotmpdir" -type f -name 'GeoLite2-City.mmdb' | head -n 1)
if [ -z "$geommdb" ]; then
echo "::error::GeoLite2-City.mmdb not found in downloaded MaxMind archive."
exit 1
fi
cp "$geommdb" '${{ steps.path_helper.outputs.dependencies }}/GeoLite2-City.mmdb'
rm -rf "$geotmpdir"
- name: Build
working-directory: sourcemod
shell: bash
env:
BREAKPAD_SYMBOL_SERVER: ${{ vars.BREAKPAD_SYMBOL_SERVER }}
BREAKPAD_SYMBOL_SERVER_TOKEN: ${{ secrets.BREAKPAD_SYMBOL_SERVER_TOKEN }}
run: |
mkdir build
cd build
python3 ../configure.py \
--enable-optimize \
--breakpad-dump \
--symbol-files \
--sdks=${{ join(fromJson(steps.sdk_list.outputs.sdk_list), ',') }} \
--targets=${{ env.ARCH }} \
'--mms-path=${{ steps.path_helper.outputs.dependencies }}/mmsource-${{ env.MMSOURCE_VERSION }}' \
'--hl2sdk-root=${{ steps.path_helper.outputs.dependencies }}' \
'--mariadb-path=${{ steps.path_helper.outputs.dependencies }}/mariadb-connector-c-${{ env.MARIADB_CONNECTOR_C_VERSION }}-x86' \
'--mariadb64-path=${{ steps.path_helper.outputs.dependencies }}/mariadb-connector-c-${{ env.MARIADB_CONNECTOR_C_VERSION }}-x86_64'
ambuild
mkdir -p package/addons/sourcemod/configs/geoip
cp '${{ steps.path_helper.outputs.dependencies }}/GeoLite2-City.mmdb' package/addons/sourcemod/configs/geoip/GeoLite2-City.mmdb
- name: Package
id: package
working-directory: sourcemod/build/package
shell: bash
run: |
version_base=$(cat ../../product.version)
version_base=${version_base%-dev} # Ex. 1.12.0
version_rev=$(git rev-list --count HEAD)
version="${version_base}.${version_rev}"
expanded_version="${version_base}-git${version_rev}"
if [ "${{ matrix.platform}}" == "windows" ]; then
filename="sourcemod-${expanded_version}-${{ matrix.platform }}.zip"
7z a "$filename" addons cfg
content_type="application/zip"
else
filename="sourcemod-${expanded_version}-${{ matrix.platform }}.tar.gz"
tar zcf "$filename" addons cfg
content_type="application/gzip"
fi
echo "version=$version" >> $GITHUB_OUTPUT
echo "expanded_version=$expanded_version" >> $GITHUB_OUTPUT
echo "filename=$filename" >> $GITHUB_OUTPUT
echo "content_type=$content_type" >> $GITHUB_OUTPUT
- name: Create Release
id: create_release
uses: ncipollo/[email protected]
with:
# Windows and Linux packages will need to upload to the same release
allowUpdates: true
replacesArtifacts: false
omitBodyDuringUpdate: true
omitDraftDuringUpdate: true
omitNameDuringUpdate: true
omitPrereleaseDuringUpdate: true
# This gets overly large and meaningless with our existing release patterns
omitBody: true
artifacts: sourcemod/build/package/${{ steps.package.outputs.filename }}
artifactContentType: ${{ steps.package.outputs.content_type }}
artifactErrorsFailBuild: true
tag: ${{ steps.package.outputs.version }}
commit: ${{ github.sha }}
generateReleaseNotes: true
draft: false
prerelease: ${{ github.ref == 'refs/heads/master' }}
makeLatest: ${{ github.ref != 'refs/heads/master' }}
token: ${{ secrets.GITHUB_TOKEN }}
- name: Output PDBs
if: startsWith(matrix.os, 'windows')
shell: pwsh
id: output_pdbs
working-directory: sourcemod/build
run: |
$ErrorActionPreference = 'Stop'
$buildDir = Join-Path -Path $env:GITHUB_WORKSPACE -ChildPath 'sourcemod/build'
$outDir = Join-Path -Path $env:GITHUB_WORKSPACE -ChildPath 'pdbs'
New-Item -ItemType Directory -Force -Path $outDir | Out-Null
Get-Content -LiteralPath (Join-Path -Path $buildDir -ChildPath 'pdblog.txt') |
ForEach-Object -Process {
$fullPdbPathInfo = (Get-Item -Path (Join-Path -Path $buildDir -ChildPath $_))
$baseName = $fullPdbPathInfo.BaseName
$dir = $fullPdbPathInfo.DirectoryName
$relDir = [System.IO.Path]::GetRelativePath($buildDir, $dir)
$destDir = Join-Path $outDir $relDir
New-Item -ItemType Directory -Force -Path $destDir | Out-Null
'.pdb', '.exe', '.dll' | ForEach-Object -Process {
$binPath = Join-Path $dir ($baseName + $_)
if (Test-Path $binPath) {
Copy-Item -Path $binPath -Destination $destDir
}
}
}
- name: Upload PDBs
if: startsWith(matrix.os, 'windows')
id: upload_pdbs
uses: actions/upload-artifact@v7
with:
name: pdbs
path: pdbs/*
-61
View File
@@ -1,61 +0,0 @@
name: Build and Push spcomp Container
on:
push:
branches:
- master
- '[0-9]+.[0-9]+-dev'
tags:
- '*'
pull_request:
branches:
- master
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/master' && !contains(github.ref, '-dev') }}
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}-spcomp
jobs:
build-and-push:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout repository
uses: actions/checkout@v7
with:
submodules: recursive
- name: Log in to the Container registry
if: github.event_name != 'pull_request'
uses: docker/login-action@v4
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v6
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=ref,event=branch
type=ref,event=pr
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
- name: Build and push Docker image
uses: docker/build-push-action@v7
with:
context: .
file: ./containers/Containerfile.spcomp
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
+98
View File
@@ -0,0 +1,98 @@
name: Continuous Integration
on:
push:
branches:
- master
- '[0-9]+.[0-9]+-dev'
pull_request:
branches:
- master
- '[0-9]+.[0-9]+-dev'
jobs:
test:
strategy:
matrix:
os: [ubuntu-20.04, ubuntu-latest, windows-latest]
include:
- os: windows-latest
os_short: win
compiler_cc: msvc
- os: ubuntu-latest
os_short: linux
compiler_cc: clang
compiler_cxx: clang++
- os: ubuntu-20.04
os_short: linux
compiler_cc: clang-8
compiler_cxx: clang++-8
fail-fast: false
runs-on: ${{ matrix.os }}
name: ${{ matrix.os_short }}-${{ matrix.compiler_cc }}
env:
SDKS: '["episode1","css","tf2","l4d2","csgo"]'
ARCH: x86,x86_64
DEPENDENCIES_FOLDER: dependencies
DEPENDENCIES_ROOT: ${{ github.workspace }}/dependencies
MYSQL_VERSION: '5.5'
MMSOURCE_VERSION: '1.12'
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
path: sourcemod
- name: Cache dependencies
uses: actions/cache@v4
env:
cache-name: hl2sdk-mysql-mmsource
with:
path: ${{ env.DEPENDENCIES_ROOT }}
key: ${{ runner.os }}-build-${{ env.cache-name }}-mysql${{ env.MYSQL_VERSION }}-mmsource${{ env.MMSOURCE_VERSION }}-${{ join(fromJSON(env.SDKS), '') }}
restore-keys: |
${{ runner.os }}-build-${{ env.cache-name }}-mysql${{ env.MYSQL_VERSION }}-mmsource${{ env.MMSOURCE_VERSION }}-
${{ runner.os }}-build-${{ env.cache-name }}-mysql${{ env.MYSQL_VERSION }}-
# Setup Python for AMBuild
- uses: actions/setup-python@v5
name: Setup Python 3.8
with:
python-version: 3.8
- name: Install Python dependencies
run: |
python -m pip install --upgrade pip setuptools wheel
- name: Install dependencies
shell: bash
run: |
mkdir -p ${{ env.DEPENDENCIES_FOLDER }}
cd ${{ env.DEPENDENCIES_FOLDER }}
# Satisfy checkout-deps requirement for a "sourcemod" folder.
mkdir -p sourcemod
../sourcemod/tools/checkout-deps.sh -s ${{ join(fromJSON(env.SDKS)) }}
- name: Install Linux dependencies
if: startsWith(runner.os, 'Linux')
run: |
sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
gcc-multilib g++-multilib libstdc++6 lib32stdc++6 \
libc6-dev libc6-dev-i386 linux-libc-dev \
linux-libc-dev:i386 lib32z1-dev ${{ matrix.compiler_cc }}
- name: Select clang compiler
if: startsWith(runner.os, 'Linux')
run: |
echo "CC=${{ matrix.compiler_cc }}" >> $GITHUB_ENV
echo "CXX=${{ matrix.compiler_cxx }}" >> $GITHUB_ENV
${{ matrix.compiler_cc }} --version
${{ matrix.compiler_cxx }} --version
- name: Build
working-directory: sourcemod
run: |
mkdir build
cd build
python ../configure.py --enable-optimize --sdks=${{ join(fromJSON(env.SDKS)) }} --targets=${{ env.ARCH }} --mms-path=${{ env.DEPENDENCIES_ROOT }}/mmsource-${{ env.MMSOURCE_VERSION }} --hl2sdk-root=${{ env.DEPENDENCIES_ROOT }} --mysql-path=${{ env.DEPENDENCIES_ROOT }}/mysql-${{ env.MYSQL_VERSION }} --mysql64-path=${{ env.DEPENDENCIES_ROOT }}/mysql-${{ env.MYSQL_VERSION }}-x86_64
ambuild
+104 -106
View File
@@ -1,106 +1,104 @@
name: hl2sdk-mock tests
on:
push:
branches:
- master
- '[0-9]+.[0-9]+-dev'
pull_request:
branches:
- master
- '[0-9]+.[0-9]+-dev'
jobs:
mock:
runs-on: ubuntu-latest
container:
image: ghcr.io/alliedmodders/build-containers/debian11-clang22:latest
steps:
- uses: actions/checkout@v7
name: Clone sourcemod
with:
submodules: recursive
path: sourcemod
- uses: actions/checkout@v7
name: Clone metamod-source
with:
repository: alliedmodders/metamod-source
ref: 1.12-dev
submodules: recursive
path: metamod-source
- uses: actions/checkout@v7
name: Clone hl2sdk-mock
with:
repository: alliedmodders/hl2sdk-mock
submodules: recursive
path: hl2sdk-mock
- name: Build MetaMod:Source
working-directory: metamod-source
run: |
python3 configure.py --enable-optimize --sdks=mock --targets=x86,x86_64
ambuild objdir
- name: Build SourceMod
working-directory: sourcemod
run: |
python3 configure.py --no-mysql --enable-optimize --sdks=mock --targets=x86,x86_64
ambuild objdir
- name: Build hl2sdk-mock
working-directory: hl2sdk-mock
run: |
python3 configure.py --enable-optimize --targets=x86,x86_64
ambuild objdir
- name: Setup gamedir
working-directory: hl2sdk-mock
shell: bash
run: |
mkdir ../gamedir
./build_gamedir.sh ../gamedir ../metamod-source/objdir/package
./build_gamedir.sh ../gamedir ../sourcemod/objdir/package
- name: Compile testsuite
working-directory: hl2sdk-mock
shell: bash
run: |
mkdir ../gamedir/addons/sourcemod/plugins/optional
for f in ../sourcemod/plugins/testsuite/mock/*.sp; do
echo "Compiling $(basename $f)"
../gamedir/addons/sourcemod/scripting/spcomp64 -i ../gamedir/addons/sourcemod/scripting/include -o "../gamedir/addons/sourcemod/plugins/optional/$(basename $f .sp).smx" -E "$f"
done
- name: Test
working-directory: hl2sdk-mock
shell: bash
run: |
for arch in x86 x86_64; do
echo "==================================="
echo "Testing $arch..."
echo "==================================="
for f in ../gamedir/addons/sourcemod/plugins/optional/*.smx; do
echo "==================================="
echo "Running $(basename $f)..."
echo "==================================="
timeout 60 ./objdir/dist/$arch/srcds -game_dir ../gamedir +map de_thunder -command "sm plugins load optional/$(basename $f)" -run -run-ticks 20 |
{
failed=0
succeeded=0
while IFS= read -r line; do
echo "$line"
if [[ "$line" == *"FAIL"* || "$line" == *"Exception reported"* ]]; then
failed=1
fi
if [[ "$line" == *" OK"* ]]; then
succeeded=1
fi
done
if [ "$failed" = "1" ] || [ "$succeeded" = "0" ]; then
echo "$(basename $f) failed."
exit 1
fi
}
done
done
name: hl2sdk-mock tests
on:
push:
branches:
- master
- '[0-9]+.[0-9]+-dev'
pull_request:
branches:
- master
- '[0-9]+.[0-9]+-dev'
jobs:
mock:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
name: Clone sourcemod
with:
submodules: recursive
path: sourcemod
- uses: actions/checkout@v4
name: Clone metamod-source
with:
repository: alliedmodders/metamod-source
submodules: recursive
path: metamod-source
- uses: actions/checkout@v4
name: Clone hl2sdk-mock
with:
repository: alliedmodders/hl2sdk-mock
submodules: recursive
path: hl2sdk-mock
- uses: actions/setup-python@v5
name: Setup Python 3.10
with:
python-version: "3.10"
- name: Install AMBuild
run: |
python -m pip install --upgrade pip setuptools wheel
pip install git+https://github.com/alliedmodders/ambuild
- name: Build MetaMod:Source
working-directory: metamod-source
run: |
python configure.py --enable-optimize --sdks=mock --targets=x86_64
ambuild objdir
- name: Build SourceMod
working-directory: sourcemod
run: |
python configure.py --no-mysql --enable-optimize --sdks=mock --targets=x86_64
ambuild objdir
- name: Build hl2sdk-mock
working-directory: hl2sdk-mock
run: |
python configure.py --enable-optimize --targets=x86_64
ambuild objdir
- name: Setup gamedir
working-directory: hl2sdk-mock
shell: bash
run: |
mkdir ../gamedir
./build_gamedir.sh ../gamedir ../metamod-source/objdir/package
./build_gamedir.sh ../gamedir ../sourcemod/objdir/package
- name: Compile testsuite
working-directory: hl2sdk-mock
shell: bash
run: |
mkdir ../gamedir/addons/sourcemod/plugins/optional
for f in ../sourcemod/plugins/testsuite/mock/*.sp; do
echo "Compiling $(basename $f)"
../gamedir/addons/sourcemod/scripting/spcomp64 -i ../gamedir/addons/sourcemod/scripting/include -o "../gamedir/addons/sourcemod/plugins/optional/$(basename $f .sp).smx" -E "$f"
done
- name: Test
working-directory: hl2sdk-mock
shell: bash
run: |
for f in ../gamedir/addons/sourcemod/plugins/optional/*.smx; do
echo "==================================="
echo "Running $(basename $f)..."
echo "==================================="
timeout 60 ./objdir/dist/x86_64/srcds -game_dir ../gamedir +map de_thunder -command "sm plugins load optional/$(basename $f)" -run -run-ticks 20 |
{
failed=0
while IFS= read -r line; do
echo "$line"
if [[ "$line" == *"FAIL"* ]]; then
failed=1
fi
done
if [ "$failed" = "1" ]; then
echo "$(basename $f) failed."
exit 1
fi
}
done
-84
View File
@@ -1,84 +0,0 @@
name: PR Checks
on:
pull_request:
branches:
- master
- '[0-9]+.[0-9]+-dev'
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
test:
strategy:
matrix:
include:
- platform: windows
os: windows-latest
os_short: win
- platform: linux
os: ubuntu-latest
os_short: linux
container_image: ghcr.io/alliedmodders/build-containers/debian11-clang22:latest
fail-fast: false
runs-on: ${{ matrix.os }}
container:
image: ${{ matrix.container_image }}
name: ${{ matrix.os_short }}
env:
SDKS: '["episode1","css","tf2","l4d2","csgo","dods"]'
ARCH: x86,x86_64
MARIADB_CONNECTOR_C_VERSION: '3.4.9'
MARIADB_CONNECTOR_C_RELEASE: '3.4.9-sm.5'
MMSOURCE_VERSION: '1.12'
steps:
- uses: actions/checkout@v7
with:
submodules: recursive
path: sourcemod
# Largely a workaround for issue where github.workspace doesn't match $GITHUB_WORKSPACE
# in containerized jobs. See https://github.com/actions/runner/issues/2058
- name: Resolve paths
id: path_helper
shell: bash
run: |
echo "dependencies=$GITHUB_WORKSPACE/dependencies" >> $GITHUB_OUTPUT
- name: Cache dependencies
uses: actions/cache@v6
env:
cache-name: hl2sdk-mariadb-connector-c-mmsource
with:
path: ${{ steps.path_helper.outputs.dependencies }}
key: ${{ runner.os }}-build-${{ env.cache-name }}-mariadb${{ env.MARIADB_CONNECTOR_C_RELEASE }}-mmsource${{ env.MMSOURCE_VERSION }}-${{ join(fromJSON(env.SDKS), '') }}
restore-keys: |
${{ runner.os }}-build-${{ env.cache-name }}-mariadb${{ env.MARIADB_CONNECTOR_C_RELEASE }}-mmsource${{ env.MMSOURCE_VERSION }}-
${{ runner.os }}-build-${{ env.cache-name }}-mariadb${{ env.MARIADB_CONNECTOR_C_RELEASE }}-
- name: Install dependencies
shell: bash
run: |
mkdir -p '${{ steps.path_helper.outputs.dependencies }}'
cd '${{ steps.path_helper.outputs.dependencies }}'
# Satisfy checkout-deps requirement for a "sourcemod" folder.
mkdir -p sourcemod
../sourcemod/tools/checkout-deps.sh -s ${{ join(fromJSON(env.SDKS), ',') }}
- name: Build
working-directory: sourcemod
shell: bash
run: |
mkdir build
cd build
python3 ../configure.py \
--enable-optimize \
--sdks=${{ join(fromJSON(env.SDKS), ',') }} \
--targets=${{ env.ARCH }} \
'--mms-path=${{ steps.path_helper.outputs.dependencies }}/mmsource-${{ env.MMSOURCE_VERSION }}' \
'--hl2sdk-root=${{ steps.path_helper.outputs.dependencies }}' \
'--mariadb-path=${{ steps.path_helper.outputs.dependencies }}/mariadb-connector-c-${{ env.MARIADB_CONNECTOR_C_VERSION }}-x86' \
'--mariadb64-path=${{ steps.path_helper.outputs.dependencies }}/mariadb-connector-c-${{ env.MARIADB_CONNECTOR_C_VERSION }}-x86_64'
ambuild
+13 -7
View File
@@ -14,31 +14,37 @@ jobs:
build:
strategy:
matrix:
os: [ubuntu-latest, windows-latest]
os: [ubuntu-latest, windows-latest, macos-latest]
include:
- os: ubuntu-latest
os_short: linux
- os: windows-latest
os_short: win
- os: macos-latest
os_short: mac
fail-fast: false
runs-on: ${{ matrix.os }}
env:
ARCH: x86,x86_64
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@v4
with:
submodules: recursive
# Setup Python for AMBuild
- uses: actions/setup-python@v7
name: Setup Python 3.12
- uses: actions/setup-python@v5
name: Setup Python 3.8
with:
python-version: 3.12
python-version: 3.8
- name: Install AMBuild
run: |
python -m pip install --upgrade pip setuptools wheel
pip install git+https://github.com/alliedmodders/ambuild
- name: Build universal x64/arm64 on macOS
if: startsWith(runner.os, 'macOS')
run: echo "ARCH=x86_64,arm64" >> $GITHUB_ENV
- name: Install Linux dependencies
if: startsWith(runner.os, 'Linux')
run: |
@@ -50,7 +56,7 @@ jobs:
linux-libc-dev:i386 lib32z1-dev ${{ matrix.compiler_cc }}
- name: Select clang compiler
if: startsWith(runner.os, 'Linux')
if: startsWith(runner.os, 'Linux') || startsWith(runner.os, 'macOS')
run: |
echo "CC=clang" >> $GITHUB_ENV
echo "CXX=clang++" >> $GITHUB_ENV
@@ -67,7 +73,7 @@ jobs:
echo "SM_VERSION=$(cat ../product.version)" >> $GITHUB_ENV
- name: Archive tooling
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v4
with:
name: sourcemod-tooling-${{ env.SM_VERSION }}-${{ matrix.os_short }}
path: build/package
-115
View File
@@ -1,115 +0,0 @@
# srcdslab only (not in alliedmodders/sourcemod): build the patched 1.13-<rev> branches
# (upstream SourceMod at <rev> plus our x86_64 DHooks/BinTools fixes) and publish them as a
# GitHub release. build-release.yml only runs on master and X.Y-dev and needs secrets this
# fork does not have (MAXMIND_LICENSE_KEY, breakpad symbol server), so it is left untouched
# to keep upstream merges clean.
name: srcdslab build
on:
push:
branches:
- '1.13-[0-9]+'
pull_request:
branches:
- '1.13-[0-9]+'
workflow_dispatch:
env:
ARCH: x86,x86_64
# NiDE only runs CS:S on Linux (checked on 2026-11-13), so only that SDK is built.
SDKS: css
MARIADB_CONNECTOR_C_VERSION: '3.4.9'
MARIADB_CONNECTOR_C_RELEASE: '3.4.9-sm.5'
# srcdslab MM:S 1.12-dev carries the Linux x86_64 SourceHook work (srcdslab/metamod-source#4)
# that the x86_64 DHooks needs (x64JitWriter::leave). checkout-deps.sh keeps an existing
# mmsource-1.12 folder and pulls from its own origin, so it stays on this repository.
MMSOURCE_REPO: https://github.com/srcdslab/metamod-source
MMSOURCE_BRANCH: 1.12-dev
jobs:
build:
name: linux
runs-on: ubuntu-latest
container:
image: ghcr.io/alliedmodders/build-containers/debian11-clang22:latest
permissions:
contents: write
steps:
- name: Checkout SourceMod
uses: actions/checkout@v7
with:
path: sourcemod
fetch-depth: 0
submodules: recursive
- name: Install dependencies
shell: bash
run: |
set -euo pipefail
mkdir -p "$GITHUB_WORKSPACE/dependencies"
cd "$GITHUB_WORKSPACE/dependencies"
# Satisfy checkout-deps requirement for a "sourcemod" folder.
mkdir -p sourcemod
git clone --recursive -b "$MMSOURCE_BRANCH" "$MMSOURCE_REPO" mmsource-1.12
../sourcemod/tools/checkout-deps.sh -s "$SDKS"
- name: Build
working-directory: sourcemod
shell: bash
run: |
set -euo pipefail
deps="$GITHUB_WORKSPACE/dependencies"
mkdir build
cd build
python3 ../configure.py \
--enable-optimize \
--sdks="$SDKS" \
--targets="$ARCH" \
--mms-path="$deps/mmsource-1.12" \
--hl2sdk-root="$deps" \
--mariadb-path="$deps/mariadb-connector-c-$MARIADB_CONNECTOR_C_VERSION-x86" \
--mariadb64-path="$deps/mariadb-connector-c-$MARIADB_CONNECTOR_C_VERSION-x86_64"
ambuild
- name: Package
id: package
working-directory: sourcemod/build/package
shell: bash
run: |
set -euo pipefail
version_base=$(cat ../../product.version)
version_base=${version_base%-dev}
version_rev=$(git rev-list --count HEAD)
version="${version_base}.${version_rev}"
filename="sourcemod-${version_base}-git${version_rev}-srcdslab-linux.tar.gz"
# Fail early if the x86_64 DHooks or BinTools did not build.
for ext in dhooks bintools; do
test -f "addons/sourcemod/extensions/x64/$ext.ext.so"
done
tar zcf "$filename" addons cfg
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "filename=$filename" >> "$GITHUB_OUTPUT"
- name: Upload package
uses: actions/upload-artifact@v7
with:
name: sourcemod-${{ steps.package.outputs.version }}-linux
path: sourcemod/build/package/${{ steps.package.outputs.filename }}
- name: Create release
if: github.event_name == 'push'
uses: ncipollo/[email protected]
with:
allowUpdates: true
replacesArtifacts: true
artifacts: sourcemod/build/package/${{ steps.package.outputs.filename }}
artifactContentType: application/gzip
artifactErrorsFailBuild: true
tag: ${{ steps.package.outputs.version }}-srcdslab
name: SourceMod ${{ steps.package.outputs.version }} (srcdslab ${{ github.ref_name }})
body: |
SourceMod built from the srcdslab `${{ github.ref_name }}` branch: upstream SourceMod plus the srcdslab x86_64 DHooks and BinTools fixes, against srcdslab/metamod-source `${{ env.MMSOURCE_BRANCH }}`.
CS:S only, Linux x86 and x86_64. No GeoLite2 database is included.
commit: ${{ github.sha }}
makeLatest: true
token: ${{ secrets.GITHUB_TOKEN }}
+2 -2
View File
@@ -10,11 +10,11 @@ jobs:
update_translations:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@v4
with:
submodules: recursive
- uses: actions/setup-python@v7
- uses: actions/setup-python@v5
name: Setup Python 3.10
with:
python-version: "3.10"
@@ -15,9 +15,9 @@ jobs:
check_translations:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@v4
- uses: actions/setup-python@v7
- uses: actions/setup-python@v5
name: Setup Python 3.10
with:
python-version: "3.10"
+1 -1
View File
@@ -37,7 +37,7 @@ obj-*/
*.gdb_history
objdir
# Not standardized, but common name for build directories
/build*/
build*/
.vs/*
.vscode/*
+51 -98
View File
@@ -42,10 +42,11 @@ class SMConfig(object):
self.sdks = {}
self.sdk_targets = []
self.binaries = []
self.spvm = []
self.extensions = []
self.generated_headers = None
self.mms_root = None
self.mariadb_root = {}
self.mysql_root = {}
self.spcomp = None
self.spcomp_bins = []
self.smx_files = {}
@@ -128,8 +129,6 @@ class SMConfig(object):
self.mms_root = builder.options.mms_path
else:
self.mms_root = ResolveEnvPath('MMSOURCE112', 'mmsource-1.12')
if not self.mms_root:
self.mms_root = ResolveEnvPath('MMSOURCE', 'metamod-source')
if not self.mms_root:
self.mms_root = ResolveEnvPath('MMSOURCE_DEV', 'metamod-source')
if not self.mms_root:
@@ -141,26 +140,28 @@ class SMConfig(object):
if builder.options.hasMySql:
if 'x86' in self.target_archs:
mariadb_path = getattr(builder.options, 'mariadb_path',
getattr(builder.options, 'mysql_path', None))
if mariadb_path:
self.mariadb_root['x86'] = mariadb_path
if builder.options.mysql_path:
self.mysql_root['x86'] = builder.options.mysql_path
else:
self.mariadb_root['x86'] = ResolveEnvPath('MARIADB_CONNECTOR_C', 'mariadb-connector-c-x86')
if not self.mariadb_root['x86'] or not os.path.isdir(self.mariadb_root['x86']):
raise Exception('Could not find an x86 MariaDB Connector/C path. Configure with --no-mysql to disable it.')
self.mariadb_root['x86'] = Normalize(self.mariadb_root['x86'])
for i in range(10):
self.mysql_root['x86'] = ResolveEnvPath('MYSQL55', 'mysql-5.' + str(i))
if self.mysql_root['x86']:
break
if not self.mysql_root['x86'] or not os.path.isdir(self.mysql_root['x86']):
raise Exception('Could not find a path to MySQL. Configure with --no-mysql to disable it.')
self.mysql_root['x86'] = Normalize(self.mysql_root['x86'])
if 'x86_64' in self.target_archs:
mariadb64_path = getattr(builder.options, 'mariadb64_path',
getattr(builder.options, 'mysql64_path', None))
if mariadb64_path:
self.mariadb_root['x86_64'] = mariadb64_path
if builder.options.mysql64_path:
self.mysql_root['x86_64'] = builder.options.mysql64_path
else:
self.mariadb_root['x86_64'] = ResolveEnvPath('MARIADB_CONNECTOR_C_64', 'mariadb-connector-c-x86_64')
if not self.mariadb_root['x86_64'] or not os.path.isdir(self.mariadb_root['x86_64']):
raise Exception('Could not find an x86_64 MariaDB Connector/C path.')
self.mariadb_root['x86_64'] = Normalize(self.mariadb_root['x86_64'])
for i in range(10):
self.mysql_root['x86_64'] = ResolveEnvPath('MYSQL55_64', 'mysql-5.' + str(i) + '-x86_64')
if self.mysql_root['x86_64']:
break
if not self.mysql_root['x86_64'] or not os.path.isdir(self.mysql_root['x86_64']):
raise Exception('Could not find a path to 64-bit MySQL!')
self.mysql_root['x86_64'] = Normalize(self.mysql_root['x86_64'])
def configure(self):
builder.AddConfigureFile('pushbuild.txt')
@@ -194,7 +195,9 @@ class SMConfig(object):
elif cxx.family == 'msvc':
self.configure_msvc(cxx)
# Optimization flags are applied separately, earlier in configure_optimize so that the SDK static libs inherit them.
# Optimizaiton
if builder.options.opt == '1':
cxx.defines += ['NDEBUG']
# Debugging
if builder.options.debug == '1':
@@ -223,32 +226,6 @@ class SMConfig(object):
os.path.join(builder.sourcePath, 'versionlib'),
]
def configure_optimize(self, cxx):
if builder.options.opt != '1':
return
cxx.defines += ['NDEBUG']
if cxx.like('gcc'):
if self.enable_asan:
cxx.cflags += ['-O1']
else:
cxx.cflags += ['-O3']
elif cxx.family == 'msvc':
cxx.cflags += ['/Ox', '/Zo']
cxx.linkflags += ['/OPT:ICF', '/OPT:REF']
def configure_pre_sdk(self, cxx):
self.configure_optimize(cxx)
if not cxx.like('gcc'):
return
if cxx.target.arch in ['x86', 'x86_64']:
cxx.cflags += ['-msse']
if cxx.family == 'gcc':
cxx.cflags += ['-mfpmath=sse']
if cxx.target.platform == 'linux' and cxx.target.arch == 'x86':
cxx.cflags += ['-mstackrealign']
def configure_gcc(self, cxx):
cxx.defines += [
'stricmp=strcasecmp',
@@ -266,12 +243,12 @@ class SMConfig(object):
'-Wno-unused',
'-Wno-switch',
'-Wno-array-bounds',
'-Wno-unknown-pragmas',
'-Wno-dangling-else',
'-fvisibility=hidden',
]
if cxx.target.arch in ['x86', 'x86_64']:
cxx.cflags += ['-msse']
cxx.cxxflags += ['-std=c++20']
cxx.cxxflags += ['-std=c++17']
cxx.cxxflags += [
'-fno-threadsafe-statics',
@@ -312,10 +289,6 @@ class SMConfig(object):
raise Exception('--enable-asan only supported when using Clang')
self.configure_asan(cxx)
# AMTL uses std::bind
if (have_gcc and cxx.version >= 'gcc-10.0') or (have_clang and cxx.version >= 'clang-12.0'):
cxx.cxxflags += ['-Wno-deprecated-declarations']
# Work around SDK warnings.
if cxx.version >= 'clang-10.0' or cxx.version >= 'apple-clang-12.0':
cxx.cflags += [
@@ -323,20 +296,15 @@ class SMConfig(object):
'-Wno-tautological-overlap-compare',
]
if cxx.version >= 'clang-21.0':
cxx.cflags += ['-Wno-uninitialized-const-pointer']
if cxx.version >= 'clang-16.0' or cxx.version >= 'apple-clang-15.0':
cxx.cxxflags += ['-Wno-deprecated-anon-enum-enum-conversion']
# C++20 deprecates volatile ++/-- and compound assignment (P1152R4).
if cxx.version >= 'clang-12.0' or cxx.version >= 'apple-clang-13.0':
cxx.cxxflags += ['-Wno-deprecated-volatile']
if have_gcc:
cxx.cflags += ['-mfpmath=sse']
cxx.cflags += ['-Wno-maybe-uninitialized']
# Optimization flags are applied separately, earlier in configure_optimize so that the SDK static libs inherit them.
if builder.options.opt == '1':
if self.enable_asan:
cxx.cflags += ['-O1']
else:
cxx.cflags += ['-O3']
# Don't omit the frame pointer.
cxx.cflags += ['-fno-omit-frame-pointer']
@@ -363,7 +331,7 @@ class SMConfig(object):
'/EHsc',
'/GR-',
'/TP',
'/std:c++20',
'/std:c++17',
]
cxx.linkflags += [
'kernel32.lib',
@@ -380,7 +348,9 @@ class SMConfig(object):
'odbccp32.lib',
]
# Optimization flags are applied separately, earlier in configure_optimize so that the SDK static libs inherit them.
if builder.options.opt == '1':
cxx.cflags += ['/Ox', '/Zo']
cxx.linkflags += ['/OPT:ICF', '/OPT:REF']
if builder.options.debug == '1':
cxx.cflags += ['/Od', '/RTC1']
@@ -420,7 +390,6 @@ class SMConfig(object):
elif cxx.family == 'clang':
cxx.linkflags += ['-lgcc_eh']
cxx.linkflags += ['-static-libstdc++']
cxx.linkflags += ['-Wl,--exclude-libs=libstdc++.a']
def configure_mac(self, cxx):
cxx.defines += ['OSX', '_OSX', 'POSIX', 'KE_ABSOLUTELY_NO_STL']
@@ -443,34 +412,19 @@ class SMConfig(object):
return lambda builder, name: self.StaticLibrary(builder, cxx, name)
extra_vars = {'Configure': get_configure_fn(cxx)}
libamtl = builder.Build('public/amtl/amtl/AMBuilder', extra_vars)
self.libamtl[cxx.target] = libamtl.binary
self.libamtl[cxx.target.arch] = libamtl.binary
def BinaryOutputName(self, binary, binary_type):
target = binary.compiler.target
if binary_type == 'program':
name_fn = binary.compiler.vendor.nameForExecutable
elif binary_type == 'library':
name_fn = binary.compiler.vendor.nameForSharedLibrary
else:
raise Exception('Unsupported binary type: {}'.format(binary_type))
try:
return name_fn(binary.name_, target)
except TypeError:
# Older AMBuild versions did not require the target argument.
return name_fn(binary.name_)
def AddVersioning(self, binary, binary_type):
def AddVersioning(self, binary):
if binary.compiler.target.platform == 'windows':
binary.sources += ['version.rc']
binary.compiler.rcdefines += [
'BINARY_NAME="{0}"'.format(self.BinaryOutputName(binary, binary_type)),
'BINARY_NAME="{0}"'.format(binary.outputFile),
'RC_COMPILE',
]
if self.use_auto_versioning():
binary.compiler.rcdefines += ['SM_GENERATED_BUILD']
elif binary.compiler.target.platform == 'mac':
if binary_type == 'library':
if binary.type == 'library':
binary.compiler.postlink += [
'-compatibility_version', '1.0.0',
'-current_version', self.productVersion
@@ -482,7 +436,7 @@ class SMConfig(object):
def LibraryBuilder(self, compiler, name):
binary = compiler.Library(name)
self.AddVersioning(binary, 'library')
self.AddVersioning(binary)
if binary.compiler.like('msvc'):
binary.compiler.linkflags += ['/SUBSYSTEM:WINDOWS']
self.AddCxxCompat(binary)
@@ -497,7 +451,7 @@ class SMConfig(object):
def ProgramBuilder(self, compiler, name):
binary = compiler.Program(name)
self.AddVersioning(binary, 'program')
self.AddVersioning(binary)
if '-static-libgcc' in binary.compiler.linkflags:
binary.compiler.linkflags.remove('-static-libgcc')
if self.enable_asan:
@@ -587,14 +541,14 @@ class SMConfig(object):
binary = project.Configure(compiler, name,
'{0} - {1} {2}'.format(self.tag, sdk['name'], compiler.target.arch))
self.AddCxxCompat(binary)
self.AddVersioning(binary, 'library')
self.AddVersioning(binary)
return self.ConfigureForHL2(context, binary, sdk)
def HL2ExtConfig(self, project, context, compiler, name, sdk):
binary = project.Configure(compiler, name,
'{0} - {1} {2}'.format(self.tag, sdk['name'], compiler.target.arch))
self.AddCxxCompat(binary)
self.AddVersioning(binary, 'library')
self.AddVersioning(binary)
self.ConfigureForHL2(context, binary, sdk)
self.ConfigureForExtension(context, binary.compiler)
return binary
@@ -607,10 +561,6 @@ if getattr(builder, 'target', None) is not None:
SM = SMConfig()
SM.detectProductVersion()
# Apply settings that SDK static libraries must inherit to the base compilers
# before detectSDKs() clones them.
for cxx in SM.all_targets:
SM.configure_pre_sdk(cxx)
if not getattr(builder.options, 'scripting_only', False):
SM.detectSDKs()
SM.configure()
@@ -685,13 +635,16 @@ for spcomp in SP.spcomp:
SM.spcomp = spcomp
SM.spcomp_bins.append(spcomp)
for spcomp in SP.oldspcomp:
SM.spcomp_bins.append(spcomp)
# If we have a universal binary, ignore all other spcomps.
if SM.spcomp.target.arch == 'universal':
SM.spcomp_bins = [SM.spcomp]
if not getattr(builder.options, 'scripting_only', False):
for cxx in SM.all_targets:
SM.spvm += [
SP.libsourcepawn[cxx.target.arch]
]
if getattr(builder.options, 'scripting_only', False):
BuildScripts = [
'tools/buildbot/PackageHelpers',
@@ -726,7 +679,7 @@ else:
'tools/buildbot/PackageScript',
]
builder.Build(BuildScripts, { 'SM': SM, 'SP': SP })
builder.Build(BuildScripts, { 'SM': SM })
if builder.options.breakpad_dump:
builder.Build('tools/buildbot/BreakpadSymbols', { 'SM': SM })
+1 -1
View File
@@ -35,7 +35,7 @@ namespace SourceMod {
// Add 1 to the RHS of this expression to bump the intercom file
// This is to prevent mismatching core/logic binaries
static const uint32_t SM_LOGIC_MAGIC = 0x0F47C0DE - 58;
static const uint32_t SM_LOGIC_MAGIC = 0x0F47C0DE - 57;
} // namespace SourceMod
+8 -4
View File
@@ -30,7 +30,12 @@
#include <stddef.h>
#include <stdint.h>
#include <IAdminSystem.h>
#include <functional>
#include <amtl/am-function.h>
namespace SourcePawn {
class ISourcePawnEngine;
class ISourcePawnEngine2;
} // namespace SourcePawn
// SDK types.
#if defined(SM_LOGIC)
@@ -62,7 +67,7 @@ struct DatabaseInfo;
class IPlayerInfoBridge;
class ICommandArgs;
typedef std::function<bool(int client, const ICommandArgs*)> CommandFunc;
typedef ke::Function<bool(int client, const ICommandArgs*)> CommandFunc;
class CoreProvider
{
@@ -78,7 +83,6 @@ public:
IMenuManager *menus;
SourcePawn::ISourcePawnEngine **spe1;
SourcePawn::ISourcePawnEngine2 **spe2;
SourcePawn::ISourcePawnEnvironment **spe_env;
const char *gamesuffix;
/* Data */
ServerGlobals *serverGlobals;
@@ -102,7 +106,7 @@ public:
virtual bool IsMapLoading() = 0;
virtual bool IsMapRunning() = 0;
virtual int MaxClients() = 0;
virtual bool DescribePlayer(int entRef, const char **namep, const char **authp, int *useridp) = 0;
virtual bool DescribePlayer(int index, const char **namep, const char **authp, int *useridp) = 0;
virtual void LogToGame(const char *message) = 0;
virtual void ConPrint(const char *message) = 0;
virtual void ConsolePrint(const char *fmt, ...) = 0;
+6 -5
View File
@@ -29,12 +29,13 @@
#include <sp_vm_api.h>
#include <IExtensionSys.h>
#include <vector>
#include <sh_vector.h>
struct edict_t;
namespace SourceMod {
using namespace SourceHook;
using namespace SourcePawn;
class SMPlugin;
@@ -50,8 +51,8 @@ public:
virtual IExtension *GetExtensionFromIdent(IdentityToken_t *token) = 0;
virtual void BindChildPlugin(IExtension *ext, SMPlugin *plugin) = 0;
virtual void AddRawDependency(IExtension *myself, IdentityToken_t *token, void *iface) = 0;
virtual const std::vector<IExtension *> *ListExtensions() = 0;
virtual void FreeExtensionList(const std::vector<IExtension *> *list) = 0;
virtual const CVector<IExtension *> *ListExtensions() = 0;
virtual void FreeExtensionList(const CVector<IExtension *> *list) = 0;
virtual void CallOnCoreMapEnd() = 0;
};
@@ -66,13 +67,13 @@ public:
{
extensions_->FreeExtensionList(list_);
}
const std::vector<IExtension *> *operator ->()
const CVector<IExtension *> *operator ->()
{
return list_;
}
private:
IExtensionSys *extensions_;
const std::vector<IExtension *> *list_;
const CVector<IExtension *> *list_;
};
} // namespace SourceMod
-21
View File
@@ -32,18 +32,6 @@ typedef int FileFindHandle_t;
namespace SourceMod {
typedef void *AsyncControl_t;
enum AsyncStatus
{
AsyncStatus_FileOpenError = -1,
AsyncStatus_Ok = 0,
AsyncStatus_Pending,
AsyncStatus_InProgress,
AsyncStatus_Aborted,
AsyncStatus_Unserviced,
};
class IFileSystemBridge
{
public:
@@ -70,15 +58,6 @@ public:
virtual bool IsDirectory(const char *pFileName, const char *pathID = 0) = 0;
virtual void CreateDirHierarchy(const char *path, const char *pathID = 0) = 0;
virtual int GetSearchPath(const char* pathID, bool bGetPackFiles, char* pPath, int nMaxLen) = 0;
virtual const char * GetGameBinArchSubdirectory() = 0;
virtual bool SupportsAsync() = 0;
virtual int AsyncRead(const char *filename, const char *pathID, AsyncControl_t *control) = 0;
virtual int AsyncWrite(const char *filename, const void *data, int size, bool append,
AsyncControl_t *control) = 0;
virtual int AsyncStatus(AsyncControl_t control) = 0;
virtual int AsyncGetResult(AsyncControl_t control, void **data, int *size) = 0;
virtual void AsyncAbort(AsyncControl_t control) = 0;
virtual void AsyncRelease(AsyncControl_t control) = 0;
};
} // namespace SourceMod
+10 -8
View File
@@ -29,11 +29,12 @@
#include <sp_vm_api.h>
#include <IPluginSys.h>
#include <vector>
#include <string>
#include <sh_vector.h>
#include <sh_string.h>
namespace SourceMod {
using namespace SourceHook;
using namespace SourcePawn;
class IChangeableForward;
@@ -46,8 +47,8 @@ enum LibraryAction
struct AutoConfig
{
std::string autocfg;
std::string folder;
SourceHook::String autocfg;
SourceHook::String folder;
bool create;
};
@@ -77,11 +78,12 @@ public:
virtual SMPlugin *FindPluginByOrder(unsigned num) = 0;
virtual SMPlugin *FindPluginByIdentity(IdentityToken_t *ident) = 0;
virtual SMPlugin *FindPluginByContext(IPluginContext *ctx) = 0;
virtual SMPlugin *FindPluginByContext(sp_context_t *ctx) = 0;
virtual SMPlugin *FindPluginByConsoleArg(const char *text) = 0;
virtual SMPlugin *FindPluginByHandle(Handle_t hndl, HandleError *errp) = 0;
virtual bool UnloadPlugin(IPlugin *plugin) = 0;
virtual const std::vector<SMPlugin *> *ListPlugins() = 0;
virtual void FreePluginList(const std::vector<SMPlugin *> *list) = 0;
virtual const CVector<SMPlugin *> *ListPlugins() = 0;
virtual void FreePluginList(const CVector<SMPlugin *> *list) = 0;
virtual void AddFunctionsToForward(const char *name, IChangeableForward *fwd) = 0;
};
@@ -96,13 +98,13 @@ public:
{
scripts_->FreePluginList(list_);
}
const std::vector<SMPlugin *> *operator ->()
const CVector<SMPlugin *> *operator ->()
{
return list_;
}
private:
IScriptManager *scripts_;
const std::vector<SMPlugin *> *list_;
const CVector<SMPlugin *> *list_;
};
} // namespace SourceMod
+2 -13
View File
@@ -52,14 +52,6 @@ class ITextParsers;
class ILogger;
class ICellArray;
class IEntityLumpWriter
{
public:
virtual void Reset() = 0;
virtual bool AppendEntity() = 0;
virtual bool AppendPair(const char *key, const char *value) = 0;
};
struct sm_logic_t
{
SMGlobalClass *head;
@@ -79,14 +71,11 @@ struct sm_logic_t
void (*RegisterProfiler)(IProfilingTool *tool);
ICellArray * (*CreateCellArray)(size_t blocksize);
void (*FreeCellArray)(ICellArray *arr);
void * (*FromPseudoAddress)(uint32_t pseudoAddr);
uint32_t (*ToPseudoAddress)(void *addr);
void (*SetEntityLumpWritable)(bool writable);
bool (*ParseEntityLumpString)(const char *entityString, int &status, size_t &position);
const char * (*GetEntityLumpString)();
IEntityLumpWriter *(*GetEntityLumpWriter)();
bool (*CopyEntityLump)(IEntityLumpWriter *writer);
void (*Shutdown)();
void (*SetJitEnabled)(bool enabled);
void (*SetDebugMetadataFlags)(int flags);
IScriptManager *scripts;
IShareSys *sharesys;
IExtensionSys *extsys;
-26
View File
@@ -21,15 +21,6 @@
*/
"LogMode" "daily"
/**
* This option determines the time format SourceMod logging should use.
*
* "default" - Uses SourceMod's default time format. (%m/%d/%Y - %H:%M:%S)
* You can specify any time format you want. See https://cplusplus.com/reference/ctime/strftime/ for a list of format parameters.
* Example: "%d/%m/%Y - %H:%M:%S"
*/
"LogTimeFormat" "default"
/**
* Language that multilingual enabled plugins and extensions will use to print messages.
* Only languages listed in languages.cfg are valid.
@@ -117,16 +108,6 @@
*/
"BlockBadPlugins" "yes"
/**
* Controls how plugin unloads handle outstanding threaded database operations.
*
* "discard" - Immediately discard the plugin's outstanding database operations.
* This is the default and keeps the server responsive.
* "wait" - Wait for outstanding operations and run their callbacks before unload.
* Warning: This can stall the server.
*/
"DatabasePluginUnload" "discard"
/**
* If a plugin takes too long to execute, hanging or freezing the game server in the process,
* SourceMod will attempt to terminate that plugin after the specified timeout length has
@@ -157,11 +138,4 @@
* "jitdump" - Generate extended perf metadata (Linux only - function names, bytecode, and source information)
*/
"JITMetadata" "default"
/**
* Setup the SourcePawn VM to enable extensions to use a debugging API to step through
* plugins line by line. This heavily decreases server performance and should NEVER be
* used on a production server, but ONLY during plugin development.
*/
"EnableLineDebugging" "no"
}
-1
View File
@@ -13,7 +13,6 @@
"pass" ""
//"timeout" "0"
//"port" "0"
//"schema" "public" // PostgreSQL only
}
"storage-local"
@@ -16,7 +16,7 @@ CREATE TABLE IF NOT EXISTS sm_cookie_cache
PRIMARY KEY (player, cookie_id)
);
CREATE OR REPLACE LANGUAGE plpgsql;
CREATE LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION add_or_update_cookie(in_player VARCHAR(65), in_cookie INT, in_value VARCHAR(100), in_time INT) RETURNS VOID AS
$$
@@ -1,4 +1,4 @@
CREATE TABLE IF NOT EXISTS sm_admins (
CREATE TABLE sm_admins (
id serial,
authtype varchar(6) NOT NULL,
CHECK (authtype in ('steam', 'name', 'ip')),
@@ -10,7 +10,7 @@ CREATE TABLE IF NOT EXISTS sm_admins (
PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS sm_groups (
CREATE TABLE sm_groups (
id serial,
flags varchar(30) NOT NULL,
name varchar(120) NOT NULL,
@@ -18,7 +18,7 @@ CREATE TABLE IF NOT EXISTS sm_groups (
PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS sm_group_immunity (
CREATE TABLE sm_group_immunity (
group_id int NOT NULL,
other_id int NOT NULL,
FOREIGN KEY (group_id) REFERENCES sm_groups(id) ON DELETE CASCADE,
@@ -26,7 +26,7 @@ CREATE TABLE IF NOT EXISTS sm_group_immunity (
PRIMARY KEY (group_id, other_id)
);
CREATE TABLE IF NOT EXISTS sm_group_overrides (
CREATE TABLE sm_group_overrides (
group_id int NOT NULL,
FOREIGN KEY (group_id) REFERENCES sm_groups(id) ON DELETE CASCADE,
type varchar(10) NOT NULL,
@@ -37,7 +37,7 @@ CREATE TABLE IF NOT EXISTS sm_group_overrides (
PRIMARY KEY (group_id, type, name)
);
CREATE TABLE IF NOT EXISTS sm_overrides (
CREATE TABLE sm_overrides (
type varchar(10) NOT NULL,
CHECK (type in ('command', 'group')),
name varchar(32) NOT NULL,
@@ -45,7 +45,7 @@ CREATE TABLE IF NOT EXISTS sm_overrides (
PRIMARY KEY (type,name)
);
CREATE TABLE IF NOT EXISTS sm_admins_groups (
CREATE TABLE sm_admins_groups (
admin_id int NOT NULL,
group_id int NOT NULL,
FOREIGN KEY (admin_id) REFERENCES sm_admins(id) ON DELETE CASCADE,
@@ -56,10 +56,10 @@ CREATE TABLE IF NOT EXISTS sm_admins_groups (
-- side note, this is pgsql module, sm_config will not exist if the above stuff exists... and it's being left to the admin
-- to figure out if it exists.
CREATE TABLE IF NOT EXISTS sm_config (
CREATE TABLE sm_config (
cfg_key varchar(32) NOT NULL,
cfg_value varchar(255) NOT NULL,
PRIMARY KEY (cfg_key)
);
INSERT INTO sm_config (cfg_key, cfg_value) VALUES ('admin_version', '1.0.0.1409') ON CONFLICT (cfg_key) DO UPDATE SET cfg_value = EXCLUDED.cfg_value;
INSERT INTO sm_config (cfg_key, cfg_value) VALUES ('admin_version', '1.0.0.1409');
+4 -4
View File
@@ -21,10 +21,10 @@ if ambuild_version.startswith('2.1'):
parser = run.BuildParser(sourcePath=sys.path[0], api='2.2')
parser.options.add_argument('--hl2sdk-root', type=str, dest='hl2sdk_root', default=None,
help='Root search folder for HL2SDKs')
parser.options.add_argument('--mariadb-path', type=str, dest='mariadb_path', default=None,
help='Path to x86 MariaDB Connector/C')
parser.options.add_argument('--mariadb64-path', type=str, dest='mariadb64_path', default=None,
help='Path to x86_64 MariaDB Connector/C')
parser.options.add_argument('--mysql-path', type=str, dest='mysql_path', default=None,
help='Path to MySQL 5')
parser.options.add_argument('--mysql64-path', type=str, dest='mysql64_path', default=None,
help='Path to 64-bit MySQL 5')
parser.options.add_argument('--mms-path', type=str, dest='mms_path', default=None,
help='Path to Metamod:Source')
parser.options.add_argument('--enable-debug', action='store_const', const='1', dest='debug',
-18
View File
@@ -1,18 +0,0 @@
# Build stage - use the same image as sourcemod CI builds
FROM ghcr.io/alliedmodders/build-containers/debian11:latest AS builder
COPY sourcepawn/ /build/sourcepawn/
WORKDIR /build/sourcepawn
RUN mkdir build && cd build && \
python3 ../configure.py --enable-optimize --targets=x86_64 && \
ambuild
# Runtime stage
FROM debian:bullseye-slim
# AMBuild names the per-target output folder <platform>-<arch>; since this stage
# always builds linux/x86_64, that's deterministically "linux-x86_64".
COPY --from=builder --chmod=0755 /build/sourcepawn/build/spcomp/linux-x86_64/spcomp /usr/local/bin/spcomp
ENTRYPOINT ["/usr/local/bin/spcomp"]
+3 -23
View File
@@ -42,12 +42,11 @@ project.sources += [
'GameHooks.cpp',
]
# SDK name to shipping gamedir, mostly
# SDK name to shipping gamedir
pb_gamedir_map = {
'csgo': 'csgo',
'blade': 'berimbau',
'mcv': 'vietnam',
'outbreak': 'terror'
}
# SDK name to source code gamedir
@@ -55,7 +54,6 @@ pb_gamesrcdir_map = {
'csgo': 'cstrike15',
'blade': 'berimbau',
'mcv': 'vietnam',
'outbreak': 'terror',
}
for sdk_target in SM.sdk_targets:
@@ -63,7 +61,7 @@ for sdk_target in SM.sdk_targets:
cxx = sdk_target.cxx
binary_name = 'sourcemod.' + sdk['extension']
needs_protobuf = sdk['name'] in ['csgo', 'blade', 'mcv', 'outbreak']
needs_protobuf = sdk['name'] in ['csgo', 'blade', 'mcv']
binary = SM.HL2Config(project, builder, cxx, binary_name, sdk)
SM.ConfigureForExtension(builder, binary.compiler)
@@ -75,22 +73,10 @@ for sdk_target in SM.sdk_targets:
if needs_protobuf:
compiler.cxxincludes += [
os.path.join(sdk['path'], 'common', 'protobuf-2.5.0', 'src'),
os.path.join(sdk['path'], 'public', 'engine', 'protobuf'),
os.path.join(sdk['path'], 'public', 'game', 'shared', pb_gamedir_map[sdk['name']], 'protobuf')
]
if sdk['name'] == 'outbreak':
compiler.cxxincludes += [
# Outbreak has "base" usermessages split from the game-specific ones
os.path.join(sdk['path'], 'public', 'game', 'shared', 'protobuf')
]
protobuf_version = "2.5.0"
if sdk['name'] == 'mcv':
protobuf_version = "3.2.0"
elif sdk['name'] == 'outbreak':
protobuf_version = "3.17.3"
compiler.cxxincludes += [
os.path.join(sdk['path'], 'common', 'protobuf-' + protobuf_version, 'src')
]
if compiler.like('msvc'):
compiler.defines += ['_ALLOW_KEYWORD_MACROS']
@@ -150,12 +136,6 @@ for sdk_target in SM.sdk_targets:
os.path.join(sdk['path'], 'public', 'game', 'shared', pb_gamedir_map[sdk['name']], 'protobuf', pb_gamesrcdir_map[sdk['name']] + '_gcmessages.pb.cc'),
os.path.join(sdk['path'], 'public', 'engine', 'protobuf', 'engine_gcmessages.pb.cc'),
]
if sdk['name'] == 'outbreak':
binary.sources += [
os.path.join(sdk['path'], 'public', 'engine', 'protobuf', 'network_connection.pb.cc'),
os.path.join(sdk['path'], 'public', 'game', 'shared', 'protobuf', 'base_usermessages.pb.cc'),
os.path.join(sdk['path'], 'public', 'game', 'shared', 'protobuf', 'base_usermessage_helpers.cpp'),
]
SM.binaries += builder.Add(project)
+11 -11
View File
@@ -76,18 +76,18 @@ void ConCmdManager::OnUnlinkConCommandBase(ConCommandBase *pBase, const char *na
if (!m_Cmds.retrieve(name, &pInfo))
return;
auto iter = pInfo->hooks.begin();
CmdHookList::iterator iter = pInfo->hooks.begin();
while (iter != pInfo->hooks.end())
{
CmdHook *hook = *iter;
IPluginContext *pContext = hook->pf->GetParentContext();
IPlugin *pPlugin = scripts->FindPluginByContext(pContext);
IPlugin *pPlugin = scripts->FindPluginByContext(pContext->GetContext());
// The list is guaranteed to exist.
PluginHookList *list;
pPlugin->GetProperty("CommandList", (void **)&list, false);
for (auto hiter = list->begin(); hiter != list->end(); hiter++)
for (PluginHookList::iterator hiter = list->begin(); hiter != list->end(); hiter++)
{
if (*hiter == hook)
{
@@ -112,7 +112,7 @@ void ConCmdManager::OnPluginDestroyed(IPlugin *plugin)
if (!plugin->GetProperty("CommandList", (void **)&pList, true))
return;
auto iter = pList->begin();
PluginHookList::iterator iter = pList->begin();
while (iter != pList->end())
{
CmdHook *hook = *iter;
@@ -163,7 +163,7 @@ ResultType ConCmdManager::DispatchClientCommand(int client, const char *cmd, int
}
cell_t result = type;
for (auto iter = pInfo->hooks.begin(); iter != pInfo->hooks.end(); iter++)
for (CmdHookList::iterator iter = pInfo->hooks.begin(); iter != pInfo->hooks.end(); iter++)
{
CmdHook *hook = *iter;
@@ -235,7 +235,7 @@ bool ConCmdManager::InternalDispatch(int client, const ICommandArgs *args)
: client;
int dedicatedClient = engine->IsDedicatedServer() ? 0 : g_Players.ListenClient();
for (auto iter = pInfo->hooks.begin(); iter != pInfo->hooks.end(); iter++)
for (CmdHookList::iterator iter = pInfo->hooks.begin(); iter != pInfo->hooks.end(); iter++)
{
CmdHook *hook = *iter;
@@ -398,7 +398,7 @@ void RegisterInPlugin(CmdHook *hook)
const char *orig = hook->info->pCmd->GetName();
/* Insert this into the help list, SORTED alphabetically. */
auto iter = pList->begin();
PluginHookList::iterator iter = pList->begin();
while (iter != pList->end())
{
const char *cmd = (*iter)->info->pCmd->GetName();
@@ -415,7 +415,7 @@ void RegisterInPlugin(CmdHook *hook)
void ConCmdManager::AddToCmdList(ConCmdInfo *info)
{
auto iter = m_CmdList.begin();
List<ConCmdInfo *>::iterator iter = m_CmdList.begin();
ConCmdInfo *pInfo;
bool inserted = false;
const char *orig = NULL;
@@ -451,7 +451,7 @@ void ConCmdManager::UpdateAdminCmdFlags(const char *cmd, OverrideType type, Flag
if (!m_Cmds.retrieve(cmd, &pInfo))
return;
for (auto iter = pInfo->hooks.begin(); iter != pInfo->hooks.end(); iter++)
for (CmdHookList::iterator iter = pInfo->hooks.begin(); iter != pInfo->hooks.end(); iter++)
{
if (!iter->admin)
continue;
@@ -471,7 +471,7 @@ void ConCmdManager::UpdateAdminCmdFlags(const char *cmd, OverrideType type, Flag
RefPtr<CommandGroup> group(r->value);
for (auto iter = group->hooks.begin(); iter != group->hooks.end(); iter++)
for (PluginHookList::iterator iter = group->hooks.begin(); iter != group->hooks.end(); iter++)
{
CmdHook *hook = *iter;
if (!remove)
@@ -613,7 +613,7 @@ void ConCmdManager::OnRootConsoleCommand(const char *cmdname, const ICommandArgs
const char *help;
UTIL_ConsolePrint("[SM] Listing commands for: %s", plname);
UTIL_ConsolePrint(" %-17.16s %-8.7s %s", "[Name]", "[Type]", "[Help]");
for (auto iter = pList->begin(); iter != pList->end(); iter++)
for (PluginHookList::iterator iter = pList->begin(); iter != pList->end(); iter++)
{
CmdHook *hook = *iter;
if (hook->type == CmdHook::Server)
+7 -5
View File
@@ -38,19 +38,21 @@
#include <am-inlinelist.h>
#include <am-refcounting.h>
#include <am-utility.h>
#include <sm_hashmap.h>
#include <sm_stringhashmap.h>
#include "sm_globals.h"
#include "sourcemm_api.h"
#include <IForwardSys.h>
#include <list>
#include <string>
#include <sh_list.h>
#include <sh_string.h>
#include <IRootConsoleMenu.h>
#include <IAdminSystem.h>
#include "concmd_cleaner.h"
#include "GameHooks.h"
#include <sm_namehashset.h>
using namespace SourceHook;
struct CmdHook;
struct ConCmdInfo;
@@ -135,7 +137,7 @@ struct ConCmdInfo
};
};
typedef std::list<ConCmdInfo *> ConCmdList;
typedef List<ConCmdInfo *> ConCmdList;
class ConCmdManager :
public SMGlobalClass,
@@ -178,7 +180,7 @@ private:
bool CheckAccess(int client, const char *cmd, AdminCmdInfo *pAdmin);
ConCmdInfo *FindInTrie(const char *name);
public:
inline const std::list<ConCmdInfo *> & GetCommandList()
inline const List<ConCmdInfo *> & GetCommandList()
{
return m_CmdList;
}
+16 -20
View File
@@ -30,7 +30,7 @@
#include "ConVarManager.h"
#include "HalfLife2.h"
#include "sm_stringutil.h"
#include <vector>
#include <sh_vector.h>
#include <sm_namehashset.h>
#include "logic_bridge.h"
#include "sourcemod.h"
@@ -40,7 +40,7 @@
ConVarManager g_ConVarManager;
const ParamType CONVARCHANGE_PARAMS[] = {Param_Cell, Param_String, Param_String};
typedef std::list<const ConVar *> ConVarList;
typedef List<const ConVar *> ConVarList;
NameHashSet<ConVarInfo *, ConVarInfo::ConVarPolicy> convar_cache;
enum {
@@ -114,7 +114,7 @@ void ConVarManager::OnSourceModAllInitialized()
void ConVarManager::OnSourceModShutdown()
{
auto iter = m_ConVars.begin();
List<ConVarInfo *>::iterator iter = m_ConVars.begin();
HandleSecurity sec(NULL, g_pCoreIdent);
/* Iterate list of ConVarInfo structures, remove every one of them */
@@ -217,7 +217,7 @@ void ConVarManager::OnPluginUnloaded(IPlugin *plugin)
}
/* Clear any references to this plugin as the convar creator */
for (auto iter = m_ConVars.begin(); iter != m_ConVars.end(); ++iter)
for (List<ConVarInfo *>::iterator iter = m_ConVars.begin(); iter != m_ConVars.end(); ++iter)
{
ConVarInfo *pInfo = (*iter);
@@ -230,7 +230,7 @@ void ConVarManager::OnPluginUnloaded(IPlugin *plugin)
const IPluginRuntime * pRuntime = plugin->GetRuntime();
/* Remove convar queries for this plugin that haven't returned results yet */
for (auto iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end();)
for (List<ConVarQuery>::iterator iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end();)
{
ConVarQuery &query = (*iter);
if (query.pCallback->GetParentRuntime() == pRuntime)
@@ -246,7 +246,7 @@ void ConVarManager::OnPluginUnloaded(IPlugin *plugin)
void ConVarManager::OnClientDisconnected(int client)
{
/* Remove convar queries for this client that haven't returned results yet */
for (auto iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end();)
for (List<ConVarQuery>::iterator iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end();)
{
ConVarQuery &query = (*iter);
if (query.client == client)
@@ -311,6 +311,7 @@ void ConVarManager::OnRootConsoleCommand(const char *cmdname, const ICommandArgs
const char *plname = IS_STR_FILLED(plinfo->name) ? plinfo->name : plugin->GetFilename();
ConVarList *pConVarList;
ConVarList::iterator iter;
/* If no convar list... */
if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
@@ -326,7 +327,7 @@ void ConVarManager::OnRootConsoleCommand(const char *cmdname, const ICommandArgs
}
/* Iterate convar list and display/reset each one */
for (auto iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
{
/*const */ConVar *pConVar = const_cast<ConVar *>(*iter);
if (!wantReset)
@@ -355,7 +356,7 @@ Handle_t ConVarManager::CreateConVar(IPluginContext *pContext, const char *name,
ConVarInfo *pInfo = NULL;
Handle_t hndl = 0;
IPlugin *plugin = scripts->FindPluginByContext(pContext);
IPlugin *plugin = scripts->FindPluginByContext(pContext->GetContext());
/* Find out if the convar exists already */
pConVar = icvar->FindVar(name);
@@ -588,6 +589,7 @@ QueryCvarCookie_t ConVarManager::QueryClientConVar(edict_t *pPlayer, const char
void ConVarManager::AddConVarToPluginList(IPlugin *plugin, const ConVar *pConVar)
{
ConVarList *pConVarList;
ConVarList::iterator iter;
bool inserted = false;
const char *orig = pConVar->GetName();
@@ -597,14 +599,14 @@ void ConVarManager::AddConVarToPluginList(IPlugin *plugin, const ConVar *pConVar
pConVarList = new ConVarList();
plugin->SetProperty("ConVarList", pConVarList);
}
else if (std::find(pConVarList->begin(), pConVarList->end(), pConVar) != pConVarList->end())
else if (pConVarList->find(pConVar) != pConVarList->end())
{
/* If convar is already in list, then don't add it */
return;
}
/* Insert convar into list which is sorted alphabetically */
for (auto iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
{
if (strcmp(orig, (*iter)->GetName()) < 0)
{
@@ -648,16 +650,10 @@ void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue, float
{
ConVarReentrancyGuard guard(pConVar);
/* Copy the new value to a local buffer so it survives reentrant
* ChangeStringValue calls that may delete[] + reallocate m_pszString
* while the forward is still iterating plugin callbacks. */
char newValue[512];
ke::SafeStrcpy(newValue, sizeof(newValue), pConVar->GetString());
/* Now call forwards in plugins that have hooked this */
pForward->PushCell(pInfo->handle);
pForward->PushString(oldValue);
pForward->PushString(newValue);
pForward->PushString(pConVar->GetString());
pForward->Execute(NULL);
}
}
@@ -676,9 +672,9 @@ void ConVarManager::OnClientQueryFinished(QueryCvarCookie_t cookie,
{
IPluginFunction *pCallback = NULL;
cell_t value = 0;
List<ConVarQuery>::iterator iter;
auto iter = m_ConVarQueries.begin();
for (; iter != m_ConVarQueries.end(); iter++)
for (iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end(); iter++)
{
ConVarQuery &query = (*iter);
if (query.cookie == cookie)
@@ -689,7 +685,7 @@ void ConVarManager::OnClientQueryFinished(QueryCvarCookie_t cookie,
}
}
if (pCallback && iter != m_ConVarQueries.end())
if (pCallback)
{
cell_t ret;
+7 -5
View File
@@ -34,7 +34,7 @@
#include "sm_globals.h"
#include "sourcemm_api.h"
#include <list>
#include <sh_list.h>
#include <IPluginSys.h>
#include <IForwardSys.h>
#include <IHandleSys.h>
@@ -43,7 +43,9 @@
#include <compat_wrappers.h>
#include "concmd_cleaner.h"
#include "PlayerManager.h"
#include <sm_hashmap.h>
#include <sm_stringhashmap.h>
using namespace SourceHook;
class IConVarChangeListener
{
@@ -61,7 +63,7 @@ struct ConVarInfo
IChangeableForward *pChangeForward; /**< Forward associated with convar */
ConVar *pVar; /**< The actual convar */
IPlugin *pPlugin; /**< Originally owning plugin */
std::list<IConVarChangeListener *> changeListeners;
List<IConVarChangeListener *> changeListeners;
struct ConVarPolicy
{
@@ -173,8 +175,8 @@ private:
static void AddConVarToPluginList(IPlugin *plugin, const ConVar *pConVar);
private:
HandleType_t m_ConVarType;
std::list<ConVarInfo *> m_ConVars;
std::list<ConVarQuery> m_ConVarQueries;
List<ConVarInfo *> m_ConVars;
List<ConVarQuery> m_ConVarQueries;
};
extern ConVarManager g_ConVarManager;
+3 -3
View File
@@ -76,7 +76,7 @@ class GenericCommandHooker : public IConCommandLinkListener
int hook;
unsigned int refcount;
};
std::vector<HackInfo> vtables;
CVector<HackInfo> vtables;
bool enabled;
SourceHook::MemFuncInfo dispatch;
@@ -144,7 +144,7 @@ class GenericCommandHooker : public IConCommandLinkListener
vtables[i].refcount = 0;
for (ConCommandBaseIterator iter; iter.IsValid(); iter.Next())
MakeHookable(iter.Get());
auto iter = vtables.begin();
CVector<HackInfo>::iterator iter = vtables.begin();
while (iter != vtables.end())
{
if ((*iter).refcount)
@@ -191,7 +191,7 @@ class GenericCommandHooker : public IConCommandLinkListener
if (vtables[index].refcount == 0)
{
SH_REMOVE_HOOK_ID(vtables[index].hook);
vtables.erase(vtables.begin() + index);
vtables.erase(vtables.iterAt(index));
}
}
+1 -1
View File
@@ -34,7 +34,7 @@
#include "sm_globals.h"
#include "sourcemm_api.h"
#include <IForwardSys.h>
#include <sm_hashmap.h>
#include <sm_stringhashmap.h>
namespace SourceMod {
class ICommandArgs;
+80 -328
View File
@@ -41,11 +41,13 @@
#include <sourcemod_version.h>
#include <amtl/os/am-path.h>
#include <amtl/os/am-fsutil.h>
#include <list>
#include <sh_list.h>
#include <IForwardSys.h>
#include <bridge/include/IScriptManager.h>
#include <bridge/include/ILogger.h>
using namespace SourceHook;
#ifdef PLATFORM_WINDOWS
ConVar sm_corecfgfile("sm_corecfgfile", "addons\\sourcemod\\configs\\core.cfg", 0, "SourceMod core configuration file");
#elif defined PLATFORM_LINUX || defined PLATFORM_APPLE
@@ -316,284 +318,6 @@ inline bool IsPathSepChar(char c)
#endif
}
void SM_ParseConfig(FILE *fp, ke::HashMap<std::string, std::string, StringPolicy> &cvars_list)
{
char line[4096];
char cvar_name[256];
while (fgets(line, sizeof(line), fp))
{
char *ptr = line;
// Ignore whitespaces and tabs
while (*ptr == ' ' || *ptr == '\t')
{
ptr++;
}
// Ignore empty lines if found
if (*ptr == '\0' || *ptr == '\n' || *ptr == '\r')
{
continue;
}
// Ignore comments
if (*ptr == '/' && *(ptr + 1) == '/')
{
continue;
}
size_t i = 0;
while (*ptr != '\0' && *ptr != '\n' && *ptr != '\r' && *ptr != ' ' && *ptr != '\t' && i < (sizeof(cvar_name) - 1))
{
cvar_name[i++] = *ptr++;
}
cvar_name[i] = '\0';
if (!i)
{
continue;
}
auto p = cvars_list.findForAdd(cvar_name);
if (p.found())
{
continue;
}
// Remove spaces and tabs before the value
while (*ptr == ' ' || *ptr == '\t')
{
ptr++;
}
char *value_start = ptr;
char *value_end = value_start + strlen(value_start);
while (value_end > value_start &&
(*(value_end - 1) == '\n' ||
*(value_end - 1) == '\r' ||
*(value_end - 1) == ' ' ||
*(value_end - 1) == '\t' ||
*(value_end - 1) == '"'))
{
value_end--;
}
*value_end = '\0';
if (*value_start == '"')
{
value_start++;
}
cvars_list.add(p, cvar_name, value_start);
}
}
inline bool SM_CvarExistsInConfig(ke::HashMap<std::string, std::string, StringPolicy> &cvars, const char *cvar_name)
{
return cvars.find(cvar_name).found();
}
bool SM_CvarExistsInPlugin(std::list<const ConVar *> &convars, const char *cvar_name)
{
for (auto iter = convars.begin(); iter != convars.end(); iter++)
{
const ConVar *cvar = (*iter);
#if SOURCE_ENGINE >= SE_ORANGEBOX
if (cvar->IsFlagSet(FCVAR_DONTRECORD))
#else
if (cvar->IsBitSet(FCVAR_DONTRECORD))
#endif
{
continue;
}
if (strcasecmp(cvar_name, cvar->GetName()) == 0)
{
return true;
}
}
return false;
}
bool SM_ConfigCheckRegeneration(
const char *file,
ke::HashMap<std::string, std::string, StringPolicy> &existing_cvars,
std::list<const ConVar *> &convars)
{
FILE *fp = fopen(file, "rt");
if (!fp)
{
logger->LogError("Failed to read config for checking regeneration, make sure the directory has read permission.");
return true;
}
SM_ParseConfig(fp, existing_cvars);
fclose(fp);
/* #1. Check if the plugin's cvar list has a cvar that doesn't exist in the config file. */
for (auto iter = convars.begin(); iter != convars.end(); iter++)
{
const ConVar *cvar = (*iter);
#if SOURCE_ENGINE >= SE_ORANGEBOX
if (cvar->IsFlagSet(FCVAR_DONTRECORD))
#else
if (cvar->IsBitSet(FCVAR_DONTRECORD))
#endif
{
continue;
}
if (!SM_CvarExistsInConfig(existing_cvars, cvar->GetName()))
{
return true;
}
}
/* #2. Check if the config file has a cvar that doesn't exist in the plugin's cvar list. */
for (auto it = existing_cvars.iter(); !it.empty(); it.next())
{
if (!SM_CvarExistsInPlugin(convars, it->key.c_str()))
{
return true;
}
}
return false;
}
inline void SM_ExecuteConfigFile(const char *file)
{
char cmd[255];
ke::SafeSprintf(cmd, sizeof(cmd), "exec %s\n", file);
engine->ServerCommand(cmd);
}
bool SM_GenerateConfigFile(
IPlugin *pl,
const char *file,
std::list<const ConVar *> &convars,
bool needs_regeneration = false,
ke::HashMap<std::string, std::string, StringPolicy> *existing_cvars = NULL)
{
FILE *fp = NULL;
char tmp_file[PLATFORM_MAX_PATH];
if (!needs_regeneration)
{
fp = fopen(file, "wt");
if (!fp)
{
logger->LogError("Failed to auto generate config for %s, make sure the directory has write permission.", pl->GetFilename());
return false;
}
}
else
{
/* Create a .tmp file with the new contents of the new config file and then override it to the existing file */
ke::path::Format(tmp_file, sizeof(tmp_file), "%s.tmp", file);
fp = fopen(tmp_file, "wt");
if (!fp)
{
logger->LogError("Failed to create temp config file for %s, make sure the directory has write permission.", pl->GetFilename());
return false;
}
}
fprintf(fp, "// This file was auto-generated by SourceMod (v%s)\n", SOURCEMOD_VERSION);
fprintf(fp, "// ConVars for plugin \"%s\"\n", pl->GetFilename());
fprintf(fp, "\n\n");
float x;
for (auto iter = convars.begin(); iter != convars.end(); iter++)
{
const ConVar *cvar = (*iter);
#if SOURCE_ENGINE >= SE_ORANGEBOX
if (cvar->IsFlagSet(FCVAR_DONTRECORD))
#else
if (cvar->IsBitSet(FCVAR_DONTRECORD))
#endif
{
continue;
}
char descr[255];
char *dptr = descr;
/* Print comments until there is no more */
ke::SafeStrcpy(descr, sizeof(descr), cvar->GetHelpText());
while (*dptr != '\0')
{
/* Find the next line */
char *next_ptr = dptr;
while (*next_ptr != '\0')
{
if (*next_ptr == '\n')
{
*next_ptr = '\0';
next_ptr++;
break;
}
next_ptr++;
}
fprintf(fp, "// %s\n", dptr);
dptr = next_ptr;
}
fprintf(fp, "// -\n");
fprintf(fp, "// Default: \"%s\"\n", cvar->GetDefault());
if (cvar->GetMin(x))
{
fprintf(fp, "// Minimum: \"%02f\"\n", x);
}
if (cvar->GetMax(x))
{
fprintf(fp, "// Maximum: \"%02f\"\n", x);
}
const char *value = cvar->GetDefault();
if (needs_regeneration && existing_cvars)
{
auto p = existing_cvars->find(cvar->GetName());
if (p.found())
{
value = p->value.c_str();
}
}
fprintf(fp, "%s \"%s\"\n", cvar->GetName(), value);
fprintf(fp, "\n");
}
fprintf(fp, "\n");
fclose(fp);
if (needs_regeneration)
{
#ifdef PLATFORM_WINDOWS
if (!MoveFileEx(tmp_file, file, MOVEFILE_REPLACE_EXISTING))
#else
if (rename(tmp_file, file) != 0)
#endif
{
/* Replacing the temp config file with the existing one failed, remove it and notify the user about it */
logger->LogError("Failed to replace temp config file for %s, make sure the directory has write permission.", pl->GetFilename());
if (remove(tmp_file) != 0)
{
logger->LogError("Failed to remove temp config file for %s.", pl->GetFilename());
}
return false;
}
}
return true;
}
bool SM_ExecuteConfig(IPlugin *pl, AutoConfig *cfg, bool can_create)
{
bool will_create = false;
@@ -670,62 +394,90 @@ bool SM_ExecuteConfig(IPlugin *pl, AutoConfig *cfg, bool can_create)
g_SourceMod.BuildPath(Path_Game, file, sizeof(file), "cfg/%s", local);
bool file_exists = ke::file::IsFile(file);
if (!will_create)
if (!file_exists && will_create)
{
if (file_exists)
List<const ConVar *> *convars = NULL;
if (pl->GetProperty("ConVarList", (void **)&convars, false) && convars)
{
SM_ExecuteConfigFile(local);
/* Attempt to create it */
FILE *fp = fopen(file, "wt");
if (fp)
{
fprintf(fp, "// This file was auto-generated by SourceMod (v%s)\n", SOURCEMOD_VERSION);
fprintf(fp, "// ConVars for plugin \"%s\"\n", pl->GetFilename());
fprintf(fp, "\n\n");
List<const ConVar *>::iterator iter;
float x;
for (iter = convars->begin(); iter != convars->end(); iter++)
{
const ConVar *cvar = (*iter);
#if SOURCE_ENGINE >= SE_ORANGEBOX
if (cvar->IsFlagSet(FCVAR_DONTRECORD))
#else
if (cvar->IsBitSet(FCVAR_DONTRECORD))
#endif
{
continue;
}
char descr[255];
char *dptr = descr;
/* Print comments until there is no more */
ke::SafeStrcpy(descr, sizeof(descr), cvar->GetHelpText());
while (*dptr != '\0')
{
/* Find the next line */
char *next_ptr = dptr;
while (*next_ptr != '\0')
{
if (*next_ptr == '\n')
{
*next_ptr = '\0';
next_ptr++;
break;
}
next_ptr++;
}
fprintf(fp, "// %s\n", dptr);
dptr = next_ptr;
}
fprintf(fp, "// -\n");
fprintf(fp, "// Default: \"%s\"\n", cvar->GetDefault());
if (cvar->GetMin(x))
{
fprintf(fp, "// Minimum: \"%02f\"\n", x);
}
if (cvar->GetMax(x))
{
fprintf(fp, "// Maximum: \"%02f\"\n", x);
}
fprintf(fp, "%s \"%s\"\n", cvar->GetName(), cvar->GetDefault());
fprintf(fp, "\n");
}
fprintf(fp, "\n");
file_exists = true;
can_create = false;
fclose(fp);
}
else
{
logger->LogError("Failed to auto generate config for %s, make sure the directory has write permission.", pl->GetFilename());
return can_create;
}
}
return can_create;
}
std::list<const ConVar *> *convars = NULL;
if (!pl->GetProperty("ConVarList", (void **)&convars, false) || !convars)
if (file_exists)
{
if (file_exists)
{
SM_ExecuteConfigFile(local);
}
return can_create;
char cmd[255];
ke::SafeSprintf(cmd, sizeof(cmd), "exec %s\n", local);
engine->ServerCommand(cmd);
}
if (!file_exists)
{
/* If file doesn't exist, then automatically generate the config file and execute it. */
/* If sourcemod somehow failed to generate the config file, then stop. */
if (!SM_GenerateConfigFile(pl, file, *convars))
{
return can_create;
}
SM_ExecuteConfigFile(local);
can_create = false;
return can_create;
}
/* Now if the file exists, read the content of it to see if we need to regenerate it or not. */
ke::HashMap<std::string, std::string, StringPolicy> existing_cvars;
existing_cvars.init();
if (!SM_ConfigCheckRegeneration(file, existing_cvars, *convars))
{
SM_ExecuteConfigFile(local);
return can_create;
}
/* File exists and misses cvars between the config file and the plugin's convars list
* Create a temporary config file with the new contents and then override it to the existing file.
* If sourcemod somehow failed to override the new contents to the existing config file, then execute the existing config file.
*/
can_create = false;
if (!SM_GenerateConfigFile(pl, file, *convars, true, &existing_cvars))
{
logger->LogError("An error occurred while regenerating config file for %s, executing the existing file instead.", pl->GetFilename());
}
SM_ExecuteConfigFile(local);
return can_create;
}
@@ -762,7 +514,7 @@ void SM_ConfigsExecuted_Plugin(unsigned int serial)
void SM_ExecuteForPlugin(IPluginContext *ctx)
{
SMPlugin *plugin = scripts->FindPluginByContext(ctx);
SMPlugin *plugin = scripts->FindPluginByContext(ctx->GetContext());
unsigned int num = plugin->GetConfigCount();
if (!num)
+1 -14
View File
@@ -36,7 +36,7 @@
#include <ITextParsers.h>
#include <IRootConsoleMenu.h>
#include <am-string.h>
#include <sm_hashmap.h>
#include <sm_stringhashmap.h>
using namespace SourceMod;
@@ -71,19 +71,6 @@ private:
StringHashMap<std::string> m_KeyValues;
};
struct StringPolicy
{
static inline uint32_t hash(const std::string &key)
{
std::string lower = ke::Lowercase(key.c_str());
return ke::FastHashCharSequence(lower.c_str(), lower.length());
}
static inline bool matches(const char *find, const std::string &key)
{
return strcasecmp(find, key.c_str()) == 0;
}
};
extern bool SM_AreConfigsExecuted();
extern void SM_ExecuteAllConfigs();
extern void SM_ExecuteForPlugin(IPluginContext *ctx);
+13 -10
View File
@@ -41,7 +41,7 @@ EventManager g_EventManager;
SH_DECL_HOOK2(IGameEventManager2, FireEvent, SH_NOATTRIB, 0, bool, IGameEvent *, bool);
const ParamType GAMEEVENT_PARAMS[] = {Param_Cell, Param_String, Param_Cell};
typedef std::list<EventHook *> EventHookList;
typedef List<EventHook *> EventHookList;
class EventForwardFilter : public IForwardFilter
{
@@ -64,10 +64,13 @@ EventManager::EventManager() : m_EventType(0)
EventManager::~EventManager()
{
/* Free memory used by EventInfo structs if any */
while (!m_FreeEvents.empty()) {
delete m_FreeEvents.top();
m_FreeEvents.pop();
CStack<EventInfo *>::iterator iter;
for (iter = m_FreeEvents.begin(); iter != m_FreeEvents.end(); iter++)
{
delete (*iter);
}
m_FreeEvents.popall();
}
void EventManager::OnSourceModAllInitialized()
@@ -181,7 +184,7 @@ EventHookError EventManager::HookEvent(const char *name, IPluginFunction *pFunct
if (!m_EventHooks.retrieve(name, &pHook))
{
EventHookList *pHookList;
IPlugin *plugin = scripts->FindPluginByContext(pFunction->GetParentContext());
IPlugin *plugin = scripts->FindPluginByContext(pFunction->GetParentContext()->GetContext());
/* Check plugin for an existing EventHook list */
if (!plugin->GetProperty("EventHooks", (void **)&pHookList))
@@ -294,7 +297,7 @@ EventHookError EventManager::UnhookEvent(const char *name, IPluginFunction *pFun
/* If reference count is now 0, free hook structure */
EventHookList *pHookList;
IPlugin *plugin = scripts->FindPluginByContext(pFunction->GetParentContext());
IPlugin *plugin = scripts->FindPluginByContext(pFunction->GetParentContext()->GetContext());
/* Get plugin's event hook list */
if (!plugin->GetProperty("EventHooks", (void**)&pHookList))
@@ -303,7 +306,7 @@ EventHookError EventManager::UnhookEvent(const char *name, IPluginFunction *pFun
}
/* Make sure the event was actually being hooked */
if (std::find(pHookList->begin(), pHookList->end(), pHook) == pHookList->end())
if (pHookList->find(pHook) == pHookList->end())
{
return EventHookErr_NotActive;
}
@@ -332,7 +335,7 @@ EventInfo *EventManager::CreateEvent(IPluginContext *pContext, const char *name,
{
pInfo = new EventInfo();
} else {
pInfo = m_FreeEvents.top();
pInfo = m_FreeEvents.front();
m_FreeEvents.pop();
}
@@ -461,7 +464,7 @@ bool EventManager::OnFireEvent_Post(IGameEvent *pEvent, bool bDontBroadcast)
RETURN_META_VALUE(MRES_IGNORED, false);
}
pHook = m_EventStack.top();
pHook = m_EventStack.front();
if (pHook != NULL)
{
@@ -472,7 +475,7 @@ bool EventManager::OnFireEvent_Post(IGameEvent *pEvent, bool bDontBroadcast)
if (pHook->postCopy)
{
info.bDontBroadcast = bDontBroadcast;
info.pEvent = m_EventCopies.top();
info.pEvent = m_EventCopies.front();
info.pOwner = NULL;
hndl = handlesys->CreateHandle(m_EventType, &info, NULL, g_pCoreIdent, NULL);
+7 -5
View File
@@ -35,14 +35,16 @@
#include "sm_globals.h"
#include "sourcemm_api.h"
#include <sm_namehashset.h>
#include <list>
#include <stack>
#include <sh_list.h>
#include <sh_stack.h>
#include <IHandleSys.h>
#include <IForwardSys.h>
#include <IPluginSys.h>
class IClient;
using namespace SourceHook;
struct EventInfo
{
EventInfo()
@@ -138,9 +140,9 @@ private: // IGameEventManager2 hooks
private:
HandleType_t m_EventType;
NameHashSet<EventHook *> m_EventHooks;
std::stack<EventInfo *> m_FreeEvents;
std::stack<EventHook *> m_EventStack;
std::stack<IGameEvent *> m_EventCopies;
CStack<EventInfo *> m_FreeEvents;
CStack<EventHook *> m_EventStack;
CStack<IGameEvent *> m_EventCopies;
};
extern EventManager g_EventManager;
+1 -1
View File
@@ -115,7 +115,7 @@ void GameHooks::OnQueryCvarValueFinished(QueryCvarCookie_t cookie, edict_t *pPla
const char *cvarName, const char *cvarValue){
int client = IndexOfEdict(pPlayer);
# if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
# if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
if (g_Players.HandleConVarQuery(cookie, client, result, cvarName, cvarValue))
return;
# endif
+2 -2
View File
@@ -34,7 +34,7 @@
#include <iserverplugin.h>
#include <amtl/am-refcounting.h>
#include <amtl/am-vector.h>
#include <functional>
#include <amtl/am-function.h>
class ConVar;
class CCommand;
@@ -63,7 +63,7 @@ class CommandHook : public ke::Refcounted<CommandHook>
{
public:
// return false to RETURN_META(MRES_IGNORED), or true to SUPERCEDE.
typedef std::function<bool(int, const ICommandArgs *)> Callback;
typedef ke::Function<bool(int, const ICommandArgs *)> Callback;
public:
CommandHook(ConCommand *cmd, const Callback &callback, bool post);
+35 -181
View File
@@ -49,12 +49,6 @@
#include <berimbau_usermessages.pb.h>
#elif SOURCE_ENGINE == SE_MCV
#include <vietnam_usermessages.pb.h>
#elif SOURCE_ENGINE == SE_OUTBREAK
#include <terror_usermessages.pb.h>
#endif
#if SOURCE_ENGINE == SE_TF2 || SOURCE_ENGINE == SE_DODS || SOURCE_ENGINE == SE_HL2DM || SOURCE_ENGINE == SE_CSS
#define SE_SDK2013_2025
#endif
typedef ICommandLine *(*FakeGetCommandLine)();
@@ -63,6 +57,7 @@ typedef ICommandLine *(*FakeGetCommandLine)();
#define VSTDLIB_NAME FORMAT_SOURCE_BIN_NAME("vstdlib")
CHalfLife2 g_HL2;
ConVar *sv_lan = NULL;
static void *g_EntList = NULL;
static void **g_pEntInfoList = NULL;
@@ -192,8 +187,7 @@ void CHalfLife2::InitLogicalEntData()
|| SOURCE_ENGINE == SE_BMS \
|| SOURCE_ENGINE == SE_BLADE \
|| SOURCE_ENGINE == SE_NUCLEARDAWN \
|| SOURCE_ENGINE == SE_PVKII \
|| SOURCE_ENGINE == SE_OUTBREAK
|| SOURCE_ENGINE == SE_PVKII
if (g_SMAPI->GetServerFactory(false)("VSERVERTOOLS003", nullptr))
{
@@ -241,9 +235,9 @@ void CHalfLife2::InitLogicalEntData()
return;
}
#ifdef KE_ARCH_X86
#ifdef PLATFORM_X86
g_EntList = *reinterpret_cast<void **>(addr + offset);
#elif defined KE_ARCH_X64
#elif defined PLATFORM_X64
int32_t varOffset = *reinterpret_cast<int32_t *>(addr + offset);
g_EntList = reinterpret_cast<void *>(addr + offset + sizeof(int32_t) + varOffset);
#endif
@@ -406,70 +400,7 @@ bool UTIL_FindDataMapInfo(datamap_t *pMap, const char *name, sm_datatable_info_t
pMap = pMap->baseMap;
}
return false;
}
template <typename Table, typename Info>
static bool UTIL_FindInTablePath(Table *pTable, const char *name, Info *info,
bool (*search)(Table *, const char *, Info *),
Table *(*descend)(const Info &))
{
unsigned int baseOffset = 0;
const char *component = name;
while (true)
{
const char *dot = strchr(component, '.');
size_t len = dot ? (size_t)(dot - component) : strlen(component);
char buffer[256];
if (len == 0 || len >= sizeof(buffer))
{
return false;
}
memcpy(buffer, component, len);
buffer[len] = '\0';
// Search the table for the prop
Info local;
if (!search(pTable, buffer, &local))
{
return false;
}
if (!dot)
{
info->prop = local.prop;
info->actual_offset = baseOffset + local.actual_offset;
return true;
}
// Handle nested properties
Table *pNext = descend(local);
if (!pNext)
{
return false;
}
baseOffset += local.actual_offset;
pTable = pNext;
component = dot + 1;
}
}
static bool UTIL_FindInSendTablePath(SendTable *pTable, const char *name, sm_sendprop_info_t *info)
{
return UTIL_FindInTablePath<SendTable, sm_sendprop_info_t>(pTable, name, info,
[](SendTable *t, const char *n, sm_sendprop_info_t *o) { return UTIL_FindInSendTable(t, n, o, 0); },
[](const sm_sendprop_info_t &i) -> SendTable * { return i.prop->GetDataTable(); });
}
static bool UTIL_FindDataMapInfoPath(datamap_t *pMap, const char *name, sm_datatable_info_t *info)
{
return UTIL_FindInTablePath<datamap_t, sm_datatable_info_t>(pMap, name, info,
[](datamap_t *m, const char *n, sm_datatable_info_t *o) { return UTIL_FindDataMapInfo(m, n, o); },
[](const sm_datatable_info_t &i) -> datamap_t * { return i.prop->td; });
return false;
}
ServerClass *CHalfLife2::FindServerClass(const char *classname)
@@ -490,11 +421,7 @@ ServerClass *CHalfLife2::FindEntityServerClass(CBaseEntity *pEntity)
return nullptr;
}
#if SOURCE_ENGINE == SE_OUTBREAK
return pNetwork->GetServerClassForModify();
#else
return pNetwork->GetServerClass();
#endif
}
DataTableInfo *CHalfLife2::_FindServerClass(const char *classname)
@@ -534,10 +461,6 @@ bool CHalfLife2::FindSendPropInfo(const char *classname, const char *offset, sm_
if (!pInfo->lookup.retrieve(offset, &temp))
{
bool found = UTIL_FindInSendTable(pInfo->sc->m_pTable, offset, &temp.info, 0);
if (!found && strchr(offset, '.'))
{
found = UTIL_FindInSendTablePath(pInfo->sc->m_pTable, offset, &temp.info);
}
temp.name = offset;
pInfo->lookup.insert(offset, temp);
@@ -590,10 +513,6 @@ bool CHalfLife2::FindDataMapInfo(datamap_t *pMap, const char *offset, sm_datatab
if (!cache->retrieve(offset, &temp))
{
bool found = UTIL_FindDataMapInfo(pMap, offset, &temp.info);
if (!found && strchr(offset, '.'))
{
found = UTIL_FindDataMapInfoPath(pMap, offset, &temp.info);
}
temp.name = offset;
cache->insert(offset, temp);
@@ -648,14 +567,9 @@ bool CHalfLife2::TextMsg(int client, int dest, const char *msg)
char buffer[253];
ke::SafeSprintf(buffer, sizeof(buffer), "%s\1\n", msg);
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_OUTBREAK
CUsrMsg_SayText *pMsg;
if ((pMsg = (CUsrMsg_SayText *)g_UserMsgs.StartProtobufMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
#else
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
CCSUsrMsg_SayText *pMsg;
if ((pMsg = (CCSUsrMsg_SayText *)g_UserMsgs.StartProtobufMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
#endif
{
return false;
}
@@ -680,14 +594,9 @@ bool CHalfLife2::TextMsg(int client, int dest, const char *msg)
}
}
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_OUTBREAK
CUsrMsg_TextMsg *pMsg;
if ((pMsg = (CUsrMsg_TextMsg *)g_UserMsgs.StartProtobufMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
#else
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
CCSUsrMsg_TextMsg *pMsg;
if ((pMsg = (CCSUsrMsg_TextMsg *)g_UserMsgs.StartProtobufMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
#endif
{
return false;
}
@@ -722,14 +631,9 @@ bool CHalfLife2::HintTextMsg(int client, const char *msg)
{
cell_t players[] = {client};
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_OUTBREAK
CUsrMsg_HintText *pMsg;
if ((pMsg = (CUsrMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
#else
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
CCSUsrMsg_HintText *pMsg;
if ((pMsg = (CCSUsrMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
#endif
{
return false;
}
@@ -757,14 +661,9 @@ bool CHalfLife2::HintTextMsg(int client, const char *msg)
bool CHalfLife2::HintTextMsg(cell_t *players, int count, const char *msg)
{
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_OUTBREAK
CUsrMsg_HintText *pMsg;
if ((pMsg = (CUsrMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
#else
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
CCSUsrMsg_HintText *pMsg;
if ((pMsg = (CCSUsrMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
#endif
{
return false;
}
@@ -797,14 +696,9 @@ bool CHalfLife2::ShowVGUIMenu(int client, const char *name, KeyValues *data, boo
int count = 0;
cell_t players[] = {client};
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_OUTBREAK
CUsrMsg_VGUIMenu *pMsg;
if ((pMsg = (CUsrMsg_VGUIMenu *)g_UserMsgs.StartProtobufMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
#else
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
CCSUsrMsg_VGUIMenu *pMsg;
if ((pMsg = (CCSUsrMsg_VGUIMenu *)g_UserMsgs.StartProtobufMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
#endif
{
return false;
}
@@ -827,17 +721,13 @@ bool CHalfLife2::ShowVGUIMenu(int client, const char *name, KeyValues *data, boo
SubKey = data->GetFirstSubKey();
}
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
pMsg->set_name(name);
pMsg->set_show(show);
while (SubKey)
{
#if SOURCE_ENGINE == SE_OUTBREAK
CUsrMsg_VGUIMenu_Subkey *key = pMsg->add_subkeys();
#else
CCSUsrMsg_VGUIMenu_Subkey *key = pMsg->add_subkeys();
#endif
key->set_name(SubKey->GetName());
key->set_str(SubKey->GetString());
SubKey = SubKey->GetNextKey();
@@ -867,7 +757,7 @@ void CHalfLife2::AddToFakeCliCmdQueue(int client, int userid, const char *cmd)
{
pFake = new DelayedFakeCliCmd;
} else {
pFake = m_FreeCmds.top();
pFake = m_FreeCmds.front();
m_FreeCmds.pop();
}
@@ -897,7 +787,7 @@ void CHalfLife2::ProcessFakeCliCmdQueue()
bool CHalfLife2::IsLANServer()
{
static ConVar *sv_lan = icvar->FindVar("sv_lan");
sv_lan = icvar->FindVar("sv_lan");
if (!sv_lan)
{
@@ -963,7 +853,7 @@ const ICommandArgs *CHalfLife2::PeekCommandStack()
return NULL;
}
return m_CommandStack.top().args;
return m_CommandStack.front().args;
}
void CHalfLife2::PopCommandStack()
@@ -974,9 +864,9 @@ void CHalfLife2::PopCommandStack()
const char *CHalfLife2::CurrentCommandName()
{
#if SOURCE_ENGINE >= SE_ORANGEBOX
return m_CommandStack.top().args->Arg(0);
return m_CommandStack.front().args->Arg(0);
#else
return m_CommandStack.top().cmd;
return m_CommandStack.front().cmd;
#endif
}
@@ -1089,7 +979,7 @@ cell_t CHalfLife2::EntityToReference(CBaseEntity *pEntity)
{
IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
CBaseHandle hndl = pUnknown->GetRefEHandle();
return (hndl.ToInt() | ENTREF_MASK);
return (hndl.ToInt() | (1<<31));
}
CBaseEntity *CHalfLife2::ReferenceToEntity(cell_t entRef)
@@ -1101,15 +991,11 @@ CBaseEntity *CHalfLife2::ReferenceToEntity(cell_t entRef)
CEntInfo *pInfo = NULL;
if (entRef & ENTREF_MASK)
if (entRef & (1<<31))
{
/* Proper ent reference */
int hndlValue = entRef & ~ENTREF_MASK;
#if defined(SE_SDK2013_2025)
auto hndl = CBaseHandle::UnsafeFromIndex(hndlValue);
#else
int hndlValue = entRef & ~(1<<31);
CBaseHandle hndl(hndlValue);
#endif
pInfo = LookupEntity(hndl.GetEntryIndex());
if (!pInfo || pInfo->m_SerialNumber != hndl.GetSerialNumber())
@@ -1209,19 +1095,15 @@ int CHalfLife2::ReferenceToIndex(cell_t entRef)
return INVALID_EHANDLE_INDEX;
}
if (entRef & ENTREF_MASK)
if (entRef & (1<<31))
{
/* Proper ent reference */
int hndlValue = entRef & ~ENTREF_MASK;
#if defined(SE_SDK2013_2025)
auto hndl = CBaseHandle::UnsafeFromIndex(hndlValue);
#else
int hndlValue = entRef & ~(1<<31);
CBaseHandle hndl(hndlValue);
#endif
CEntInfo *pInfo = LookupEntity(hndl.GetEntryIndex());
if (!pInfo || pInfo->m_SerialNumber != hndl.GetSerialNumber())
if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
{
return INVALID_EHANDLE_INDEX;
}
@@ -1260,14 +1142,14 @@ cell_t CHalfLife2::EntityToBCompatRef(CBaseEntity *pEntity)
IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
CBaseHandle hndl = pUnknown->GetRefEHandle();
if (!hndl.IsValid())
if (hndl == INVALID_EHANDLE_INDEX)
{
return INVALID_EHANDLE_INDEX;
}
if (hndl.GetEntryIndex() >= MAX_EDICTS)
{
return (hndl.ToInt() | ENTREF_MASK);
return (hndl.ToInt() | (1<<31));
}
else
{
@@ -1282,12 +1164,8 @@ cell_t CHalfLife2::ReferenceToBCompatRef(cell_t entRef)
return INVALID_EHANDLE_INDEX;
}
int hndlValue = entRef & ~ENTREF_MASK;
#if defined(SE_SDK2013_2025)
auto hndl = CBaseHandle::UnsafeFromIndex(hndlValue);
#else
int hndlValue = entRef & ~(1<<31);
CBaseHandle hndl(hndlValue);
#endif
if (hndl.GetEntryIndex() < MAX_EDICTS)
{
@@ -1416,15 +1294,15 @@ public:
void Purge()
{
if (!this->IsExternallyAllocated())
if (!IsExternallyAllocated())
{
if (this->m_pMemory)
if (m_pMemory)
{
UTLMEMORY_TRACK_FREE();
g_pMemAlloc->Free((void*)this->m_pMemory);
this->m_pMemory = 0;
g_pMemAlloc->Free((void*)m_pMemory);
m_pMemory = 0;
}
this->m_nAllocationCount = 0;
m_nAllocationCount = 0;
}
BaseClass::Purge();
}
@@ -1554,7 +1432,7 @@ bool CHalfLife2::IsMapValid(const char *map)
if (!map || !map[0])
return false;
return FindMap(map) != SMFindMapResult::NotFound;
return FindMap(map) == SMFindMapResult::Found;
}
#if SOURCE_ENGINE < SE_ORANGEBOX
@@ -1692,13 +1570,12 @@ uint64_t CHalfLife2::GetServerSteamId64() const
|| SOURCE_ENGINE == SE_EYE \
|| SOURCE_ENGINE == SE_HL2DM \
|| SOURCE_ENGINE == SE_INSURGENCY \
|| SOURCE_ENGINE == SE_DOI \
|| SOURCE_ENGINE == SE_DOI \
|| SOURCE_ENGINE == SE_SDK2013 \
|| SOURCE_ENGINE == SE_ALIENSWARM \
|| SOURCE_ENGINE == SE_TF2 \
|| SOURCE_ENGINE == SE_PVKII \
|| SOURCE_ENGINE == SE_MCV \
|| SOURCE_ENGINE == SE_OUTBREAK
|| SOURCE_ENGINE == SE_TF2 \
|| SOURCE_ENGINE == SE_PVKII \
|| SOURCE_ENGINE == SE_MCV
const CSteamID *sid = engine->GetGameServerSteamID();
if (sid)
{
@@ -1724,26 +1601,3 @@ uint64_t CHalfLife2::GetServerSteamId64() const
return 1ULL;
}
void CHalfLife2::RemoveDataTableCache(datamap_t *pMap)
{
if (pMap == nullptr)
{
m_Maps.clear();
return;
}
m_Maps.removeIfExists(pMap);
}
bool CHalfLife2::RemoveSendPropCache(const char *classname)
{
if (classname == nullptr)
{
m_Classes.clear();
return true;
}
return m_Classes.remove(classname);
}
+8 -10
View File
@@ -32,12 +32,13 @@
#ifndef _INCLUDE_SOURCEMOD_CHALFLIFE2_H_
#define _INCLUDE_SOURCEMOD_CHALFLIFE2_H_
#include <list>
#include <string>
#include <sh_list.h>
#include <sh_string.h>
#include <sh_tinyhash.h>
#include <am-utility.h>
#include <am-hashset.h>
#include <am-hashmap.h>
#include <sm_hashmap.h>
#include <sm_stringhashmap.h>
#include <sm_namehashset.h>
#include "sm_globals.h"
#include "sm_queue.h"
@@ -53,10 +54,9 @@ namespace SourceMod {
class ICommandArgs;
} // namespace SourceMod
using namespace SourceHook;
using namespace SourceMod;
static const int ENTREF_MASK = (1 << 31);
#define HUD_PRINTTALK 3
#define HUD_PRINTCENTER 4
@@ -151,7 +151,7 @@ typedef NameHashSet<DataMapCacheInfo> DataMapCache;
struct DelayedFakeCliCmd
{
std::string cmd;
String cmd;
int client;
int userid;
};
@@ -259,8 +259,6 @@ public: //IGameHelpers
string_t AllocPooledString(const char *pszValue);
bool GetServerSteam3Id(char *pszOut, size_t len) const override;
uint64_t GetServerSteamId64() const override;
void RemoveDataTableCache(datamap_t *pMap = nullptr);
bool RemoveSendPropCache(const char *classname = nullptr);
public:
void AddToFakeCliCmdQueue(int client, int userid, const char *cmd);
void ProcessFakeCliCmdQueue();
@@ -286,8 +284,8 @@ private:
int m_SayTextMsg;
int m_VGUIMenu;
Queue<DelayedFakeCliCmd *> m_CmdQueue;
std::stack<DelayedFakeCliCmd *> m_FreeCmds;
std::stack<CachedCommandInfo> m_CommandStack;
CStack<DelayedFakeCliCmd *> m_FreeCmds;
CStack<CachedCommandInfo> m_CommandStack;
Queue<DelayedKickInfo> m_DelayedKicks;
void *m_pGetCommandLine;
#if SOURCE_ENGINE == SE_CSGO
+5 -4
View File
@@ -33,13 +33,14 @@
#define _INCLUDE_SOURCEMOD_MENUMANAGER_H_
#include <IMenuManager.h>
#include <vector>
#include <stack>
#include <list>
#include <sh_vector.h>
#include <sh_stack.h>
#include <sh_list.h>
#include "sm_globals.h"
#include <string>
using namespace SourceMod;
using namespace SourceHook;
class MenuManager :
public IMenuManager,
@@ -101,7 +102,7 @@ protected:
private:
int m_ShowMenu;
IMenuStyle *m_pDefaultStyle;
std::vector<IMenuStyle *> m_Styles;
CVector<IMenuStyle *> m_Styles;
HandleType_t m_StyleType;
HandleType_t m_MenuType;
std::string m_SelectSound = "";
+73 -22
View File
@@ -8,7 +8,7 @@
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
@@ -97,12 +97,9 @@ void BaseMenuStyle::_CancelClientMenu(int client, MenuCancelReason reason, bool
RemoveClientFromWatch(client);
}
Handle_t hndl = menu ? menu->GetHandle() : BAD_HANDLE;
AutoHandleRooter ahr(hndl);
/* Fire callbacks */
mh->OnMenuCancel(menu, client, reason);
/* Only fire end if there's a valid menu */
if (menu)
{
@@ -217,7 +214,7 @@ void BaseMenuStyle::ProcessWatchList()
}
#if defined MENU_DEBUG
logger->LogMessage("BaseMenuStyle::ProcessWatchList(%d,%d,%d,%d,%d,%p)",
logger->LogMessage("BaseMenuStyle::ProcessWatchList(%d,%d,%d,%d,%d,%p)",
m_WatchList.m_Size,
m_WatchList.m_FirstLink,
m_WatchList.m_FreeNodes,
@@ -305,7 +302,7 @@ void BaseMenuStyle::ClientPressedKey(int client, unsigned int key_press)
ItemSelection type = states.slots[key_press].type;
/* Check if we should play a sound about the type */
if (g_Menus.MenuSoundsEnabled() &&
if (g_Menus.MenuSoundsEnabled() &&
(!menu || (menu->GetMenuOptionFlags() & MENUFLAG_NO_SOUND) != MENUFLAG_NO_SOUND))
{
CellRecipientFilter filter;
@@ -326,21 +323,21 @@ void BaseMenuStyle::ClientPressedKey(int client, unsigned int key_press)
if (pCollideable)
{
const Vector & pos = pCollideable->GetCollisionOrigin();
enginesound->EmitSound(filter,
client,
CHAN_AUTO,
enginesound->EmitSound(filter,
client,
CHAN_AUTO,
#if SOURCE_ENGINE >= SE_PORTAL2
sound->c_str(),
-1,
-1,
#endif
sound->c_str(),
VOL_NORM,
ATTN_NORM,
VOL_NORM,
ATTN_NORM,
#if SOURCE_ENGINE >= SE_PORTAL2
0,
0,
#endif
0,
PITCH_NORM,
0,
PITCH_NORM,
#if SOURCE_ENGINE == SE_CSS || SOURCE_ENGINE == SE_HL2DM || SOURCE_ENGINE == SE_DODS \
|| SOURCE_ENGINE == SE_SDK2013 || SOURCE_ENGINE == SE_BMS || SOURCE_ENGINE == SE_TF2 || SOURCE_ENGINE == SE_PVKII
0,
@@ -422,7 +419,7 @@ bool BaseMenuStyle::DoClientMenu(int client, IMenuPanel *menu, IMenuHandler *mh,
time);
#endif
CPlayer *pPlayer = g_Players.GetPlayerByIndex(client);
if (!pPlayer || !pPlayer->IsInGame())
if (!pPlayer || pPlayer->IsFakeClient() || !pPlayer->IsInGame())
{
return false;
}
@@ -579,8 +576,6 @@ bool BaseMenuStyle::RedoClientMenu(int client, ItemOrder order)
CBaseMenuPlayer *player = GetMenuPlayer(client);
menu_states_t &states = player->states;
AutoHandleRooter ahr(states.menu ? states.menu->GetHandle() : BAD_HANDLE);
player->bAutoIgnore = true;
IMenuPanel *display = g_Menus.RenderMenu(client, states, order);
if (!display)
@@ -609,9 +604,9 @@ bool BaseMenuStyle::RedoClientMenu(int client, ItemOrder order)
return true;
}
CBaseMenu::CBaseMenu(IMenuHandler *pHandler, IMenuStyle *pStyle, IdentityToken_t *pOwner) :
m_pStyle(pStyle), m_Pagination(7), m_bShouldDelete(false), m_bCancelling(false),
m_pOwner(pOwner ? pOwner : g_pCoreIdent), m_bDeleting(false), m_bWillFreeHandle(false),
CBaseMenu::CBaseMenu(IMenuHandler *pHandler, IMenuStyle *pStyle, IdentityToken_t *pOwner) :
m_pStyle(pStyle), m_Pagination(7), m_bShouldDelete(false), m_bCancelling(false),
m_pOwner(pOwner ? pOwner : g_pCoreIdent), m_bDeleting(false), m_bWillFreeHandle(false),
m_hHandle(BAD_HANDLE), m_pHandler(pHandler), m_nFlags(MENUFLAG_BUTTON_EXIT)
{
}
@@ -759,6 +754,62 @@ unsigned int CBaseMenu::GetRealItemIndex(int client, unsigned int position)
return position;
}
void CBaseMenu::ShufflePerClient(int start, int stop)
{
// limit map len to 255 items since it's using uint8
int length = MIN(GetItemCount(), 255);
if (stop >= 0)
length = MIN(length, stop);
for (int i = 1; i < SM_MAXPLAYERS + 1; i++)
{
// populate per-client map ...
m_RandomMaps[i].resize(length);
for (int j = 0; j < length; j++)
m_RandomMaps[i][j] = j;
// ... and random shuffle it
for (int j = length - 1; j > start; j--)
{
int x = rand() % (j - start + 1) + start;
uint8_t tmp = m_RandomMaps[i][x];
m_RandomMaps[i][x] = m_RandomMaps[i][j];
m_RandomMaps[i][j] = tmp;
}
}
}
void CBaseMenu::SetClientMapping(int client, int *array, int length)
{
length = MIN(length, 255);
m_RandomMaps[client].resize(length);
for (int i = 0; i < length; i++)
{
m_RandomMaps[client][i] = array[i];
}
}
bool CBaseMenu::IsPerClientShuffled()
{
for (int i = 1; i < SM_MAXPLAYERS + 1; i++)
{
if(m_RandomMaps[i].length() > 0)
return true;
}
return false;
}
unsigned int CBaseMenu::GetRealItemIndex(int client, unsigned int position)
{
if (client > 0 && position < m_RandomMaps[client].length())
{
position = m_RandomMaps[client][position];
return m_items[position].index;
}
return position;
}
unsigned int CBaseMenu::GetItemCount()
{
return m_items.size();
+6 -6
View File
@@ -8,7 +8,7 @@
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
@@ -98,7 +98,7 @@ public:
class CBaseMenu;
class BaseMenuStyle :
class BaseMenuStyle :
public IMenuStyle,
public IClientListener
{
@@ -113,11 +113,11 @@ public: //IClientListener
public: //what derived must implement
virtual CBaseMenuPlayer *GetMenuPlayer(int client) =0;
virtual void SendDisplay(int client, IMenuPanel *display) =0;
public: //what derived may implement
virtual bool DoClientMenu(int client,
CBaseMenu *menu,
public: //what derived may implement
virtual bool DoClientMenu(int client,
CBaseMenu *menu,
unsigned int first_item,
IMenuHandler *mh,
IMenuHandler *mh,
unsigned int time);
virtual bool DoClientMenu(int client, IMenuPanel *menu, IMenuHandler *mh, unsigned int time);
virtual void AddClientToWatch(int client);
+4 -12
View File
@@ -49,8 +49,6 @@
#include <game/shared/berimbau/protobuf/berimbau_usermessages.pb.h>
#elif SOURCE_ENGINE == SE_MCV
#include <game/shared/vietnam/protobuf/vietnam_usermessages.pb.h>
#elif SOURCE_ENGINE == SE_OUTBREAK
#include <game/shared/protobuf/base_usermessages.pb.h>
#endif
extern const char *g_RadioNumTable[];
@@ -146,7 +144,7 @@ void CRadioStyle::OnSourceModShutdown()
while (!m_FreeDisplays.empty())
{
delete m_FreeDisplays.top();
delete m_FreeDisplays.front();
m_FreeDisplays.pop();
}
}
@@ -188,8 +186,6 @@ void CRadioStyle::OnUserMessage(int msg_id, bf_write *bf, IRecipientFilter *pFil
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
int c = ((CCSUsrMsg_ShowMenu &)msg).display_time();
#elif SOURCE_ENGINE == SE_OUTBREAK
int c = ((CUsrMsg_ShowMenu &)msg).display_time();
#else
bf_read br(bf->GetBasePointer(), 3);
@@ -265,7 +261,7 @@ CRadioDisplay *CRadioStyle::MakeRadioDisplay(CRadioMenu *menu)
}
else
{
display = m_FreeDisplays.top();
display = m_FreeDisplays.front();
m_FreeDisplays.pop();
display->Reset();
}
@@ -506,13 +502,9 @@ void CRadioMenuPlayer::Radio_Refresh()
time = menuHoldTime - (unsigned int)(gpGlobals->curtime - menuStartTime);
}
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
// TODO: find what happens past 240 on CS:GO
#if SOURCE_ENGINE == SE_OUTBREAK
CUsrMsg_ShowMenu *msg = (CUsrMsg_ShowMenu *)g_UserMsgs.StartProtobufMessage(g_ShowMenuId, players, 1, USERMSG_BLOCKHOOKS);
#else
CCSUsrMsg_ShowMenu *msg = (CCSUsrMsg_ShowMenu *)g_UserMsgs.StartProtobufMessage(g_ShowMenuId, players, 1, USERMSG_BLOCKHOOKS);
#endif
CCSUsrMsg_ShowMenu *msg = (CCSUsrMsg_ShowMenu *)g_UserMsgs.StartProtobufMessage(g_ShowMenuId, players, 1, USERMSG_BLOCKHOOKS);
if (!msg)
{
return;
+5 -5
View File
@@ -39,8 +39,8 @@
#include <IPlayerHelpers.h>
#include "UserMessages.h"
#include "sm_fastlink.h"
#include <stack>
#include <string>
#include <sh_stack.h>
#include <sh_string.h>
#include <compat_wrappers.h>
#include "logic/common_logic.h"
#include "AutoHandleRooter.h"
@@ -106,7 +106,7 @@ public:
CRadioMenuPlayer *GetRadioMenuPlayer(int client);
private:
CRadioMenuPlayer *m_players;
std::stack<CRadioDisplay *> m_FreeDisplays;
CStack<CRadioDisplay *> m_FreeDisplays;
};
class CRadioDisplay : public IMenuPanel
@@ -133,8 +133,8 @@ public: //IMenuPanel
unsigned int GetApproxMemUsage();
bool DirectSet(const char *str);
private:
std::string m_BufferText;
std::string m_Title;
String m_BufferText;
String m_Title;
unsigned int m_NextPos;
int keys;
};
+1 -1
View File
@@ -40,7 +40,7 @@ SH_DECL_HOOK4_void(IServerPluginHelpers, CreateMessage, SH_NOATTRIB, false, edic
ValveMenuStyle g_ValveMenuStyle;
extern const char *g_OptionNumTable[];
extern const char *g_OptionCmdTable[];
SourceHook::CallClass<IServerPluginHelpers> *g_pSPHCC = NULL;
CallClass<IServerPluginHelpers> *g_pSPHCC = NULL;
ValveMenuStyle::ValveMenuStyle() : m_players(new CValveMenuPlayer[256+1])
{
+2 -26
View File
@@ -41,7 +41,6 @@
#include <const.h>
#include <ITranslator.h>
#include "logic_bridge.h"
#include "AutoHandleRooter.h"
float g_next_vote = 0.0f;
@@ -172,12 +171,6 @@ void VoteMenuHandler::OnClientDisconnected(int client)
assert((unsigned)item < m_Items);
assert(m_Votes[item] > 0);
m_Votes[item]--;
if (sm_vote_hintbox.GetBool())
{
BuildVoteLeaders();
DrawHintProgress();
}
}
m_ClientVotes[client] = VOTE_NOT_VOTING;
}
@@ -280,12 +273,6 @@ bool VoteMenuHandler::RedrawToClient(int client, bool revotes)
m_ClientVotes[client] = VOTE_PENDING;
m_Revoting[client] = true;
m_NumVotes--;
if (sm_vote_hintbox.GetBool())
{
BuildVoteLeaders();
DrawHintProgress();
}
}
if (m_nMenuTime == MENU_TIME_FOREVER)
@@ -364,14 +351,7 @@ void VoteMenuHandler::StartVoting()
m_bStarted = true;
IBaseMenu *menu = m_pCurMenu;
AutoHandleRooter ahr(menu->GetHandle());
m_pHandler->OnMenuVoteStart(menu);
if (!m_bStarted)
{
return;
}
m_pHandler->OnMenuVoteStart(m_pCurMenu);
m_displayTimer = g_Timers.CreateTimer(this, 1.0, NULL, TIMER_FLAG_REPEAT|TIMER_FLAG_NO_MAPCHANGE);
@@ -434,7 +414,6 @@ void VoteMenuHandler::EndVoting()
IBaseMenu *menu = m_pCurMenu;
IMenuHandler *handler = m_pHandler;
InternalReset();
AutoHandleRooter ahr(menu ? menu->GetHandle() : BAD_HANDLE);
handler->OnMenuVoteCancel(menu, VoteCancel_Generic);
handler->OnMenuEnd(menu, MenuEnd_VotingCancelled);
return;
@@ -464,7 +443,6 @@ void VoteMenuHandler::EndVoting()
IBaseMenu *menu = m_pCurMenu;
IMenuHandler *handler = m_pHandler;
InternalReset();
AutoHandleRooter ahr(menu ? menu->GetHandle() : BAD_HANDLE);
handler->OnMenuVoteCancel(menu, VoteCancel_NoVotes);
handler->OnMenuEnd(menu, MenuEnd_VotingCancelled);
return;
@@ -496,7 +474,6 @@ void VoteMenuHandler::EndVoting()
InternalReset();
/* Send vote info */
AutoHandleRooter ahr(menu ? menu->GetHandle() : BAD_HANDLE);
handler->OnMenuVoteResults(menu, &vote);
handler->OnMenuEnd(menu, MenuEnd_VotingDone);
}
@@ -584,7 +561,7 @@ void VoteMenuHandler::OnMenuSelect(IBaseMenu *menu, int client, unsigned int ite
if (sm_vote_client_console.GetBool())
{
ClientConsolePrint(pPlayer->GetEdict(), "%s", buffer);
ClientConsolePrint(pPlayer->GetEdict(), buffer);
}
}
}
@@ -673,7 +650,6 @@ void VoteMenuHandler::BuildVoteLeaders()
{
if (m_NumVotes == 0 || !sm_vote_hintbox.GetBool())
{
m_leaderList[0] = '\0';
return;
}
+3 -2
View File
@@ -34,10 +34,11 @@
#include <IMenuManager.h>
#include <IPlayerHelpers.h>
#include <vector>
#include <sh_vector.h>
#include "sm_globals.h"
#include <TimerSys.h>
using namespace SourceHook;
using namespace SourceMod;
class VoteMenuHandler :
@@ -96,7 +97,7 @@ private:
unsigned int m_Clients;
unsigned int m_TotalClients;
unsigned int m_Items;
std::vector<unsigned int> m_Votes;
CVector<unsigned int> m_Votes;
IBaseMenu *m_pCurMenu;
bool m_bStarted;
bool m_bCancelled;
+4 -3
View File
@@ -82,7 +82,8 @@ void NextMapManager::OnSourceModShutdown()
SH_REMOVE_HOOK(ConCommand, Dispatch, changeLevelCmd, SH_STATIC(CmdChangeLevelCallback), false);
}
auto iter = m_mapHistory.begin();
SourceHook::List<MapChangeData *>::iterator iter;
iter = m_mapHistory.begin();
while (iter != m_mapHistory.end())
{
@@ -185,7 +186,7 @@ void NextMapManager::OnSourceModLevelChange( const char *mapName )
historydiff = (m_mapHistory.size() * -1);
}
for (auto iter = m_mapHistory.begin(); historydiff++ < 0; iter = m_mapHistory.erase(iter))
for (SourceHook::List<MapChangeData *>::iterator iter = m_mapHistory.begin(); historydiff++ < 0; iter = m_mapHistory.erase(iter))
{
delete (MapChangeData *)*iter;
}
@@ -212,7 +213,7 @@ void NextMapManager::ForceChangeLevel( const char *mapName, const char* changeRe
NextMapManager::NextMapManager()
{
m_tempChangeInfo = MapChangeData();
m_mapHistory = std::list<MapChangeData *>();
m_mapHistory = SourceHook::List<MapChangeData *>();
}
#if SOURCE_ENGINE >= SE_ORANGEBOX
+2 -2
View File
@@ -34,7 +34,7 @@
#include "sm_globals.h"
#include <eiface.h>
#include <list>
#include "sh_list.h"
#include "sm_stringutil.h"
#include <amtl/am-string.h>
@@ -92,7 +92,7 @@ public:
#endif
public:
std::list<MapChangeData *> m_mapHistory;
SourceHook::List<MapChangeData *> m_mapHistory;
private:
MapChangeData m_tempChangeInfo;
+83 -98
View File
@@ -46,7 +46,6 @@
#include <iserver.h>
#include <IGameConfigs.h>
#include "ConsoleDetours.h"
#include "frame_hooks.h"
#include "logic_bridge.h"
#include <sourcemod_version.h>
#include "smn_keyvalues.h"
@@ -65,7 +64,7 @@ IForward *ServerExitHibernation = NULL;
const unsigned int *g_NumPlayersToAuth = NULL;
int lifestate_offset = -1;
std::list<ICommandTargetProcessor *> target_processors;
List<ICommandTargetProcessor *> target_processors;
ConVar sm_debug_connect("sm_debug_connect", "1", 0, "Log Debug information about potential connection issues.");
@@ -79,16 +78,6 @@ SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *)
#endif
SH_DECL_HOOK1_void(IServerGameClients, ClientSettingsChanged, SH_NOATTRIB, 0, edict_t *);
// mock lacks NetworkIDValidated; episode1/darkm (< SE_ORANGEBOX) predate it.
#if SOURCE_ENGINE >= SE_ORANGEBOX && SOURCE_ENGINE != SE_MOCK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
SH_DECL_HOOK3_void(IServerGameClients, NetworkIDValidated, SH_NOATTRIB, 0, const char *, const char *, CSteamID);
#else
SH_DECL_HOOK2_void(IServerGameClients, NetworkIDValidated, SH_NOATTRIB, 0, const char *, const char *);
#endif
#define SM_HAS_NETWORKID_VALIDATED 1
#endif
#if SOURCE_ENGINE >= SE_EYE
SH_DECL_HOOK2_void(IServerGameClients, ClientCommandKeyValues, SH_NOATTRIB, 0, edict_t *, KeyValues *);
#endif
@@ -186,9 +175,6 @@ void PlayerManager::OnSourceModAllInitialized()
SH_ADD_HOOK(IServerGameClients, ClientCommandKeyValues, serverClients, SH_MEMBER(this, &PlayerManager::OnClientCommandKeyValues_Post), true);
#endif
SH_ADD_HOOK(IServerGameClients, ClientSettingsChanged, serverClients, SH_MEMBER(this, &PlayerManager::OnClientSettingsChanged), true);
#if defined SM_HAS_NETWORKID_VALIDATED
SH_ADD_HOOK(IServerGameClients, NetworkIDValidated, serverClients, SH_MEMBER(this, &PlayerManager::OnNetworkIDValidated), true);
#endif
SH_ADD_HOOK(IServerGameDLL, ServerActivate, gamedll, SH_MEMBER(this, &PlayerManager::OnServerActivate), true);
#if SOURCE_ENGINE >= SE_LEFT4DEAD
SH_ADD_HOOK(IServerGameDLL, ServerHibernationUpdate, gamedll, SH_MEMBER(this, &PlayerManager::OnServerHibernationUpdate), true);
@@ -231,6 +217,9 @@ void PlayerManager::OnSourceModAllInitialized()
SH_ADD_HOOK(ConCommand, Dispatch, pCmd, SH_STATIC(CmdMaxplayersCallback), true);
maxplayersCmd = pCmd;
}
gameevents->AddListener(this, "player_connect", true);
gameevents->AddListener(this, "player_disconnect", true);
}
void PlayerManager::OnSourceModShutdown()
@@ -246,9 +235,6 @@ void PlayerManager::OnSourceModShutdown()
SH_REMOVE_HOOK(IServerGameClients, ClientCommandKeyValues, serverClients, SH_MEMBER(this, &PlayerManager::OnClientCommandKeyValues_Post), true);
#endif
SH_REMOVE_HOOK(IServerGameClients, ClientSettingsChanged, serverClients, SH_MEMBER(this, &PlayerManager::OnClientSettingsChanged), true);
#if defined SM_HAS_NETWORKID_VALIDATED
SH_REMOVE_HOOK(IServerGameClients, NetworkIDValidated, serverClients, SH_MEMBER(this, &PlayerManager::OnNetworkIDValidated), true);
#endif
SH_REMOVE_HOOK(IServerGameDLL, ServerActivate, gamedll, SH_MEMBER(this, &PlayerManager::OnServerActivate), true);
#if SOURCE_ENGINE >= SE_LEFT4DEAD
SH_REMOVE_HOOK(IServerGameDLL, ServerHibernationUpdate, gamedll, SH_MEMBER(this, &PlayerManager::OnServerHibernationUpdate), true);
@@ -284,6 +270,8 @@ void PlayerManager::OnSourceModShutdown()
{
SH_REMOVE_HOOK(ConCommand, Dispatch, maxplayersCmd, SH_STATIC(CmdMaxplayersCallback), true);
}
gameevents->RemoveListener(this);
}
ConfigResult PlayerManager::OnSourceModConfigChanged(const char *key,
@@ -348,7 +336,8 @@ void PlayerManager::OnServerActivate(edict_t *pEdictList, int edictCount, int cl
m_onActivate->Execute(NULL);
m_onActivate2->Execute(NULL);
for (auto iter = m_hooks.begin(); iter != m_hooks.end(); iter++)
List<IClientListener *>::iterator iter;
for (iter = m_hooks.begin(); iter != m_hooks.end(); iter++)
{
if ((*iter)->GetClientListenerVersion() >= 5)
{
@@ -450,8 +439,9 @@ void PlayerManager::RunAuthChecks()
const char *steamId = pPlayer->GetSteam2Id();
/* Send to extensions */
List<IClientListener *>::iterator iter;
IClientListener *pListener;
for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{
pListener = (*iter);
pListener->OnClientAuthorized(client, steamId ? steamId : authstr);
@@ -507,17 +497,6 @@ void PlayerManager::RunAuthChecks()
}
}
#if defined SM_HAS_NETWORKID_VALIDATED
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
void PlayerManager::OnNetworkIDValidated(const char *pszUserName, const char *pszNetworkID, CSteamID steamID)
#else
void PlayerManager::OnNetworkIDValidated(const char *pszUserName, const char *pszNetworkID)
#endif
{
g_PendingAuthCheck = true;
}
#endif
bool PlayerManager::OnClientConnect(edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen)
{
int client = IndexOfEdict(pEntity);
@@ -546,7 +525,7 @@ bool PlayerManager::OnClientConnect(edict_t *pEntity, const char *pszName, const
/* Get the client's language */
if (m_QueryLang)
{
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
pPlayer->m_LangId = translator->GetServerLanguage();
#else
const char *name;
@@ -563,8 +542,9 @@ bool PlayerManager::OnClientConnect(edict_t *pEntity, const char *pszName, const
pPlayer->m_OriginalLangId = pPlayer->m_LangId;
}
List<IClientListener *>::iterator iter;
IClientListener *pListener = NULL;
for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{
pListener = (*iter);
if (!pListener->InterceptClientConnect(client, reject, maxrejectlen))
@@ -587,11 +567,7 @@ bool PlayerManager::OnClientConnect(edict_t *pEntity, const char *pszName, const
m_AuthQueue[++m_AuthQueue[0]] = client;
}
int userid = engine->GetPlayerUserId(pEntity);
if (userid >= 0 && userid <= USHRT_MAX)
{
m_UserIdLookUp[userid] = client;
}
m_UserIdLookUp[engine->GetPlayerUserId(pEntity)] = client;
}
else
{
@@ -612,8 +588,9 @@ bool PlayerManager::OnClientConnect_Post(edict_t *pEntity, const char *pszName,
if (orig_value)
{
List<IClientListener *>::iterator iter;
IClientListener *pListener = NULL;
for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{
pListener = (*iter);
pListener->OnClientConnected(client);
@@ -703,7 +680,7 @@ void PlayerManager::OnClientPutInServer(edict_t *pEntity, const char *playername
&& ((!m_bIsReplayActive && newCount == 1)
|| (m_bIsReplayActive && newCount == 2))
&& (m_SourceTVUserId == userId
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_MCV
// It seems likely that MCV will change this at some point, but it's GOTV at the moment.
|| strcmp(playername, "GOTV") == 0
#elif SOURCE_ENGINE == SE_BLADE
@@ -726,8 +703,9 @@ void PlayerManager::OnClientPutInServer(edict_t *pEntity, const char *playername
/* :TODO: kick the bot if it's rejected */
return;
}
List<IClientListener *>::iterator iter;
IClientListener *pListener = NULL;
for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{
pListener = (*iter);
pListener->OnClientConnected(client);
@@ -747,7 +725,7 @@ void PlayerManager::OnClientPutInServer(edict_t *pEntity, const char *playername
const char *steamId = pPlayer->GetSteam2Id();
/* Now do authorization */
for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{
pListener = (*iter);
pListener->OnClientAuthorized(client, steamId ? steamId : pPlayer->m_AuthID.c_str());
@@ -762,7 +740,7 @@ void PlayerManager::OnClientPutInServer(edict_t *pEntity, const char *playername
}
pPlayer->Authorize_Post();
}
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
else if(m_QueryLang)
{
// Not a bot
@@ -778,8 +756,9 @@ void PlayerManager::OnClientPutInServer(edict_t *pEntity, const char *playername
pPlayer->Connect();
m_PlayerCount++;
List<IClientListener *>::iterator iter;
IClientListener *pListener = NULL;
for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{
pListener = (*iter);
pListener->OnClientPutInServer(client);
@@ -826,8 +805,7 @@ void PlayerManager::OnServerHibernationUpdate(bool bHibernating)
CPlayer *pPlayer = &m_Players[i];
if (pPlayer->IsConnected() && pPlayer->IsFakeClient())
{
#if SOURCE_ENGINE < SE_LEFT4DEAD || SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_NUCLEARDAWN || \
SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE < SE_LEFT4DEAD || SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_NUCLEARDAWN || SOURCE_ENGINE == SE_MCV
// These games have the bug fixed where hltv/replay was getting kicked on hibernation
if (pPlayer->IsSourceTV() || pPlayer->IsReplay())
continue;
@@ -861,8 +839,9 @@ void PlayerManager::OnClientDisconnect(edict_t *pEntity)
m_PlayerCount--;
}
List<IClientListener *>::iterator iter;
IClientListener *pListener = NULL;
for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{
pListener = (*iter);
pListener->OnClientDisconnecting(client);
@@ -891,8 +870,9 @@ void PlayerManager::OnClientDisconnect_Post(edict_t *pEntity)
m_cldisconnect_post->PushCell(client);
m_cldisconnect_post->Execute(&res, NULL);
List<IClientListener *>::iterator iter;
IClientListener *pListener = NULL;
for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{
pListener = (*iter);
pListener->OnClientDisconnected(client);
@@ -1070,7 +1050,7 @@ void ListPluginsToClient(CPlayer *player, const CCommand &args)
return;
}
std::list<SMPlugin *> m_FailList;
SourceHook::List<SMPlugin *> m_FailList;
size_t i = 0;
for (; i < plugins->size(); i++)
@@ -1237,7 +1217,7 @@ void PlayerManager::OnClientCommandKeyValues(edict_t *pEntity, KeyValues *pComma
KeyValueStack *pStk = new KeyValueStack;
pStk->pBase = pCommand;
pStk->pCurRoot.push_front(pStk->pBase);
pStk->pCurRoot.push(pStk->pBase);
pStk->m_bDeleteOnDestroy = false;
Handle_t hndl = handlesys->CreateHandle(g_KeyValueType, pStk, g_pCoreIdent, g_pCoreIdent, NULL);
@@ -1282,7 +1262,7 @@ void PlayerManager::OnClientCommandKeyValues_Post(edict_t *pEntity, KeyValues *p
KeyValueStack *pStk = new KeyValueStack;
pStk->pBase = pCommand;
pStk->pCurRoot.push_front(pStk->pBase);
pStk->pCurRoot.push(pStk->pBase);
pStk->m_bDeleteOnDestroy = false;
Handle_t hndl = handlesys->CreateHandle(g_KeyValueType, pStk, g_pCoreIdent, g_pCoreIdent, NULL);
@@ -1378,8 +1358,9 @@ void PlayerManager::OnClientSettingsChanged(edict_t *pEntity)
}
/* Notify Extensions */
List<IClientListener *>::iterator iter;
IClientListener *pListener = NULL;
for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{
pListener = (*iter);
if (pListener->GetClientListenerVersion() >= 13)
@@ -1415,6 +1396,11 @@ int PlayerManager::GetNumPlayers()
return m_PlayerCount;
}
int PlayerManager::GetNumClients()
{
return m_ClientCount;
}
int PlayerManager::GetClientOfUserId(int userid)
{
if (userid < 0 || userid > USHRT_MAX)
@@ -1557,10 +1543,8 @@ void PlayerManager::InvalidatePlayer(CPlayer *pPlayer)
}
auto userid = engine->GetPlayerUserId(pPlayer->m_pEdict);
if (userid >= 0 && userid <= USHRT_MAX)
{
if (userid != -1)
m_UserIdLookUp[userid] = 0;
}
pPlayer->Disconnect();
}
@@ -1676,14 +1660,6 @@ void PlayerManager::ProcessCommandTarget(cmd_target_info_t *info)
strcpy(new_pattern, "STEAM_");
len = strlen(&info->pattern[7]);
/* Bound the copy so the "STEAM_" prefix, the copied bytes and the
* null terminator all fit within new_pattern. An over-long pattern
* is simply truncated; it will not match a real client's id.
*/
if (len > sizeof(new_pattern) - 7)
{
len = sizeof(new_pattern) - 7;
}
for (p = 0; p < len; p++)
{
new_pattern[6 + p] = info->pattern[7 + p];
@@ -1698,13 +1674,12 @@ void PlayerManager::ProcessCommandTarget(cmd_target_info_t *info)
{
size_t p = 0;
char c;
/* Leave room for the null terminator; truncate over-long patterns. */
while ((c = info->pattern[p + 1]) != '\0' && p < sizeof(new_pattern) - 1)
while ((c = info->pattern[p + 1]) != '\0')
{
new_pattern[p] = (c == '_') ? ':' : c;
new_pattern[p] = (c == '_') ? ':' : c;
++p;
}
new_pattern[p] = '\0';
}
@@ -1721,34 +1696,21 @@ void PlayerManager::ProcessCommandTarget(cmd_target_info_t *info)
// We want to make it easy for people to be kicked/banned, so don't require validation for command targets.
const char *steamId = steamIdType == 2 ? pTarget->GetSteam2Id(false) : pTarget->GetSteam3Id(false);
if (steamId)
if (steamId && strcmp(steamId, new_pattern) == 0)
{
// If id is STEAM2 and the universe is Public/Individual, allow either to match
if (
steamIdType == 2 && strlen(steamId) >= 7
&& (new_pattern[6] == '1' || new_pattern[6] == '0')
&& (steamId[6] == '1' || steamId[6] == '0')
)
if ((info->reason = FilterCommandTarget(pAdmin, pTarget, info->flags))
== COMMAND_TARGET_VALID)
{
new_pattern[6] = steamId[6];
info->targets[0] = i;
info->num_targets = 1;
ke::SafeStrcpy(info->target_name, info->target_name_maxlength, pTarget->GetName());
info->target_name_style = COMMAND_TARGETNAME_RAW;
}
if (strcmp(steamId, new_pattern) == 0)
else
{
if ((info->reason = FilterCommandTarget(pAdmin, pTarget, info->flags))
== COMMAND_TARGET_VALID)
{
info->targets[0] = i;
info->num_targets = 1;
ke::SafeStrcpy(info->target_name, info->target_name_maxlength, pTarget->GetName());
info->target_name_style = COMMAND_TARGETNAME_RAW;
}
else
{
info->num_targets = 0;
}
return;
info->num_targets = 0;
}
return;
}
}
}
@@ -1890,7 +1852,8 @@ void PlayerManager::ProcessCommandTarget(cmd_target_info_t *info)
}
}
for (auto iter = target_processors.begin(); iter != target_processors.end(); iter++)
List<ICommandTargetProcessor *>::iterator iter;
for (iter = target_processors.begin(); iter != target_processors.end(); iter++)
{
ICommandTargetProcessor *pProcessor = (*iter);
if (pProcessor->ProcessCommandTarget(info))
@@ -1973,8 +1936,9 @@ void PlayerManager::MaxPlayersChanged( int newvalue /*= -1*/ )
}
/* Notify Extensions */
List<IClientListener *>::iterator iter;
IClientListener *pListener = NULL;
for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{
pListener = (*iter);
if (pListener->GetClientListenerVersion() >= 8)
@@ -2017,7 +1981,7 @@ void CmdMaxplayersCallback()
g_Players.MaxPlayersChanged();
}
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
bool PlayerManager::HandleConVarQuery(QueryCvarCookie_t cookie, int client, EQueryCvarValueStatus result, const char *cvarName, const char *cvarValue)
{
for (int i = 1; i <= m_maxClients; i++)
@@ -2038,6 +2002,27 @@ bool PlayerManager::HandleConVarQuery(QueryCvarCookie_t cookie, int client, EQue
}
#endif
/* IGameEventListener2::FireGameEvent */
void PlayerManager::FireGameEvent(IGameEvent *pEvent)
{
const char *name = pEvent->GetName();
if (strcmp(name, "player_connect") == 0)
{
const int client = pEvent->GetInt("index") + 1;
const int userid = pEvent->GetInt("userid");
m_ClientCount++;
}
else if (strcmp(name, "player_disconnect") == 0)
{
const int userid = pEvent->GetInt("userid");
const int client = m_UserIdLookUp[userid];
m_ClientCount--;
}
}
/*******************
*** PLAYER CODE ***
@@ -2255,7 +2240,7 @@ void CPlayer::Disconnect()
m_bIsSourceTV = false;
m_bIsReplay = false;
m_Serial.value = -1;
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
m_LanguageCookie = InvalidQueryCvarCookie;
#endif
ClearNetchannelQueue();
@@ -2479,8 +2464,6 @@ void CPlayer::Kick(const char *str)
{
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
pClient->Disconnect(str);
#elif SOURCE_ENGINE == SE_OUTBREAK
pClient->Disconnect(NETWORK_DISCONNECT_KICKED);
#else
pClient->Disconnect("%s", str);
#endif
@@ -2499,7 +2482,8 @@ void CPlayer::DoPostConnectAuthorization()
{
bool delay = false;
for (auto iter = g_Players.m_hooks.begin();
List<IClientListener *>::iterator iter;
for (iter = g_Players.m_hooks.begin();
iter != g_Players.m_hooks.end();
iter++)
{
@@ -2558,7 +2542,8 @@ void CPlayer::NotifyPostAdminChecks()
/* Block beforehand so they can't double-call */
m_bAdminCheckSignalled = true;
for (auto iter = g_Players.m_hooks.begin();
List<IClientListener *>::iterator iter;
for (iter = g_Players.m_hooks.begin();
iter != g_Players.m_hooks.end();
iter++)
{
+19 -19
View File
@@ -39,15 +39,17 @@
#include <IPlayerHelpers.h>
#include <IAdminSystem.h>
#include <ITranslator.h>
#include <string>
#include <list>
#include <vector>
#include <sh_string.h>
#include <sh_list.h>
#include <sh_vector.h>
#include <am-string.h>
#include <am-deque.h>
#include "ConVarManager.h"
#include <steam/steamclientpublic.h>
using namespace SourceHook;
class IClient;
#define PLAYER_LIFE_UNKNOWN 0
@@ -129,9 +131,9 @@ private:
bool m_IsInGame = false;
bool m_IsAuthorized = false;
bool m_bIsInKickQueue = false;
std::string m_Name;
std::string m_Ip;
std::string m_IpNoPort;
String m_Name;
String m_Ip;
String m_IpNoPort;
std::string m_AuthID;
std::string m_Steam2Id;
std::string m_Steam3Id;
@@ -140,7 +142,7 @@ private:
edict_t *m_pEdict = nullptr;
IPlayerInfo *m_Info = nullptr;
IClient *m_pIClient = nullptr;
std::string m_LastPassword;
String m_LastPassword;
bool m_bAdminCheckSignalled = false;
int m_iIndex;
unsigned int m_LangId = SOURCEMOD_LANGUAGE_ENGLISH;
@@ -151,7 +153,7 @@ private:
bool m_bIsReplay = false;
serial_t m_Serial;
CSteamID m_SteamId;
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
QueryCvarCookie_t m_LanguageCookie = InvalidQueryCvarCookie;
#endif
std::deque<std::string> m_PrintfBuffer;
@@ -159,7 +161,8 @@ private:
class PlayerManager :
public SMGlobalClass,
public IPlayerManager
public IPlayerManager,
public IGameEventListener2
{
friend class CPlayer;
public:
@@ -192,13 +195,6 @@ public:
#endif
void OnClientSettingsChanged(edict_t *pEntity);
//void OnClientSettingsChanged_Pre(edict_t *pEntity);
#if SOURCE_ENGINE >= SE_ORANGEBOX && SOURCE_ENGINE != SE_MOCK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
void OnNetworkIDValidated(const char *pszUserName, const char *pszNetworkID, CSteamID steamID);
#else
void OnNetworkIDValidated(const char *pszUserName, const char *pszNetworkID);
#endif
#endif
void OnClientLanguageChanged(int client, unsigned int language);
void OnServerHibernationUpdate(bool bHibernating);
void OnClientPrintf(edict_t *pEdict, const char *szMsg);
@@ -210,6 +206,7 @@ public: //IPlayerManager
IGamePlayer *GetGamePlayer(edict_t *pEdict);
int GetMaxClients();
int GetNumPlayers();
int GetNumClients();
int GetClientOfUserId(int userid);
bool IsServerActivated();
int FilterCommandTarget(IGamePlayer *pAdmin, IGamePlayer *pTarget, int flags);
@@ -220,6 +217,8 @@ public: //IPlayerManager
int GetClientFromSerial(unsigned int serial);
void ClearAdminId(AdminId id);
void RecheckAnyAdmins();
public: // IGameEventListener2
void FireGameEvent(IGameEvent *pEvent);
public:
inline int MaxClients()
{
@@ -243,14 +242,14 @@ public:
{
return m_bInCCKVHook;
}
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
bool HandleConVarQuery(QueryCvarCookie_t cookie, int client, EQueryCvarValueStatus result, const char *cvarName, const char *cvarValue);
#endif
private:
void OnServerActivate(edict_t *pEdictList, int edictCount, int clientMax);
void InvalidatePlayer(CPlayer *pPlayer);
private:
std::list<IClientListener *> m_hooks;
List<IClientListener *> m_hooks;
IForward *m_clconnect;
IForward *m_clconnect_post;
IForward *m_cldisconnect;
@@ -271,7 +270,7 @@ private:
int m_PlayersSinceActive;
bool m_bServerActivated;
unsigned int *m_AuthQueue;
std::string m_PassInfoVar;
String m_PassInfoVar;
bool m_QueryLang;
bool m_bAuthstringValidation; // are we validating admins with steam before authorizing?
bool m_bIsListenServer;
@@ -281,6 +280,7 @@ private:
int m_SourceTVUserId;
int m_ReplayUserId;
bool m_bInCCKVHook;
int m_ClientCount;
private:
static const int NETMSG_TYPE_BITS = 5; // SVC_Print overhead for netmsg type
static const int SVC_Print_BufferSize = 2048 - 1; // -1 for terminating \0
+66 -86
View File
@@ -36,12 +36,12 @@
#include "ConVarManager.h"
#include "logic_bridge.h"
#define TIMER_MIN_ACCURACY 0.1
#define TIMER_MIN_ACCURACY 0.1
TimerSystem g_Timers;
double g_fUniversalTime = 0.0f;
float g_fGameStartTime = 0.0f; /* Game game start time, non-universal */
double g_fTimerThink = 0.0f; /* Timer's next think time */
float g_fGameStartTime = 0.0f; /* Game game start time, non-universal */
double g_fTimerThink = 0.0f; /* Timer's next think time */
const double *g_pUniversalTime = &g_fUniversalTime;
ConVar *mp_timelimit = NULL;
int g_TimeLeftMode = 0;
@@ -146,10 +146,9 @@ private:
*/
inline double CalcNextThink(double last, float interval)
{
const double next = last + interval;
if (g_fUniversalTime - next <= TIMER_MIN_ACCURACY)
if (g_fUniversalTime - last - interval <= TIMER_MIN_ACCURACY)
{
return next;
return last + interval;
}
else
{
@@ -157,7 +156,7 @@ inline double CalcNextThink(double last, float interval)
}
}
void ITimer::Initialize(ITimedEvent *pCallbacks, float fInterval, double fToExec, void *pData, int flags)
void ITimer::Initialize(ITimedEvent *pCallbacks, float fInterval, float fToExec, void *pData, int flags)
{
m_Listener = pCallbacks;
m_Interval = fInterval;
@@ -178,11 +177,12 @@ TimerSystem::TimerSystem()
TimerSystem::~TimerSystem()
{
while (!m_FreeTimers.empty())
CStack<ITimer *>::iterator iter;
for (iter=m_FreeTimers.begin(); iter!=m_FreeTimers.end(); iter++)
{
delete m_FreeTimers.top();
m_FreeTimers.pop();
delete (*iter);
}
m_FreeTimers.popall();
}
void TimerSystem::OnSourceModAllInitialized()
@@ -234,11 +234,10 @@ void TimerSystem::GameFrame(bool simulating)
m_fLastTickedTime = gpGlobals->curtime;
m_bHasMapTickedYet = true;
const bool timerThink = g_fUniversalTime >= g_fTimerThink;
RunFrame(timerThink);
if (timerThink)
if (g_fUniversalTime >= g_fTimerThink)
{
RunFrame();
g_fTimerThink = CalcNextThink(g_fTimerThink, TIMER_MIN_ACCURACY);
}
@@ -250,12 +249,31 @@ void TimerSystem::GameFrame(bool simulating)
}
}
void TimerSystem::ProcessRepeatTimers(double curtime, std::list<ITimer*>& timerList)
void TimerSystem::RunFrame()
{
ITimer *pTimer;
ITimer *pTimer;
TimerIter iter;
ResultType res;
for (auto iter=timerList.begin(); iter!=timerList.end(); )
double curtime = GetSimulatedTime();
for (iter=m_SingleTimers.begin(); iter!=m_SingleTimers.end(); )
{
pTimer = (*iter);
if (curtime >= pTimer->m_ToExec)
{
pTimer->m_InExec = true;
pTimer->m_Listener->OnTimer(pTimer, pTimer->m_pData);
pTimer->m_Listener->OnTimerEnd(pTimer, pTimer->m_pData);
iter = m_SingleTimers.erase(iter);
m_FreeTimers.push(pTimer);
}
else
{
break;
}
}
ResultType res;
for (iter=m_LoopTimers.begin(); iter!=m_LoopTimers.end(); )
{
pTimer = (*iter);
if (curtime >= pTimer->m_ToExec)
@@ -265,7 +283,7 @@ void TimerSystem::ProcessRepeatTimers(double curtime, std::list<ITimer*>& timerL
if (pTimer->m_KillMe || (res == Pl_Stop))
{
pTimer->m_Listener->OnTimerEnd(pTimer, pTimer->m_pData);
iter = timerList.erase(iter);
iter = m_LoopTimers.erase(iter);
m_FreeTimers.push(pTimer);
continue;
}
@@ -276,57 +294,17 @@ void TimerSystem::ProcessRepeatTimers(double curtime, std::list<ITimer*>& timerL
}
}
void TimerSystem::RunFrame(bool timerThink)
{
const double curtime = GetSimulatedTime();
//// One-off timers
ITimer *pTimer;
for (auto iter=m_SingleTimers.begin(); iter!=m_SingleTimers.end(); )
{
pTimer = (*iter);
// m_SingleTimers is sorted
if (curtime < pTimer->m_ToExec)
{
break;
}
if (timerThink || pTimer->m_Flags & TIMER_FLAG_TICK_PRECISE)
{
pTimer->m_InExec = true;
pTimer->m_Listener->OnTimer(pTimer, pTimer->m_pData);
pTimer->m_Listener->OnTimerEnd(pTimer, pTimer->m_pData);
iter = m_SingleTimers.erase(iter);
m_FreeTimers.push(pTimer);
}
else
{
iter++;
}
}
//// Repeating timers
// Most repeating timers do not need to be updated every frame
if (timerThink)
{
ProcessRepeatTimers(curtime, m_LowSpeedLoopTimers);
}
// High speed repeating timers will always update
ProcessRepeatTimers(curtime, m_HighSpeedLoopTimers);
}
ITimer *TimerSystem::CreateTimer(ITimedEvent *pCallbacks, float fInterval, void *pData, int flags)
{
ITimer *pTimer;
const double to_exec = GetSimulatedTime() + fInterval;
TimerIter iter;
float to_exec = GetSimulatedTime() + fInterval;
if (m_FreeTimers.empty())
{
pTimer = new ITimer;
} else {
pTimer = m_FreeTimers.top();
pTimer = m_FreeTimers.front();
m_FreeTimers.pop();
}
@@ -334,21 +312,20 @@ ITimer *TimerSystem::CreateTimer(ITimedEvent *pCallbacks, float fInterval, void
if (flags & TIMER_FLAG_REPEAT)
{
std::list<ITimer*>& timerList = pTimer->m_Flags & TIMER_FLAG_TICK_PRECISE ? m_HighSpeedLoopTimers : m_LowSpeedLoopTimers;
timerList.push_back(pTimer);
m_LoopTimers.push_back(pTimer);
goto return_timer;
}
if (m_SingleTimers.size() >= 1)
{
auto iter = --m_SingleTimers.end();
iter = --m_SingleTimers.end();
if ((*iter)->m_ToExec <= to_exec)
{
goto normal_insert_end;
}
}
for (auto iter=m_SingleTimers.begin(); iter!=m_SingleTimers.end(); iter++)
for (iter=m_SingleTimers.begin(); iter!=m_SingleTimers.end(); iter++)
{
if ((*iter)->m_ToExec >= to_exec)
{
@@ -393,10 +370,8 @@ void TimerSystem::FireTimerOnce(ITimer *pTimer, bool delayExec)
pTimer->m_InExec = false;
return;
}
std::list<ITimer*>& timerList = pTimer->m_Flags & TIMER_FLAG_TICK_PRECISE ? m_HighSpeedLoopTimers : m_LowSpeedLoopTimers;
pTimer->m_Listener->OnTimerEnd(pTimer, pTimer->m_pData);
timerList.remove(pTimer);
m_LoopTimers.remove(pTimer);
m_FreeTimers.push(pTimer);
}
}
@@ -414,13 +389,12 @@ void TimerSystem::KillTimer(ITimer *pTimer)
return;
}
pTimer->m_InExec = true; /* The timer is not really executed but this check needs to be done */
pTimer->m_InExec = true; /* The timer it's not really executed but this check needs to be done */
pTimer->m_Listener->OnTimerEnd(pTimer, pTimer->m_pData);
if (pTimer->m_Flags & TIMER_FLAG_REPEAT)
{
std::list<ITimer*>& timerList = pTimer->m_Flags & TIMER_FLAG_TICK_PRECISE ? m_HighSpeedLoopTimers : m_LowSpeedLoopTimers;
timerList.remove(pTimer);
m_LoopTimers.remove(pTimer);
} else {
m_SingleTimers.remove(pTimer);
}
@@ -428,27 +402,33 @@ void TimerSystem::KillTimer(ITimer *pTimer)
m_FreeTimers.push(pTimer);
}
std::stack<ITimer *> s_tokill;
CStack<ITimer *> s_tokill;
void TimerSystem::RemoveMapChangeTimers()
{
const auto KillMapchangeTimers = [](std::list<ITimer*>& timerList) {
for (ITimer* pTimer : timerList)
{
if (pTimer->m_Flags & TIMER_FLAG_NO_MAPCHANGE)
{
s_tokill.push(pTimer);
}
}
};
ITimer *pTimer;
TimerIter iter;
KillMapchangeTimers(m_SingleTimers);
for (iter=m_SingleTimers.begin(); iter!=m_SingleTimers.end(); iter++)
{
pTimer = (*iter);
if (pTimer->m_Flags & TIMER_FLAG_NO_MAPCHANGE)
{
s_tokill.push(pTimer);
}
}
KillMapchangeTimers(m_LowSpeedLoopTimers);
KillMapchangeTimers(m_HighSpeedLoopTimers);
for (iter=m_LoopTimers.begin(); iter!=m_LoopTimers.end(); iter++)
{
pTimer = (*iter);
if (pTimer->m_Flags & TIMER_FLAG_NO_MAPCHANGE)
{
s_tokill.push(pTimer);
}
}
while (!s_tokill.empty())
{
KillTimer(s_tokill.top());
KillTimer(s_tokill.front());
s_tokill.pop();
}
}
+11 -10
View File
@@ -33,17 +33,21 @@
#define _INCLUDE_SOURCEMOD_CTIMERSYS_H_
#include <ITimerSystem.h>
#include <stack>
#include <list>
#include <sh_stack.h>
#include <sh_list.h>
#include "sourcemm_api.h"
#include "sm_globals.h"
using namespace SourceHook;
using namespace SourceMod;
typedef List<ITimer *> TimerList;
typedef List<ITimer *>::iterator TimerIter;
class SourceMod::ITimer
{
public:
void Initialize(ITimedEvent *pCallbacks, float fInterval, double fToExec, void *pData, int flags);
void Initialize(ITimedEvent *pCallbacks, float fInterval, float fToExec, void *pData, int flags);
ITimedEvent *m_Listener;
void *m_pData;
float m_Interval;
@@ -76,16 +80,13 @@ public: //ITimerSystem
bool GetMapTimeLeft(float *pTime);
IMapTimer *GetMapTimer();
public:
void RunFrame(bool timerThink);
void RunFrame();
void RemoveMapChangeTimers();
void GameFrame(bool simulating);
private:
void ProcessRepeatTimers(double curtime, std::list<ITimer*>& timerList);
private:
std::list<ITimer*> m_SingleTimers;
std::list<ITimer*> m_LowSpeedLoopTimers;
std::list<ITimer*> m_HighSpeedLoopTimers;
std::stack<ITimer *> m_FreeTimers;
List<ITimer *> m_SingleTimers;
List<ITimer *> m_LoopTimers;
CStack<ITimer *> m_FreeTimers;
IMapTimer *m_pMapTimer;
/* This is stuff for our manual ticking escapades. */
+2 -6
View File
@@ -32,10 +32,6 @@
#ifndef _INCLUDE_SOURCEMOD_SMPBMESSAGE_H_
#define _INCLUDE_SOURCEMOD_SMPBMESSAGE_H_
#ifdef GetMessage
#undef GetMessage
#endif
#include <sh_list.h>
#include <google/protobuf/descriptor.h>
#include <amtl/am-string.h>
@@ -89,7 +85,7 @@
return false; \
}
typedef std::list<Handle_t> PBHandleList;
typedef List<Handle_t> PBHandleList;
class SMProtobufMessage
{
@@ -101,7 +97,7 @@ public:
~SMProtobufMessage()
{
auto iter = childHandles.begin();
PBHandleList::iterator iter = childHandles.begin();
while (iter != childHandles.end())
{
Handle_t &hndl = (*iter);
+27 -42
View File
@@ -39,15 +39,12 @@
#include <berimbau_usermessage_helpers.h>
#elif SOURCE_ENGINE == SE_MCV
#include <vietnam_usermessage_helpers.h>
#elif SOURCE_ENGINE == SE_OUTBREAK
#include <base_usermessage_helpers.h>
#include <terror_usermessage_helpers.h>
#endif
#include <amtl/am-string.h>
UserMessages g_UserMsgs;
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
SH_DECL_HOOK3_void(IVEngineServer, SendUserMessage, SH_NOATTRIB, 0, IRecipientFilter &, int, const protobuf::Message &);
#else
#if SOURCE_ENGINE >= SE_LEFT4DEAD
@@ -56,7 +53,7 @@ SH_DECL_HOOK3(IVEngineServer, UserMessageBegin, SH_NOATTRIB, 0, bf_write *, IRec
SH_DECL_HOOK2(IVEngineServer, UserMessageBegin, SH_NOATTRIB, 0, bf_write *, IRecipientFilter *, int);
#endif
SH_DECL_HOOK0_void(IVEngineServer, MessageEnd, SH_NOATTRIB, 0);
#endif // ==SE_CSGO || ==SE_BLADE || ==SE_MCV || ==SE_OUTBREAK
#endif // ==SE_CSGO || ==SE_BLADE || ==SE_MCV
UserMessages::UserMessages()
#ifndef USE_PROTOBUF_USERMESSAGES
@@ -75,11 +72,12 @@ UserMessages::UserMessages()
UserMessages::~UserMessages()
{
while (!m_FreeListeners.empty())
CStack<ListenerInfo *>::iterator iter;
for (iter=m_FreeListeners.begin(); iter!=m_FreeListeners.end(); iter++)
{
delete m_FreeListeners.top();
m_FreeListeners.pop();
delete (*iter);
}
m_FreeListeners.popall();
}
void UserMessages::OnSourceModStartup(bool late)
@@ -99,7 +97,7 @@ void UserMessages::OnSourceModAllShutdown()
{
if (m_HookCount)
{
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
SH_REMOVE_HOOK(IVEngineServer, SendUserMessage, engine, SH_MEMBER(this, &UserMessages::OnSendUserMessage_Pre), false);
SH_REMOVE_HOOK(IVEngineServer, SendUserMessage, engine, SH_MEMBER(this, &UserMessages::OnSendUserMessage_Post), true);
#else
@@ -121,9 +119,6 @@ int UserMessages::GetMessageIndex(const char *msg)
return g_BerimbauUsermessageHelpers.GetIndex(msg);
#elif SOURCE_ENGINE == SE_MCV
return g_VietnamUsermessageHelpers.GetIndex(msg);
#elif SOURCE_ENGINE == SE_OUTBREAK
int idx = g_TerrorUsermessageHelpers.GetIndex(msg);
return idx == -1 ? g_BaseUsermessageHelpers.GetIndex(msg) : idx;
#else
int msgid;
@@ -165,10 +160,6 @@ bool UserMessages::GetMessageName(int msgid, char *buffer, size_t maxlength) con
const char *pszName = g_BerimbauUsermessageHelpers.GetName(msgid);
#elif SOURCE_ENGINE == SE_MCV
const char *pszName = g_VietnamUsermessageHelpers.GetName(msgid);
#elif SOURCE_ENGINE == SE_OUTBREAK
const char *pszName = g_TerrorUsermessageHelpers.GetName(msgid);
if (pszName == nullptr)
pszName = g_BaseUsermessageHelpers.GetName(msgid);
#endif
if (!pszName)
return false;
@@ -318,7 +309,7 @@ bool UserMessages::EndMessage()
return false;
}
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
if (m_CurFlags & USERMSG_BLOCKHOOKS)
{
ENGINE_CALL(SendUserMessage)(static_cast<IRecipientFilter &>(m_CellRecFilter), m_CurId, *m_FakeEngineBuffer);
@@ -348,7 +339,7 @@ bool UserMessages::EndMessage()
} else {
engine->MessageEnd();
}
#endif // SE_CSGO || SE_BLADE || SE_MCV || SE_OUTBREAK
#endif // SE_CSGO || SE_BLADE || SE_MCV
m_InExec = false;
m_CurFlags = 0;
@@ -422,7 +413,7 @@ bool UserMessages::InternalHook(int msg_id, IBitBufUserMessageListener *pListene
{
pInfo = new ListenerInfo;
} else {
pInfo = m_FreeListeners.top();
pInfo = m_FreeListeners.front();
m_FreeListeners.pop();
}
@@ -433,7 +424,7 @@ bool UserMessages::InternalHook(int msg_id, IBitBufUserMessageListener *pListene
if (!m_HookCount++)
{
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
SH_ADD_HOOK(IVEngineServer, SendUserMessage, engine, SH_MEMBER(this, &UserMessages::OnSendUserMessage_Pre), false);
SH_ADD_HOOK(IVEngineServer, SendUserMessage, engine, SH_MEMBER(this, &UserMessages::OnSendUserMessage_Post), true);
#else
@@ -463,11 +454,6 @@ const protobuf::Message *UserMessages::GetMessagePrototype(int msg_type)
return g_BerimbauUsermessageHelpers.GetPrototype(msg_type);
#elif SOURCE_ENGINE == SE_MCV
return g_VietnamUsermessageHelpers.GetPrototype(msg_type);
#elif SOURCE_ENGINE == SE_OUTBREAK
auto *msg = g_TerrorUsermessageHelpers.GetPrototype(msg_type);
if (msg == nullptr)
msg = g_BaseUsermessageHelpers.GetPrototype(msg_type);
return msg;
#endif
}
#endif
@@ -479,6 +465,7 @@ bool UserMessages::InternalUnhook(int msg_id, IBitBufUserMessageListener *pListe
#endif
{
MsgList *pList;
MsgIter iter;
ListenerInfo *pInfo;
bool deleted = false;
@@ -488,7 +475,7 @@ bool UserMessages::InternalUnhook(int msg_id, IBitBufUserMessageListener *pListe
}
pList = (intercept) ? &m_msgIntercepts[msg_id] : &m_msgHooks[msg_id];
for (auto iter=pList->begin(); iter!=pList->end(); iter++)
for (iter=pList->begin(); iter!=pList->end(); iter++)
{
pInfo = (*iter);
if (pInfo->Callback == pListener && pInfo->IsNew == isNew)
@@ -516,7 +503,7 @@ void UserMessages::_DecRefCounter()
{
if (--m_HookCount == 0)
{
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
SH_REMOVE_HOOK(IVEngineServer, SendUserMessage, engine, SH_MEMBER(this, &UserMessages::OnSendUserMessage_Pre), false);
SH_REMOVE_HOOK(IVEngineServer, SendUserMessage, engine, SH_MEMBER(this, &UserMessages::OnSendUserMessage_Post), true);
#else
@@ -528,7 +515,7 @@ void UserMessages::_DecRefCounter()
}
}
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
void UserMessages::OnSendUserMessage_Pre(IRecipientFilter &filter, int msg_type, const protobuf::Message &msg)
{
#if SOURCE_ENGINE == SE_CSGO
@@ -537,10 +524,6 @@ void UserMessages::OnSendUserMessage_Pre(IRecipientFilter &filter, int msg_type,
const char *pszName = g_BerimbauUsermessageHelpers.GetName(msg_type);
#elif SOURCE_ENGINE == SE_MCV
const char *pszName = g_VietnamUsermessageHelpers.GetName(msg_type);
#elif SOURCE_ENGINE == SE_OUTBREAK
const char *pszName = g_TerrorUsermessageHelpers.GetName(msg_type);
if (pszName == nullptr)
pszName = g_BaseUsermessageHelpers.GetName(msg_type);
#endif
OnStartMessage_Pre(&filter, msg_type, pszName);
@@ -589,7 +572,7 @@ void UserMessages::OnSendUserMessage_Post(IRecipientFilter &filter, int msg_type
RETURN_META(res)
#endif
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
protobuf::Message *UserMessages::OnStartMessage_Pre(IRecipientFilter *filter, int msg_type, const char *msg_name)
#elif SOURCE_ENGINE >= SE_LEFT4DEAD
bf_write *UserMessages::OnStartMessage_Pre(IRecipientFilter *filter, int msg_type, const char *msg_name)
@@ -629,7 +612,7 @@ bf_write *UserMessages::OnStartMessage_Pre(IRecipientFilter *filter, int msg_typ
UM_RETURN_META_VALUE(MRES_IGNORED, NULL);
}
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
protobuf::Message *UserMessages::OnStartMessage_Post(IRecipientFilter *filter, int msg_type, const char *msg_name)
#elif SOURCE_ENGINE >= SE_LEFT4DEAD
bf_write *UserMessages::OnStartMessage_Post(IRecipientFilter *filter, int msg_type, const char *msg_name)
@@ -662,12 +645,13 @@ void UserMessages::OnMessageEnd_Post()
}
MsgList *pList;
MsgIter iter;
ListenerInfo *pInfo;
m_InHook = false;
pList = &m_msgIntercepts[m_CurId];
for (auto iter=pList->begin(); iter!=pList->end(); )
for (iter=pList->begin(); iter!=pList->end(); )
{
pInfo = (*iter);
if (m_BlockEndPost && !pInfo->IsNew)
@@ -694,7 +678,7 @@ void UserMessages::OnMessageEnd_Post()
}
pList = &m_msgHooks[m_CurId];
for (auto iter=pList->begin(); iter!=pList->end(); )
for (iter=pList->begin(); iter!=pList->end(); )
{
pInfo = (*iter);
if (m_BlockEndPost && !pInfo->IsNew)
@@ -729,6 +713,7 @@ void UserMessages::OnMessageEnd_Pre()
}
MsgList *pList;
MsgIter iter;
ListenerInfo *pInfo;
ResultType res;
@@ -736,7 +721,7 @@ void UserMessages::OnMessageEnd_Pre()
bool handled = false;
pList = &m_msgIntercepts[m_CurId];
for (auto iter=pList->begin(); iter!=pList->end(); )
for (iter=pList->begin(); iter!=pList->end(); )
{
pInfo = (*iter);
pInfo->IsHooked = true;
@@ -792,7 +777,7 @@ void UserMessages::OnMessageEnd_Pre()
if (!handled && intercepted)
{
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
ENGINE_CALL(SendUserMessage)(static_cast<IRecipientFilter &>(*m_CurRecFilter), m_CurId, *m_InterceptBuffer);
#else
bf_write *engine_bfw;
@@ -804,11 +789,11 @@ void UserMessages::OnMessageEnd_Pre()
m_ReadBuffer.StartReading(m_InterceptBuffer.GetBasePointer(), m_InterceptBuffer.GetNumBytesWritten());
engine_bfw->WriteBitsFromBuffer(&m_ReadBuffer, m_InterceptBuffer.GetNumBitsWritten());
ENGINE_CALL(MessageEnd)();
#endif // SE_CSGO || SE_BLADE || SE_MCV || SE_OUTBREAK
#endif // SE_CSGO || SE_BLADE || SE_MCV
}
{
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
int size = m_OrigBuffer->ByteSize();
uint8 *data = (uint8 *)stackalloc(size);
m_OrigBuffer->SerializePartialToArray(data, size);
@@ -820,7 +805,7 @@ void UserMessages::OnMessageEnd_Pre()
#endif
pList = &m_msgHooks[m_CurId];
for (auto iter=pList->begin(); iter!=pList->end(); )
for (iter=pList->begin(); iter!=pList->end(); )
{
pInfo = (*iter);
pInfo->IsHooked = true;
@@ -838,7 +823,7 @@ void UserMessages::OnMessageEnd_Pre()
iter++;
}
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
delete pTempMsg;
#endif
}
+12 -13
View File
@@ -34,23 +34,21 @@
#include <IUserMessages.h>
#include "sourcemm_api.h"
#include <sm_hashmap.h>
#include <sm_stringhashmap.h>
#include "sm_stringutil.h"
#include "CellRecipientFilter.h"
#include "sm_globals.h"
#include <list>
#include <stack>
#include <sh_list.h>
#include <sh_stack.h>
using namespace SourceHook;
using namespace SourceMod;
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
#define USE_PROTOBUF_USERMESSAGES
#endif
#ifdef USE_PROTOBUF_USERMESSAGES
#ifdef GetMessage
#undef GetMessage
#endif
#include <google/protobuf/message.h>
#include <google/protobuf/descriptor.h>
#include <netmessages.pb.h>
@@ -74,7 +72,8 @@ struct ListenerInfo
bool IsNew;
};
typedef std::list<ListenerInfo *> MsgList;
typedef List<ListenerInfo *> MsgList;
typedef List<ListenerInfo *>::iterator MsgIter;
class UserMessages :
public IUserMessages,
@@ -103,12 +102,12 @@ public: //IUserMessages
bool intercept=false);
UserMessageType GetUserMessageType() const;
public:
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
void OnSendUserMessage_Pre(IRecipientFilter &filter, int msg_type, const protobuf::Message &msg);
void OnSendUserMessage_Post(IRecipientFilter &filter, int msg_type, const protobuf::Message &msg);
#endif
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
protobuf::Message *OnStartMessage_Pre(IRecipientFilter *filter, int msg_type, const char *msg_name);
protobuf::Message *OnStartMessage_Post(IRecipientFilter *filter, int msg_type, const char *msg_name);
#elif SOURCE_ENGINE >= SE_LEFT4DEAD
@@ -131,9 +130,9 @@ private:
#endif
void _DecRefCounter();
private:
std::list<ListenerInfo *> m_msgHooks[255];
std::list<ListenerInfo *> m_msgIntercepts[255];
std::stack<ListenerInfo *> m_FreeListeners;
List<ListenerInfo *> m_msgHooks[255];
List<ListenerInfo *> m_msgIntercepts[255];
CStack<ListenerInfo *> m_FreeListeners;
IRecipientFilter *m_CurRecFilter;
#ifndef USE_PROTOBUF_USERMESSAGES
unsigned char m_pBase[2500];
+9 -6
View File
@@ -26,7 +26,7 @@
// or <http://www.sourcemod.net/license.php>.
#include "sm_globals.h"
#include <list>
#include <sh_list.h>
#include <convar.h>
#include "concmd_cleaner.h"
#include "sm_stringutil.h"
@@ -36,7 +36,7 @@
#if SOURCE_ENGINE >= SE_ORANGEBOX
SH_DECL_HOOK1_void(ICvar, UnregisterConCommand, SH_NOATTRIB, 0, ConCommandBase *);
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
SH_DECL_HOOK2_void(ICvar, RegisterConCommand, SH_NOATTRIB, 0, ConCommandBase *, bool);
#else
SH_DECL_HOOK1_void(ICvar, RegisterConCommand, SH_NOATTRIB, 0, ConCommandBase *);
@@ -45,6 +45,8 @@ SH_DECL_HOOK1_void(ICvar, RegisterConCommand, SH_NOATTRIB, 0, ConCommandBase *);
SH_DECL_HOOK1_void(ICvar, RegisterConCommandBase, SH_NOATTRIB, 0, ConCommandBase *);
#endif
using namespace SourceHook;
struct ConCommandInfo
{
ConCommandBase *pBase;
@@ -52,7 +54,7 @@ struct ConCommandInfo
char name[64];
};
std::list<ConCommandInfo *> tracked_bases;
List<ConCommandInfo *> tracked_bases;
IConCommandLinkListener *IConCommandLinkListener::head = NULL;
ConCommandBase *FindConCommandBase(const char *name);
@@ -80,7 +82,7 @@ public:
#endif
}
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV || SOURCE_ENGINE == SE_OUTBREAK
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_BLADE || SOURCE_ENGINE == SE_MCV
void LinkConCommandBase(ConCommandBase *pBase, bool unknown)
#else
void LinkConCommandBase(ConCommandBase *pBase)
@@ -97,7 +99,7 @@ public:
void UnlinkConCommandBase(ConCommandBase *pBase)
{
ConCommandInfo *pInfo;
auto iter = tracked_bases.begin();
List<ConCommandInfo *>::iterator iter = tracked_bases.begin();
IConCommandLinkListener *listener = IConCommandLinkListener::head;
while (listener)
@@ -135,9 +137,10 @@ public:
void RemoveTarget(ConCommandBase *pBase, IConCommandTracker *cls)
{
List<ConCommandInfo *>::iterator iter;
ConCommandInfo *pInfo;
auto iter = tracked_bases.begin();
iter = tracked_bases.begin();
while (iter != tracked_bases.end())
{
pInfo = (*iter);
+1 -9
View File
@@ -45,7 +45,6 @@ static Queue<FrameAction> *frame_actions;
static float g_LastMenuTime = 0.0f;
static float g_LastAuthCheck = 0.0f;
bool g_PendingInternalPush = false;
bool g_PendingAuthCheck = false;
class FrameActionInit : public SMGlobalClass
{
@@ -115,16 +114,9 @@ void RunFrameHooks(bool simulating)
g_LastMenuTime = curtime;
}
/* g_PendingAuthCheck is set by the NetworkIDValidated hook so that a client
* whose Steam ticket was just validated is authorized on the next frame rather
* than waiting up to 0.7s for the periodic check. It's deferred to the next frame
* (instead of authorizing inline in the hook) because the engine doesn't flag the
* client as fully authenticated until after the NetworkIDValidated callback returns.
*/
if (*g_NumPlayersToAuth && (g_PendingAuthCheck || curtime - g_LastAuthCheck >= 0.7f))
if (*g_NumPlayersToAuth && curtime - g_LastAuthCheck >= 0.7f)
{
g_Players.RunAuthChecks();
g_LastAuthCheck = curtime;
g_PendingAuthCheck = false;
}
}
-1
View File
@@ -46,7 +46,6 @@ struct FrameAction
};
extern bool g_PendingInternalPush;
extern bool g_PendingAuthCheck;
void AddFrameAction(const FrameAction & action);
void RunFrameHooks(bool simulating);
+1 -1
View File
@@ -34,7 +34,7 @@
#include <IADTFactory.h>
#include "common_logic.h"
#include <sm_hashmap.h>
#include <sm_stringhashmap.h>
using namespace SourceMod;
+9 -16
View File
@@ -8,8 +8,6 @@ for cxx in builder.targets:
os.path.join(builder.sourcePath, 'core', 'logic'),
os.path.join(builder.sourcePath, 'public'),
os.path.join(builder.sourcePath, 'sourcepawn', 'include'),
os.path.join(builder.sourcePath, 'sourcepawn'),
os.path.join(builder.sourcePath, 'sourcepawn', 'vm'),
os.path.join(builder.sourcePath, 'public', 'amtl', 'amtl'),
os.path.join(builder.sourcePath, 'public', 'amtl'),
os.path.join(SM.mms_root, 'core', 'sourcehook')
@@ -18,24 +16,15 @@ for cxx in builder.targets:
'SM_DEFAULT_THREADER',
'SM_LOGIC'
]
SP.AddVmFlags(binary)
if binary.compiler.target.platform == 'linux':
binary.compiler.postlink += ['-lpthread', '-lrt', '-lm']
binary.compiler.postlink += ['-lpthread', '-lrt']
elif binary.compiler.target.platform == 'mac':
binary.compiler.cflags += ['-Wno-deprecated-declarations']
binary.compiler.postlink += ['-framework', 'CoreServices', '-lm']
target = binary.compiler.target
binary.compiler.linkflags += [
SP.static_libsp[target],
SP.libamtl[target],
SP.zlib[target],
SP.mimalloc[target],
]
binary.compiler.postlink += ['-framework', 'CoreServices']
if binary.compiler.family == 'gcc' or binary.compiler.family == 'clang':
binary.compiler.cxxflags += ['-fno-rtti', '-Wno-invalid-offsetof']
binary.compiler.cxxflags += ['-fno-rtti']
elif binary.compiler.family == 'msvc':
binary.compiler.cxxflags += ['/GR-']
@@ -96,7 +85,11 @@ for cxx in builder.targets:
'FrameIterator.cpp',
'DatabaseConfBuilder.cpp',
'LumpManager.cpp',
'smn_entitylump.cpp'
'smn_entitylump.cpp',
'NativeInvoker.cpp',
]
if binary.compiler.target.arch == 'x86_64':
binary.sources += ['PseudoAddrManager.cpp']
SM.binaries += [builder.Add(binary)]
+14 -8
View File
@@ -233,7 +233,8 @@ AdminCache::~AdminCache()
DumpAdminCache(AdminCache_Overrides, false);
DumpAdminCache(AdminCache_Groups, false);
for (auto iter=m_AuthMethods.begin();
List<AuthMethod *>::iterator iter;
for (iter=m_AuthMethods.begin();
iter!=m_AuthMethods.end();
iter++)
{
@@ -758,7 +759,8 @@ bool AdminCache::GetGroupCommandOverride(GroupId id, const char *name, OverrideT
AuthMethod *AdminCache::GetMethodByIndex(unsigned int index)
{
for (auto iter=m_AuthMethods.begin();
List<AuthMethod *>::iterator iter;
for (iter=m_AuthMethods.begin();
iter!=m_AuthMethods.end();
iter++)
{
@@ -972,7 +974,8 @@ void AdminCache::InvalidateAdminCache(bool unlink_admins)
}
}
/* Wipe the identity cache first */
for (auto iter=m_AuthMethods.begin();
List<AuthMethod *>::iterator iter;
for (iter=m_AuthMethods.begin();
iter!=m_AuthMethods.end();
iter++)
{
@@ -995,6 +998,7 @@ void AdminCache::InvalidateAdminCache(bool unlink_admins)
void AdminCache::DumpAdminCache(AdminCachePart part, bool rebuild)
{
List<IAdminListener *>::iterator iter;
IAdminListener *pListener;
if (part == AdminCache_Overrides)
@@ -1003,7 +1007,7 @@ void AdminCache::DumpAdminCache(AdminCachePart part, bool rebuild)
DumpCommandOverrideCache(Override_CommandGroup);
if (rebuild && !m_destroying)
{
for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{
pListener = (*iter);
pListener->OnRebuildOverrideCache();
@@ -1017,7 +1021,7 @@ void AdminCache::DumpAdminCache(AdminCachePart part, bool rebuild)
InvalidateGroupCache();
if (rebuild && !m_destroying)
{
for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{
pListener = (*iter);
pListener->OnRebuildGroupCache();
@@ -1029,7 +1033,7 @@ void AdminCache::DumpAdminCache(AdminCachePart part, bool rebuild)
InvalidateAdminCache(true);
if (rebuild && !m_destroying)
{
for (auto iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++)
{
pListener = (*iter);
pListener->OnRebuildAdminCache((part == AdminCache_Groups));
@@ -1054,8 +1058,9 @@ const char *AdminCache::GetAdminName(AdminId id)
bool AdminCache::GetMethodIndex(const char *name, unsigned int *_index)
{
List<AuthMethod *>::iterator iter;
unsigned int index = 0;
for (auto iter=m_AuthMethods.begin();
for (iter=m_AuthMethods.begin();
iter!=m_AuthMethods.end();
iter++,index++)
{
@@ -1957,7 +1962,8 @@ AdminUser *AdminCache::GetUser(AdminId aid)
const char *AdminCache::GetMethodName(unsigned int index)
{
for (auto iter=m_AuthMethods.begin();
List<AuthMethod *>::iterator iter;
for (iter=m_AuthMethods.begin();
iter!=m_AuthMethods.end();
iter++)
{
+8 -6
View File
@@ -36,12 +36,14 @@
#include <IAdminSystem.h>
#include "sm_memtable.h"
#include <sm_trie.h>
#include <list>
#include <string>
#include <sh_list.h>
#include <sh_string.h>
#include <IForwardSys.h>
#include <sm_hashmap.h>
#include <sm_stringhashmap.h>
#include <sm_namehashset.h>
using namespace SourceHook;
#define GRP_MAGIC_SET 0xDEADFADE
#define GRP_MAGIC_UNSET 0xFACEFACE
#define USR_MAGIC_SET 0xDEADFACE
@@ -68,7 +70,7 @@ struct AdminGroup
struct AuthMethod
{
std::string name;
String name;
StringHashMap<AdminId> identities;
AuthMethod(const char *name)
@@ -212,8 +214,8 @@ public:
int m_LastGroup;
int m_FreeGroupList;
StringHashMap<GroupId> m_Groups;
std::list<IAdminListener *> m_hooks;
std::list<AuthMethod *> m_AuthMethods;
List<IAdminListener *> m_hooks;
List<AuthMethod *> m_AuthMethods;
NameHashSet<AuthMethod *> m_AuthTables;
IForward *m_pCacheFwd;
int m_FirstUser;
+2 -1
View File
@@ -109,9 +109,10 @@ SWThreadHandle *BaseWorker::PopThreadFromQueue()
if (!m_ThreadQueue.size())
return NULL;
SourceHook::List<SWThreadHandle *>::iterator begin;
SWThreadHandle *swt;
auto begin = m_ThreadQueue.begin();
begin = m_ThreadQueue.begin();
swt = (*begin);
m_ThreadQueue.erase(begin);
+2 -2
View File
@@ -32,7 +32,7 @@
#ifndef _INCLUDE_SOURCEMOD_BASEWORKER_H
#define _INCLUDE_SOURCEMOD_BASEWORKER_H
#include <list>
#include "sh_list.h"
#include "ThreadSupport.h"
#define SM_DEFAULT_THREADS_PER_FRAME 1
@@ -96,7 +96,7 @@ public: //BaseWorker
virtual void AddThreadToQueue(SWThreadHandle *pHandle);
virtual SWThreadHandle *PopThreadFromQueue();
protected:
std::list<SWThreadHandle *> m_ThreadQueue;
SourceHook::List<SWThreadHandle *> m_ThreadQueue;
unsigned int m_perFrame;
volatile WorkerState m_state;
IThreadWorkerCallbacks *m_pHooks;
+42 -152
View File
@@ -51,7 +51,6 @@ DBManager g_DBMan;
DBManager::DBManager()
: m_Terminate(false),
m_ActiveOperation(NULL),
m_pDefault(NULL)
{
}
@@ -205,7 +204,7 @@ void DBManager::RemoveDriver(IDBDriver *pDriver)
{
if (m_drivers[i] == pDriver)
{
m_drivers.erase(m_drivers.begin() + i);
m_drivers.erase(m_drivers.iterAt(i));
break;
}
}
@@ -244,7 +243,11 @@ void DBManager::RemoveDriver(IDBDriver *pDriver)
for (qiter = templist.begin();
qiter != templist.end();
qiter++)
FinalizeOperation(*qiter, true);
{
IDBThreadOperation *op = (*qiter);
op->CancelThinkPart();
op->Destroy();
}
}
IDBDriver *DBManager::GetDefaultDriver()
@@ -383,108 +386,11 @@ void DBManager::KillWorkerThread()
}
}
void DBManager::FinalizeOperation(IDBThreadOperation *op, bool driver_unloading)
{
bool cancelled = false;
{
std::lock_guard<std::mutex> lock(m_Lock);
m_OperationOwners.erase(op);
auto iter = m_CancelledOperations.find(op);
if (iter != m_CancelledOperations.end())
{
cancelled = true;
m_CancelledOperations.erase(iter);
}
}
if (cancelled)
{
op->Destroy();
}
else
{
if (driver_unloading)
op->CancelThinkPart();
else
op->RunThinkPart();
op->Destroy();
}
}
void DBManager::CancelPluginOperations(IdentityToken_t *identity)
{
Queue<IDBThreadOperation *> cancelled;
bool active_in_think_queue = false;
std::unique_lock<std::mutex> lock(m_Lock);
auto owns = [this, identity](IDBThreadOperation *op) {
auto iter = m_OperationOwners.find(op);
return iter != m_OperationOwners.end() && iter->second == identity;
};
for (PrioQueueLevel priority : {PrioQueue_High, PrioQueue_Normal, PrioQueue_Low})
{
Queue<IDBThreadOperation *> &queue = m_OpQueue.GetQueue(priority);
for (auto iter = queue.begin(); iter != queue.end();)
{
IDBThreadOperation *op = *iter;
if (owns(op))
{
cancelled.push(op);
m_OperationOwners.erase(op);
iter = queue.erase(iter);
}
else
{
iter++;
}
}
}
IDBThreadOperation *active = m_ActiveOperation;
bool cancelling_active = active && owns(active);
{
std::lock_guard<std::mutex> think_lock(m_ThinkLock);
for (auto iter = m_ThinkQueue.begin(); iter != m_ThinkQueue.end();)
{
IDBThreadOperation *op = *iter;
if (owns(op))
{
if (op == active)
active_in_think_queue = true;
cancelled.push(op);
m_OperationOwners.erase(op);
iter = m_ThinkQueue.erase(iter);
}
else
{
iter++;
}
}
}
if (cancelling_active)
{
if (active_in_think_queue)
m_ActiveOperation = nullptr;
else
m_CancelledOperations.insert(active);
}
lock.unlock();
while (!cancelled.empty())
{
IDBThreadOperation *op = cancelled.first();
cancelled.pop();
op->Destroy();
}
}
static IdentityToken_t *s_pAddBlock = NULL;
bool DBManager::AddToThreadQueue(IDBThreadOperation *op, PrioQueueLevel prio)
{
IdentityToken_t *owner = op->GetOwner();
if (s_pAddBlock && owner == s_pAddBlock)
if (s_pAddBlock && op->GetOwner() == s_pAddBlock)
{
return false;
}
@@ -500,7 +406,6 @@ bool DBManager::AddToThreadQueue(IDBThreadOperation *op, PrioQueueLevel prio)
{
std::lock_guard<std::mutex> lock(m_Lock);
Queue<IDBThreadOperation *> &queue = m_OpQueue.GetQueue(prio);
m_OperationOwners.emplace(op, owner);
queue.push(op);
m_QueueEvent.notify_one();
}
@@ -554,7 +459,6 @@ void DBManager::ThreadMain()
IDBThreadOperation *op = queue->first();
queue->pop();
m_ActiveOperation = op;
// Unlock the queue when we run the query, so the main thread can
// keep pumping events. We re-acquire the lock to check for more
@@ -572,9 +476,6 @@ void DBManager::ThreadMain()
std::lock_guard<std::mutex> think_lock(m_ThinkLock);
m_ThinkQueue.push(op);
}
lock.lock();
m_ActiveOperation = nullptr;
lock.unlock();
// Note that we add a 20ms delay after processing a query. This is
// questionable but the intent is to avoid starving the game thread.
@@ -587,16 +488,21 @@ void DBManager::ThreadMain()
void DBManager::RunFrame()
{
/* Don't bother if we're empty */
if (!m_ThinkQueue.size())
{
return;
}
/* Dump one thing per-frame so the server stays sane. */
IDBThreadOperation *op;
{
std::lock_guard<std::mutex> lock(m_ThinkLock);
if (m_ThinkQueue.empty())
return;
op = m_ThinkQueue.first();
m_ThinkQueue.pop();
}
FinalizeOperation(op, false);
op->RunThinkPart();
op->Destroy();
}
void DBManager::OnSourceModIdentityDropped(IdentityToken_t *pToken)
@@ -615,8 +521,7 @@ void DBManager::OnSourceModIdentityDropped(IdentityToken_t *pToken)
while (iter != m_ThinkQueue.end())
{
IDBThreadOperation *op = (*iter);
auto owner = m_OperationOwners.find(op);
if (owner != m_OperationOwners.end() && owner->second == pToken)
if (op->GetOwner() == pToken)
{
templist.push(op);
iter = m_ThinkQueue.erase(iter);
@@ -628,64 +533,49 @@ void DBManager::OnSourceModIdentityDropped(IdentityToken_t *pToken)
for (iter = templist.begin();
iter != templist.end();
iter++)
FinalizeOperation(*iter, false);
{
IDBThreadOperation *op = (*iter);
op->RunThinkPart();
op->Destroy();
}
s_pAddBlock = NULL;
}
bool DBManager::ShouldDiscardPluginOperations()
{
const char *behavior = g_pSM->GetCoreConfigValue("DatabasePluginUnload");
return !behavior || strcasecmp(behavior, "wait") != 0;
}
void DBManager::WaitForPluginOperations(IPlugin *plugin)
void DBManager::OnPluginWillUnload(IPlugin *plugin)
{
/* Kill the thread so we can flush everything into the think queue... */
KillWorkerThread();
/* Mark the plugin as being unloaded so future database calls will ignore threading... */
plugin->SetProperty("DisallowDBThreads", NULL);
Queue<IDBThreadOperation *> operations;
/* Run all of the think operations.
* Unlike the driver unloading example, we'll let these calls go through,
* since a plugin unloading is far more normal.
*/
Queue<IDBThreadOperation *>::iterator iter = m_ThinkQueue.begin();
Queue<IDBThreadOperation *> templist;
while (iter != m_ThinkQueue.end())
{
std::lock_guard<std::mutex> lock(m_Lock);
std::lock_guard<std::mutex> think_lock(m_ThinkLock);
for (auto iter = m_ThinkQueue.begin(); iter != m_ThinkQueue.end();)
IDBThreadOperation *op = (*iter);
if (op->GetOwner() == plugin->GetIdentity())
{
IDBThreadOperation *op = *iter;
auto owner = m_OperationOwners.find(op);
if (owner != m_OperationOwners.end() && owner->second == plugin->GetIdentity())
{
operations.push(op);
iter = m_ThinkQueue.erase(iter);
}
else
{
iter++;
}
templist.push(op);
iter = m_ThinkQueue.erase(iter);
} else {
iter++;
}
}
while (!operations.empty())
for (iter = templist.begin(); iter != templist.end(); iter++)
{
IDBThreadOperation *op = operations.first();
operations.pop();
FinalizeOperation(op, false);
IDBThreadOperation *op = (*iter);
op->RunThinkPart();
op->Destroy();
}
}
void DBManager::DiscardPluginOperations(IPlugin *plugin)
{
plugin->SetProperty("DisallowDBThreads", NULL);
CancelPluginOperations(plugin->GetIdentity());
}
void DBManager::OnPluginWillUnload(IPlugin *plugin)
{
if (ShouldDiscardPluginOperations())
DiscardPluginOperations(plugin);
else
WaitForPluginOperations(plugin);
}
std::string DBManager::GetDefaultDriverName()
{
ConfDbInfoList &list = m_Builder.GetConfigList();
+7 -14
View File
@@ -33,21 +33,22 @@
#define _INCLUDE_DATABASE_MANAGER_H_
#include "common_logic.h"
#include <vector>
#include <sh_vector.h>
#include <am-string.h>
#include <list>
#include <sh_list.h>
#include <IThreader.h>
#include <IPluginSys.h>
#include <condition_variable>
#include <memory>
#include <mutex>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include "sm_simple_prioqueue.h"
#include <am-refcounting.h>
#include "DatabaseConfBuilder.h"
using namespace SourceHook;
class DBManager :
public IDBManager,
public SMGlobalClass,
@@ -88,8 +89,6 @@ public:
IDBDriver *GetDefaultDriver();
std::string GetDefaultDriverName();
bool AddToThreadQueue(IDBThreadOperation *op, PrioQueueLevel prio);
bool ShouldDiscardPluginOperations();
void DiscardPluginOperations(IPlugin *plugin);
void RunFrame();
inline HandleType_t GetDatabaseType()
{
@@ -98,24 +97,18 @@ public:
private:
void ClearConfigs();
void KillWorkerThread();
void WaitForPluginOperations(IPlugin *plugin);
void CancelPluginOperations(IdentityToken_t *identity);
void FinalizeOperation(IDBThreadOperation *op, bool driver_unloading);
private:
std::vector<IDBDriver *> m_drivers;
CVector<IDBDriver *> m_drivers;
/* Threading stuff */
PrioQueue<IDBThreadOperation *> m_OpQueue;
Queue<IDBThreadOperation *> m_ThinkQueue;
std::vector<bool> m_drSafety; /* which drivers are safe? */
CVector<bool> m_drSafety; /* which drivers are safe? */
std::unique_ptr<std::thread> m_Worker;
std::condition_variable m_QueueEvent;
std::mutex m_ThinkLock;
std::mutex m_Lock;
bool m_Terminate;
IDBThreadOperation *m_ActiveOperation;
std::unordered_map<IDBThreadOperation *, IdentityToken_t *> m_OperationOwners;
std::unordered_set<IDBThreadOperation *> m_CancelledOperations;
DatabaseConfBuilder m_Builder;
HandleType_t m_DriverType;
-3
View File
@@ -127,8 +127,6 @@ SMCResult DatabaseConfBuilder::ReadSMC_KeyValue(const SMCStates *states, const c
}
} else if (strcmp(key, "database") == 0) {
m_ParseCurrent->database = value;
} else if (strcmp(key, "schema") == 0) {
m_ParseCurrent->schemaName = value;
} else if (strcmp(key, "host") == 0) {
m_ParseCurrent->host = value;
} else if (strcmp(key, "user") == 0) {
@@ -160,7 +158,6 @@ SMCResult DatabaseConfBuilder::ReadSMC_LeavingSection(const SMCStates *states)
m_ParseCurrent->info.host = m_ParseCurrent->host.c_str();
m_ParseCurrent->info.user = m_ParseCurrent->user.c_str();
m_ParseCurrent->info.pass = m_ParseCurrent->pass.c_str();
m_ParseCurrent->info.schemaName = m_ParseCurrent->schemaName.c_str();
/* Save it.. */
m_ParseCurrent->AddRef();
-1
View File
@@ -53,7 +53,6 @@ public:
std::string user;
std::string pass;
std::string database;
std::string schemaName;
IDBDriver *realDriver;
DatabaseInfo info;
};
+44 -7
View File
@@ -34,14 +34,12 @@
#include <stdarg.h>
#include "DebugReporter.h"
#include "Logger.h"
#include "sourcepawn/vm/base-runtime.h"
#include "sourcepawn/vm/environment.h"
DebugReport g_DbgReporter;
void DebugReport::OnSourceModAllInitialized()
{
g_pPawnEnv->SetDebugListener(this);
g_pSourcePawn->SetDebugListener(this);
}
void DebugReport::OnDebugSpew(const char *msg, ...)
@@ -70,10 +68,10 @@ void DebugReport::GenerateErrorVA(IPluginContext *ctx, cell_t func_idx, int err,
char buffer[512];
ke::SafeVsprintf(buffer, sizeof(buffer), message, ap);
const char *plname = pluginsys->FindPluginByContext(ctx)->GetFilename();
const char *plname = pluginsys->FindPluginByContext(ctx->GetContext())->GetFilename();
if (err >= 0) {
const char *error = g_pPawnEnv->GetErrorString(err);
const char *error = g_pSourcePawn2->GetErrorString(err);
if (error)
g_Logger.LogError("[SM] Plugin \"%s\" encountered error %d: %s", plname, err, error);
else
@@ -88,7 +86,7 @@ void DebugReport::GenerateErrorVA(IPluginContext *ctx, cell_t func_idx, int err,
{
func_idx >>= 1;
sp_public_t *function;
if (ctx->GetBaseRuntime()->GetPublicByIndex(func_idx, &function) == SP_ERROR_NONE)
if (ctx->GetRuntime()->GetPublicByIndex(func_idx, &function) == SP_ERROR_NONE)
{
g_Logger.LogError("[SM] Unable to call function \"%s\" due to above error(s).", function->name);
}
@@ -96,6 +94,45 @@ void DebugReport::GenerateErrorVA(IPluginContext *ctx, cell_t func_idx, int err,
}
}
void DebugReport::GenerateCodeError(IPluginContext *pContext, uint32_t code_addr, int err, const char *message, ...)
{
va_list ap;
char buffer[512];
va_start(ap, message);
ke::SafeVsprintf(buffer, sizeof(buffer), message, ap);
va_end(ap);
const char *plname = pluginsys->FindPluginByContext(pContext->GetContext())->GetFilename();
const char *error = g_pSourcePawn2->GetErrorString(err);
if (error)
{
g_Logger.LogError("[SM] Plugin \"%s\" encountered error %d: %s", plname, err, error);
} else {
g_Logger.LogError("[SM] Plugin \"%s\" encountered unknown error %d", plname, err);
}
g_Logger.LogError("[SM] %s", buffer);
IPluginDebugInfo *pDebug;
if ((pDebug = pContext->GetRuntime()->GetDebugInfo()) == NULL)
{
g_Logger.LogError("[SM] Debug mode is not enabled for \"%s\"", plname);
g_Logger.LogError("[SM] To enable debug mode, edit plugin_settings.cfg, or type: sm plugins debug %d on",
_GetPluginIndex(pContext));
return;
}
const char *name;
if (pDebug->LookupFunction(code_addr, &name) == SP_ERROR_NONE)
{
g_Logger.LogError("[SM] Unable to call function \"%s\" due to above error(s).", name);
} else {
g_Logger.LogError("[SM] Unable to call function (name unknown, address \"%x\").", code_addr);
}
}
int DebugReport::_GetPluginIndex(IPluginContext *ctx)
{
int id = 1;
@@ -136,7 +173,7 @@ void DebugReport::ReportError(const IErrorReport &report, IFrameIterator &iter)
{
if (iter.IsScriptedFrame())
{
IPlugin *plugin = pluginsys->FindPluginByContext(iter.Context());
IPlugin *plugin = pluginsys->FindPluginByContext(iter.Context()->GetContext());
if (plugin)
{
blame = plugin->GetFilename();
+1
View File
@@ -51,6 +51,7 @@ public:
// good enough, and only wants the supplemental logging provided here.
void GenerateError(IPluginContext *ctx, cell_t func_idx, int err, const char *message, ...);
void GenerateErrorVA(IPluginContext *ctx, cell_t func_idx, int err, const char *message, va_list ap);
void GenerateCodeError(IPluginContext *ctx, uint32_t code_addr, int err, const char *message, ...);
std::vector<std::string> GetStackTrace(IFrameIterator *iter);
private:
int _GetPluginIndex(IPluginContext *ctx);
+54 -49
View File
@@ -283,16 +283,6 @@ bool CExtension::PerformAPICheck(char *error, size_t maxlength)
ke::SafeStrcpy(error, maxlength, "No IExtensionInterface instance provided");
return false;
}
if (m_pAPI->GetExtensionVersion() == 10) {
ke::SafeSprintf(error, maxlength, "Extension version %d is not supported", m_pAPI->GetExtensionVersion());
return false;
}
if (m_pAPI->GetExtensionVersion() < SMINTERFACE_EXTENSIONAPI_VERSION_MIN) {
ke::SafeSprintf(error, maxlength, "Extension version is too old to load (%d, max is %d)", m_pAPI->GetExtensionVersion(), SMINTERFACE_EXTENSIONAPI_VERSION_MIN);
return false;
}
if (m_pAPI->GetExtensionVersion() > SMINTERFACE_EXTENSIONAPI_VERSION)
{
@@ -356,7 +346,7 @@ void CExtension::MarkAllLoaded()
void CExtension::AddPlugin(CPlugin *pPlugin)
{
/* Unfortunately we have to do this :( */
if (std::find(m_Dependents.begin(), m_Dependents.end(), pPlugin) == m_Dependents.end())
if (m_Dependents.find(pPlugin) == m_Dependents.end())
{
m_Dependents.push_back(pPlugin);
}
@@ -399,7 +389,7 @@ bool CLocalExtension::IsLoaded()
void CExtension::AddDependency(const IfaceInfo *pInfo)
{
if (std::find(m_Deps.begin(), m_Deps.end(), *pInfo) == m_Deps.end())
if (m_Deps.find(*pInfo) == m_Deps.end())
{
m_Deps.push_back(*pInfo);
}
@@ -411,7 +401,8 @@ void CExtension::AddChildDependent(CExtension *pOther, SMInterface *iface)
info.iface = iface;
info.owner = pOther;
for (auto iter = m_ChildDeps.begin();
List<IfaceInfo>::iterator iter;
for (iter = m_ChildDeps.begin();
iter != m_ChildDeps.end();
iter++)
{
@@ -491,9 +482,11 @@ void CExtensionManager::OnSourceModShutdown()
void CExtensionManager::Shutdown()
{
while (m_Libs.begin() != m_Libs.end())
List<CExtension *>::iterator iter;
while ((iter = m_Libs.begin()) != m_Libs.end())
{
UnloadExtension((*m_Libs.begin()));
UnloadExtension((*iter));
}
}
@@ -582,13 +575,14 @@ IExtension *CExtensionManager::LoadAutoExtension(const char *path, bool bErrorOn
IExtension *CExtensionManager::FindExtensionByFile(const char *file)
{
List<CExtension *>::iterator iter;
CExtension *pExt;
/* Chomp off the path */
char lookup[PLATFORM_MAX_PATH];
libsys->GetFileFromPath(lookup, sizeof(lookup), file);
for (auto iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
{
pExt = (*iter);
if (pExt->IsSameFile(lookup))
@@ -602,11 +596,12 @@ IExtension *CExtensionManager::FindExtensionByFile(const char *file)
IExtension *CExtensionManager::FindExtensionByName(const char *ext)
{
List<CExtension *>::iterator iter;
CExtension *pExt;
IExtensionInterface *pAPI;
const char *name;
for (auto iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
{
pExt = (*iter);
if (!pExt->IsLoaded())
@@ -715,7 +710,9 @@ void CExtensionManager::BindChildPlugin(IExtension *pParent, SMPlugin *pPlugin)
void CExtensionManager::OnPluginDestroyed(IPlugin *plugin)
{
for (auto iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
List<CExtension *>::iterator iter;
for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
{
(*iter)->DropRefsTo(static_cast<CPlugin *>(plugin));
}
@@ -728,7 +725,7 @@ CExtension *CExtensionManager::FindByOrder(unsigned int num)
return NULL;
}
auto iter = m_Libs.begin();
List<CExtension *>::iterator iter = m_Libs.begin();
while (iter != m_Libs.end())
{
@@ -749,8 +746,7 @@ bool CExtensionManager::UnloadExtension(IExtension *_pExt)
CExtension *pExt = (CExtension *)_pExt;
auto iter = std::find(m_Libs.begin(), m_Libs.end(), pExt);
if (iter == m_Libs.end())
if (m_Libs.find(pExt) == m_Libs.end())
return false;
/* Tell it to unload */
@@ -764,13 +760,13 @@ bool CExtensionManager::UnloadExtension(IExtension *_pExt)
g_ShareSys.RemoveInterfaces(_pExt);
m_Libs.remove(pExt);
std::list<CExtension *> UnloadQueue;
List<CExtension *> UnloadQueue;
/* Handle dependencies */
if (pExt->IsLoaded())
{
/* Unload any dependent plugins */
auto p_iter = pExt->m_Dependents.begin();
List<CPlugin *>::iterator p_iter = pExt->m_Dependents.begin();
while (p_iter != pExt->m_Dependents.end())
{
/* We have to manually unlink ourselves here, since we're no longer being managed */
@@ -778,7 +774,8 @@ bool CExtensionManager::UnloadExtension(IExtension *_pExt)
p_iter = pExt->m_Dependents.erase(p_iter);
}
for (auto s_iter = pExt->m_Libraries.begin();
List<String>::iterator s_iter;
for (s_iter = pExt->m_Libraries.begin();
s_iter != pExt->m_Libraries.end();
s_iter++)
{
@@ -786,9 +783,10 @@ bool CExtensionManager::UnloadExtension(IExtension *_pExt)
}
/* Notify and/or unload all dependencies */
List<CExtension *>::iterator c_iter;
CExtension *pDep;
IExtensionInterface *pAPI;
for (auto c_iter = m_Libs.begin(); c_iter != m_Libs.end(); c_iter++)
for (c_iter = m_Libs.begin(); c_iter != m_Libs.end(); c_iter++)
{
pDep = (*c_iter);
if ((pAPI=pDep->GetAPI()) == NULL)
@@ -797,7 +795,7 @@ bool CExtensionManager::UnloadExtension(IExtension *_pExt)
continue;
/* Now, get its dependency list */
bool dropped = false;
auto i_iter = pDep->m_Deps.begin();
List<IfaceInfo>::iterator i_iter = pDep->m_Deps.begin();
while (i_iter != pDep->m_Deps.end())
{
if ((*i_iter).owner == _pExt)
@@ -852,7 +850,8 @@ bool CExtensionManager::UnloadExtension(IExtension *_pExt)
pExt->Unload();
delete pExt;
for (auto iter=UnloadQueue.begin(); iter!=UnloadQueue.end(); iter++)
List<CExtension *>::iterator iter;
for (iter=UnloadQueue.begin(); iter!=UnloadQueue.end(); iter++)
{
/* NOTE: This is safe because the unload function backs out of anything not present */
UnloadExtension((*iter));
@@ -863,9 +862,10 @@ bool CExtensionManager::UnloadExtension(IExtension *_pExt)
void CExtensionManager::MarkAllLoaded()
{
List<CExtension *>::iterator iter;
CExtension *pExt;
for (auto iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
{
pExt = (*iter);
if (!pExt->IsLoaded())
@@ -900,6 +900,7 @@ void CExtensionManager::OnRootConsoleCommand(const char *cmdname, const ICommand
const char *cmd = command->Arg(2);
if (strcmp(cmd, "list") == 0)
{
List<CExtension *>::iterator iter;
CExtension *pExt;
unsigned int num = 1;
@@ -921,7 +922,7 @@ void CExtensionManager::OnRootConsoleCommand(const char *cmdname, const ICommand
break;
}
}
for (auto iter = m_Libs.begin(); iter != m_Libs.end(); iter++,num++)
for (iter = m_Libs.begin(); iter != m_Libs.end(); iter++,num++)
{
pExt = (*iter);
if (pExt->IsLoaded())
@@ -1010,7 +1011,7 @@ void CExtensionManager::OnRootConsoleCommand(const char *cmdname, const ICommand
return;
}
auto iter = m_Libs.begin();
List<CExtension *>::iterator iter = m_Libs.begin();
CExtension *pExt = NULL;
while (iter != m_Libs.end())
{
@@ -1113,21 +1114,23 @@ void CExtensionManager::OnRootConsoleCommand(const char *cmdname, const ICommand
}
else
{
std::list<CPlugin *> plugins;
List<CPlugin *> plugins;
if (pExt->m_ChildDeps.size())
{
rootmenu->ConsolePrint("[SM] Unloading %s will unload the following extensions: ", pExt->GetFilename());
List<CExtension *>::iterator iter;
CExtension *pOther;
/* Get list of all extensions */
for (auto iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
{
List<IfaceInfo>::iterator i_iter;
pOther = (*iter);
if (!pOther->IsLoaded() || pOther == pExt)
{
continue;
}
/* Get their dependencies */
for (auto i_iter=pOther->m_Deps.begin();
for (i_iter=pOther->m_Deps.begin();
i_iter!=pOther->m_Deps.end();
i_iter++)
{
@@ -1141,12 +1144,12 @@ void CExtensionManager::OnRootConsoleCommand(const char *cmdname, const ICommand
{
rootmenu->ConsolePrint(" -> %s", pOther->GetFilename());
/* Add to plugin unload list */
for (auto p_iter=pOther->m_Dependents.begin();
List<CPlugin *>::iterator p_iter;
for (p_iter=pOther->m_Dependents.begin();
p_iter!=pOther->m_Dependents.end();
p_iter++)
{
auto lookup = std::find(plugins.begin(), plugins.end(), (*p_iter));
if (lookup == plugins.end())
if (plugins.find((*p_iter)) == plugins.end())
{
plugins.push_back((*p_iter));
}
@@ -1158,17 +1161,17 @@ void CExtensionManager::OnRootConsoleCommand(const char *cmdname, const ICommand
if (pExt->m_Dependents.size())
{
rootmenu->ConsolePrint("[SM] Unloading %s will unload the following plugins: ", pExt->GetFilename());
List<CPlugin *>::iterator iter;
CPlugin *pPlugin;
for (auto iter = pExt->m_Dependents.begin(); iter != pExt->m_Dependents.end(); iter++)
for (iter = pExt->m_Dependents.begin(); iter != pExt->m_Dependents.end(); iter++)
{
pPlugin = (*iter);
auto lookup = std::find(plugins.begin(), plugins.end(), pPlugin);
if (lookup == plugins.end())
if (plugins.find(pPlugin) == plugins.end())
{
plugins.push_back(pPlugin);
}
}
for (auto iter = plugins.begin(); iter != plugins.end(); iter++)
for (iter = plugins.begin(); iter != plugins.end(); iter++)
{
pPlugin = (*iter);
rootmenu->ConsolePrint(" -> %s", pPlugin->GetFilename());
@@ -1264,12 +1267,12 @@ bool CExtensionManager::LibraryExists(const char *library)
{
CExtension *pExt;
for (auto iter = m_Libs.begin();
for (List<CExtension *>::iterator iter = m_Libs.begin();
iter != m_Libs.end();
iter++)
{
pExt = (*iter);
for (auto s_iter = pExt->m_Libraries.begin();
for (List<String>::iterator s_iter = pExt->m_Libraries.begin();
s_iter != pExt->m_Libraries.end();
s_iter++)
{
@@ -1312,8 +1315,9 @@ IExtension *CExtensionManager::LoadExternal(IExtensionInterface *pInterface,
void CExtensionManager::CallOnCoreMapStart(edict_t *pEdictList, int edictCount, int clientMax)
{
IExtensionInterface *pAPI;
List<CExtension *>::iterator iter;
for (auto iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
{
if ((pAPI = (*iter)->GetAPI()) == NULL)
{
@@ -1329,8 +1333,9 @@ void CExtensionManager::CallOnCoreMapStart(edict_t *pEdictList, int edictCount,
void CExtensionManager::CallOnCoreMapEnd()
{
IExtensionInterface *pAPI;
List<CExtension *>::iterator iter;
for (auto iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
for (iter=m_Libs.begin(); iter!=m_Libs.end(); iter++)
{
if ((pAPI = (*iter)->GetAPI()) == NULL)
{
@@ -1343,17 +1348,17 @@ void CExtensionManager::CallOnCoreMapEnd()
}
}
const std::vector<IExtension *> *CExtensionManager::ListExtensions()
const CVector<IExtension *> *CExtensionManager::ListExtensions()
{
std::vector<IExtension *> *list = new std::vector<IExtension *>();
for (auto iter = m_Libs.begin(); iter != m_Libs.end(); iter++)
CVector<IExtension *> *list = new CVector<IExtension *>();
for (List<CExtension *>::iterator iter = m_Libs.begin(); iter != m_Libs.end(); iter++)
list->push_back(*iter);
return list;
}
void CExtensionManager::FreeExtensionList(const std::vector<IExtension *> *list)
void CExtensionManager::FreeExtensionList(const CVector<IExtension *> *list)
{
delete const_cast<std::vector<IExtension *> *>(list);
delete const_cast<CVector<IExtension *> *>(list);
}
bool CLocalExtension::IsSameFile(const char *file)
+14 -13
View File
@@ -34,8 +34,8 @@
#include <IExtensionSys.h>
#include <ILibrarySys.h>
#include <list>
#include <string>
#include <sh_list.h>
#include <sh_string.h>
#include "common_logic.h"
#include <IPluginSys.h>
#include <IRootConsoleMenu.h>
@@ -46,6 +46,7 @@
class CPlayer;
using namespace SourceMod;
using namespace SourceHook;
class CExtension;
@@ -94,14 +95,14 @@ protected:
protected:
IdentityToken_t *m_pIdentToken;
IExtensionInterface *m_pAPI;
std::string m_File;
std::string m_RealFile;
std::string m_Path;
std::string m_Error;
std::list<IfaceInfo> m_Deps; /** Dependencies */
std::list<IfaceInfo> m_ChildDeps; /** Children who might depend on us */
std::list<SMInterface *> m_Interfaces;
std::list<std::string> m_Libraries;
String m_File;
String m_RealFile;
String m_Path;
String m_Error;
List<IfaceInfo> m_Deps; /** Dependencies */
List<IfaceInfo> m_ChildDeps; /** Children who might depend on us */
List<SMInterface *> m_Interfaces;
List<String> m_Libraries;
unsigned int unload_code;
bool m_bFullyLoaded;
bool m_bRequired;
@@ -177,8 +178,8 @@ public:
void CallOnCoreMapStart(edict_t *pEdictList, int edictCount, int clientMax);
void CallOnCoreMapEnd();
void AddRawDependency(IExtension *ext, IdentityToken_t *other, void *iface);
const std::vector<IExtension *> *ListExtensions();
void FreeExtensionList(const std::vector<IExtension *> *list);
const CVector<IExtension *> *ListExtensions();
void FreeExtensionList(const CVector<IExtension *> *list);
public:
CExtension *GetExtensionFromIdent(IdentityToken_t *ptr);
void Shutdown();
@@ -190,7 +191,7 @@ public:
private:
CExtension *FindByOrder(unsigned int num);
private:
std::list<CExtension *> m_Libs;
List<CExtension *> m_Libs;
};
extern CExtensionManager g_Extensions;
+406 -196
View File
@@ -36,7 +36,6 @@
#include <ReentrantList.h>
using namespace ke;
using sp::CallArgs;
CForwardManager g_Forwards;
@@ -138,15 +137,6 @@ IForward *CForwardManager::FindForward(const char *name, IChangeableForward **if
void CForwardManager::ReleaseForward(IForward *aForward)
{
CForward *fwd = static_cast<CForward *>(aForward);
if (fwd->m_ExecDepth > 0)
{
/* Still executing (possibly nested); defer the real deletion until
* the outermost Execute() call unwinds. */
fwd->m_deleted = true;
return;
}
m_managed.remove(fwd);
m_unmanaged.remove(fwd);
delete fwd;
@@ -174,22 +164,24 @@ void CForwardManager::OnPluginPauseChange(IPlugin *plugin, bool paused)
*************************************/
CForward::CForward(ExecType et, const char *name, const ParamType *types, unsigned num_params)
: m_addresses(0),
m_numparams(0),
: m_numparams(0),
m_varargs(0),
m_ExecType(et),
m_errstate(SP_ERROR_NONE),
m_ExecDepth(0),
m_deleted(false)
m_curparam(0),
m_errstate(SP_ERROR_NONE)
{
ke::SafeStrcpy(m_name, sizeof(m_name), name ? name : "");
for (unsigned i = 0; i < num_params; i++) {
for (unsigned i = 0; i < num_params; i++)
m_types[i] = types[i];
if (types[i] == Param_SMAddress)
m_addresses |= 1u << i;
}
m_numparams = num_params;
if (num_params && types[num_params - 1] == Param_VarArgs) {
m_varargs = num_params;
m_numparams = num_params - 1;
} else {
m_varargs = 0;
m_numparams = num_params;
}
}
CForward *CForward::CreateForward(const char *name, ExecType et, unsigned int num_params, const ParamType *types, va_list ap)
@@ -204,273 +196,491 @@ CForward *CForward::CreateForward(const char *name, ExecType et, unsigned int nu
if (types == NULL && num_params)
{
for (unsigned int i=0; i<num_params; i++)
{
_types[i] = (ParamType)va_arg(ap, int);
if (_types[i] == Param_VarArgs && (i != num_params - 1))
{
return NULL;
}
}
types = _types;
} else {
for (unsigned int i=0; i<num_params; i++)
{
_types[i] = types[i];
if (types[i] == Param_VarArgs && (i != num_params - 1))
{
return NULL;
}
}
}
/* First parameter can never be varargs */
if (num_params && _types[0] == Param_VarArgs)
{
return NULL;
}
return new CForward(et, name, _types, num_params);
}
bool InvokePluginFunction(IPluginFunction *func, const CallArgs& args, AddressMask addresses, cell_t *result)
{
// Plugins compiled before SourceMod 1.13 take an Address as one cell and cannot read an int64 argument. Like DHooks,
// pass them the low 32 bits of an Address instead. Any other int64 has no single cell equivalent, so they cannot be
// called with one.
bool has_int64 = false;
for (uint32_t i = 0; i < args.argc; i++)
has_int64 |= args.argv[i].type == CallArgs::ARG_INT64;
if (!has_int64 || func->GetParentRuntime()->FindPubvarByName("__Int64_Address__", nullptr) == SP_ERROR_NONE)
return func->Invoke(args, result);
CallArgs legacy_args = args;
for (uint32_t i = 0; i < legacy_args.argc; i++) {
auto& arg = legacy_args.argv[i];
if (arg.type != CallArgs::ARG_INT64)
continue;
if (!(addresses & (1u << i))) {
IPluginContext *ctx = func->GetParentRuntime()->GetDefaultContext();
IPlugin *plugin = pluginsys->FindPluginByContext(ctx);
ctx->ReportError("Plugin \"%s\" was compiled before SourceMod 1.13 and cannot receive int64 argument %u",
plugin ? plugin->GetFilename() : "<unknown>", i + 1);
return false;
}
arg.u.value = static_cast<cell_t>(arg.u.i64);
arg.type = CallArgs::ARG_CELL;
arg.flags = 0;
}
return func->Invoke(legacy_args, result);
}
bool CForward::ProcessArguments(const CallArgs& args) {
if (args.error)
return !SetError(SP_ERROR_PARAMS_MAX);
for (uint32_t i = 0; i < args.argc; i++) {
if (i >= m_numparams)
return !SetError(SP_ERROR_PARAM);
ParamType pt = m_types[i];
if (pt == Param_Any)
continue;
auto& arg = args.argv[i];
switch (arg.type) {
case CallArgs::ARG_CELL:
if (arg.flags & CallArgs::FLAG_CELL_TYPE_FLOAT) {
if (pt != Param_Float)
return !SetError(SP_ERROR_PARAM);
} else {
if (pt != Param_Cell)
return !SetError(SP_ERROR_PARAM);
}
break;
case CallArgs::ARG_CELL_BY_REF:
if (arg.flags & CallArgs::FLAG_CELL_TYPE_FLOAT) {
if (pt != Param_FloatByRef)
return !SetError(SP_ERROR_PARAM);
} else {
if (pt != Param_CellByRef)
return !SetError(SP_ERROR_PARAM);
}
break;
case CallArgs::ARG_ARRAY:
if (pt != Param_Array)
return !SetError(SP_ERROR_PARAM);
break;
case CallArgs::ARG_CHAR_ARRAY:
if (pt != Param_String)
return !SetError(SP_ERROR_PARAM);
break;
case CallArgs::ARG_INT64:
if (pt != Param_Int64 && pt != Param_SMAddress)
return !SetError(SP_ERROR_PARAM);
break;
}
}
return true;
}
int CForward::Execute(cell_t *result, IForwardFilter *filter)
{
auto args = std::move(default_args_);
default_args_.Reset();
return Execute(args, result, filter);
}
int CForward::Execute(const sp::CallArgs& in_args, cell_t *result, IForwardFilter *filter)
{
if (m_errstate) {
if (m_errstate)
{
int err = m_errstate;
Cancel();
return err;
}
auto args = in_args;
unsigned int success = 0;
cell_t cur_result = 0;
cell_t high_result = 0;
cell_t low_result = 0;
cell_t cur_result = 0;
int err;
unsigned int success=0;
unsigned int num_params = m_curparam;
FwdParamInfo temp_info[SP_MAX_EXEC_PARAMS];
if (!ProcessArguments(args)) {
int err = m_errstate;
Cancel();
return err;
}
m_ExecDepth++;
/* Save local, reset */
memcpy(temp_info, m_params, sizeof(m_params));
m_curparam = 0;
for (FuncIter iter(m_functions); !iter.done(); iter.next())
{
IPluginFunction *func = (*iter);
if (filter)
filter->Preprocess(func, args);
filter->Preprocess(func, temp_info);
if (func->GetParentRuntime()->IsPaused())
continue;
ExceptionHandler eh(func->GetParentRuntime());
if (!InvokePluginFunction(func, args, m_addresses, &cur_result))
continue;
success++;
switch (m_ExecType)
for (unsigned int i=0; i<num_params; i++)
{
case ET_Event:
if (cur_result > high_result)
high_result = cur_result;
break;
case ET_Hook:
if (cur_result > high_result)
high_result = cur_result;
break;
case ET_LowEvent:
/* Check if the current result is the lowest so far (or if it's the first result) */
if (cur_result < low_result || success == 1)
low_result = cur_result;
break;
default:
break;
}
int err = SP_ERROR_PARAM;
FwdParamInfo *param = &temp_info[i];
if (m_ExecType == ET_Hook && (ResultType)high_result == Pl_Stop)
break;
ParamType type;
if (i >= m_numparams || m_types[i] == Param_Any)
type = param->pushedas;
else
type = m_types[i];
if ((i >= m_numparams) || (type & SP_PARAMFLAG_BYREF))
{
/* If we're byref or we're vararg, we always push everything by ref.
* Even if they're byval, we must push them byref.
*/
err = _ExecutePushRef(func, type, param);
}
else
{
/* If we're not byref or not vararg, our job is a bit easier. */
assert(type == Param_Cell || type == Param_Float);
err = func->PushCell(param->val);
}
if (err != SP_ERROR_NONE)
{
g_DbgReporter.GenerateError(func->GetParentContext(),
func->GetFunctionID(),
err,
"Failed to push parameter while executing forward");
continue;
}
}
/* Call the function and deal with the return value. */
if ((err=func->Execute(&cur_result)) == SP_ERROR_NONE)
{
success++;
switch (m_ExecType)
{
case ET_Event:
{
if (cur_result > high_result)
{
high_result = cur_result;
}
break;
}
case ET_Hook:
{
if (cur_result > high_result)
{
high_result = cur_result;
if ((ResultType)high_result == Pl_Stop)
{
goto done;
}
}
break;
}
case ET_LowEvent:
{
/* Check if the current result is the lowest so far (or if it's the first result) */
if (cur_result < low_result || success == 1)
{
low_result = cur_result;
}
break;
}
default:
{
break;
}
}
}
}
done:
if (success)
{
switch (m_ExecType)
{
case ET_Ignore:
case ET_Ignore:
{
cur_result = 0;
break;
case ET_Event:
case ET_Hook:
}
case ET_Event:
case ET_Hook:
{
cur_result = high_result;
break;
case ET_LowEvent:
}
case ET_LowEvent:
{
cur_result = low_result;
break;
default:
}
default:
{
break;
}
}
if (result)
{
*result = cur_result;
}
/* If a callback we just invoked freed this forward's handle (e.g. the
* plugin deletes its own private forward from within one of its own
* callbacks), the actual delete is deferred to here so we don't touch
* freed memory by continuing to use "this" above. */
if (--m_ExecDepth == 0 && m_deleted)
{
g_Forwards.ReleaseForward(this);
return SP_ERROR_NONE;
}
}
return SP_ERROR_NONE;
}
int CForward::_ExecutePushRef(IPluginFunction *func, ParamType type, FwdParamInfo *param)
{
/* If we're byref or we're vararg, we always push everything by ref.
* Even if they're byval, we must push them byref.
*/
int err;
IPluginRuntime *runtime = func->GetParentRuntime();
switch (type)
{
case Param_String:
// Normal string was pushed.
if (!param->isnull)
return func->PushStringEx((char *)param->byref.orig_addr, param->byref.cells, param->byref.sz_flags, param->byref.flags);
// If NULL_STRING was pushed, push the reference to the pubvar of the callee instead.
uint32_t null_string_idx;
err = runtime->FindPubvarByName("NULL_STRING", &null_string_idx);
if (err)
return err;
cell_t null_string;
err = runtime->GetPubvarAddrs(null_string_idx, &null_string, nullptr);
if (err)
return err;
return func->PushCell(null_string);
case Param_Float:
case Param_Cell:
return func->PushCellByRef(&param->val);
default:
assert(type == Param_Array || type == Param_FloatByRef || type == Param_CellByRef);
// No NULL_VECTOR was pushed.
if (type != Param_Array || !param->isnull)
return func->PushArray(param->byref.orig_addr, param->byref.cells, param->byref.flags);
// If NULL_VECTOR was pushed, push the reference to the pubvar of the callee instead.
uint32_t null_vector_idx;
err = runtime->FindPubvarByName("NULL_VECTOR", &null_vector_idx);
if (err)
return err;
cell_t null_vector;
err = runtime->GetPubvarAddrs(null_vector_idx, &null_vector, nullptr);
if (err)
return err;
return func->PushCell(null_vector);
}
}
int CForward::PushCell(cell_t cell)
{
default_args_.PushCell(cell);
if (default_args_.error)
return SetError(SP_ERROR_PARAMS_MAX);
return SP_ERROR_NONE;
}
if (m_curparam < m_numparams)
{
if (m_types[m_curparam] == Param_Any)
{
m_params[m_curparam].pushedas = Param_Cell;
} else if (m_types[m_curparam] != Param_Cell) {
return SetError(SP_ERROR_PARAM);
}
} else {
if (!m_varargs || m_numparams > SP_MAX_EXEC_PARAMS)
{
return SetError(SP_ERROR_PARAMS_MAX);
}
m_params[m_curparam].pushedas = Param_Cell;
}
m_params[m_curparam].isnull = false;
m_params[m_curparam++].val = cell;
int CForward::PushInt64(int64_t value)
{
default_args_.PushInt64(value);
if (default_args_.error)
return SetError(SP_ERROR_PARAMS_MAX);
return SP_ERROR_NONE;
}
int CForward::PushFloat(float number)
{
default_args_.PushFloat(number);
if (default_args_.error)
return SetError(SP_ERROR_PARAMS_MAX);
if (m_curparam < m_numparams)
{
if (m_types[m_curparam] == Param_Any)
{
m_params[m_curparam].pushedas = Param_Float;
} else if (m_types[m_curparam] != Param_Float) {
return SetError(SP_ERROR_PARAM);
}
} else {
if (!m_varargs || m_numparams > SP_MAX_EXEC_PARAMS)
{
return SetError(SP_ERROR_PARAMS_MAX);
}
m_params[m_curparam].pushedas = Param_Float;
}
m_params[m_curparam].isnull = false;
m_params[m_curparam++].val = *(cell_t *)&number;
return SP_ERROR_NONE;
}
int CForward::PushCellByRef(cell_t *cell, int flags)
{
default_args_.PushCellByRef(cell, flags);
if (default_args_.error)
return SetError(SP_ERROR_PARAMS_MAX);
if (m_curparam < m_numparams)
{
if (m_types[m_curparam] == Param_Any)
{
m_params[m_curparam].pushedas = Param_CellByRef;
} else if (m_types[m_curparam] != Param_CellByRef) {
return SetError(SP_ERROR_PARAM);
}
} else {
if (!m_varargs || m_numparams > SP_MAX_EXEC_PARAMS)
{
return SetError(SP_ERROR_PARAMS_MAX);
}
m_params[m_curparam].pushedas = Param_CellByRef;
}
_Int_PushArray(cell, 1, flags);
m_curparam++;
return SP_ERROR_NONE;
}
int CForward::PushFloatByRef(float *num, int flags)
{
default_args_.PushFloatByRef(num, flags);
if (default_args_.error)
return SetError(SP_ERROR_PARAMS_MAX);
if (m_curparam < m_numparams)
{
if (m_types[m_curparam] == Param_Any)
{
m_params[m_curparam].pushedas = Param_FloatByRef;
} else if (m_types[m_curparam] != Param_FloatByRef) {
return SetError(SP_ERROR_PARAM);
}
} else {
if (!m_varargs || m_numparams > SP_MAX_EXEC_PARAMS)
{
return SetError(SP_ERROR_PARAMS_MAX);
}
m_params[m_curparam].pushedas = Param_FloatByRef;
}
_Int_PushArray((cell_t *)num, 1, flags);
m_curparam++;
return SP_ERROR_NONE;
}
void CForward::_Int_PushArray(cell_t *inarray, unsigned int cells, int flags)
{
m_params[m_curparam].byref.cells = cells;
m_params[m_curparam].byref.flags = flags;
m_params[m_curparam].byref.orig_addr = inarray;
m_params[m_curparam].isnull = false;
}
int CForward::PushArray(cell_t *inarray, unsigned int cells, int flags)
{
if (!inarray) {
return SetError(SP_ERROR_PARAM);
/* Push a reference to the NULL_VECTOR pubvar if NULL was passed. */
if (!inarray)
{
/* Make sure this was intentional. */
if (cells == 3)
{
return PushNullVector();
} else {
/* We don't allow this here */
return SetError(SP_ERROR_PARAM);
}
}
default_args_.PushArray(inarray, cells, flags);
if (default_args_.error)
return SetError(SP_ERROR_PARAMS_MAX);
if (m_curparam < m_numparams)
{
if (m_types[m_curparam] == Param_Any)
{
m_params[m_curparam].pushedas = Param_Array;
} else if (m_types[m_curparam] != Param_Array) {
return SetError(SP_ERROR_PARAM);
}
} else {
if (!m_varargs || m_curparam > SP_MAX_EXEC_PARAMS)
{
return SetError(SP_ERROR_PARAMS_MAX);
}
m_params[m_curparam].pushedas = Param_Array;
}
_Int_PushArray(inarray, cells, flags);
m_curparam++;
return SP_ERROR_NONE;
}
void CForward::_Int_PushString(cell_t *inarray, unsigned int cells, int sz_flags, int cp_flags)
{
m_params[m_curparam].byref.cells = cells; /* Notice this contains the char count not cell count */
m_params[m_curparam].byref.flags = cp_flags;
m_params[m_curparam].byref.orig_addr = inarray;
m_params[m_curparam].byref.sz_flags = sz_flags;
m_params[m_curparam].isnull = false;
}
int CForward::PushString(const char *string)
{
if (!string) {
return SetError(SP_ERROR_PARAM);
/* Push a reference to the NULL_STRING pubvar if NULL was passed. */
if (!string)
{
return PushNullString();
}
default_args_.PushString(string);
if (default_args_.error)
return SetError(SP_ERROR_PARAMS_MAX);
if (m_curparam < m_numparams)
{
if (m_types[m_curparam] == Param_Any)
{
m_params[m_curparam].pushedas = Param_String;
} else if (m_types[m_curparam] != Param_String) {
return SetError(SP_ERROR_PARAM);
}
} else {
if (!m_varargs || m_curparam > SP_MAX_EXEC_PARAMS)
{
return SetError(SP_ERROR_PARAMS_MAX);
}
m_params[m_curparam].pushedas = Param_String;
}
_Int_PushString((cell_t *)string, strlen(string)+1, SM_PARAM_STRING_COPY, 0);
m_curparam++;
return SP_ERROR_NONE;
}
int CForward::PushStringEx(char *buffer, size_t length, int sz_flags, int cp_flags)
{
default_args_.PushString(buffer, length, sz_flags | cp_flags);
if (default_args_.error)
return SetError(SP_ERROR_PARAMS_MAX);
if (m_curparam < m_numparams)
{
if (m_types[m_curparam] == Param_Any)
{
m_params[m_curparam].pushedas = Param_String;
} else if (m_types[m_curparam] != Param_String) {
return SetError(SP_ERROR_PARAM);
}
} else {
if (!m_varargs || m_curparam > SP_MAX_EXEC_PARAMS)
{
return SetError(SP_ERROR_PARAMS_MAX);
}
m_params[m_curparam].pushedas = Param_String;
}
_Int_PushString((cell_t *)buffer, length, sz_flags, cp_flags);
m_curparam++;
return SP_ERROR_NONE;
}
int CForward::PushNullString()
{
if (m_curparam < m_numparams)
{
if (m_types[m_curparam] == Param_Any)
{
m_params[m_curparam].pushedas = Param_String;
} else if (m_types[m_curparam] != Param_String) {
return SetError(SP_ERROR_PARAM);
}
} else {
if (!m_varargs || m_numparams > SP_MAX_EXEC_PARAMS)
{
return SetError(SP_ERROR_PARAMS_MAX);
}
m_params[m_curparam].pushedas = Param_String;
}
m_params[m_curparam++].isnull = true;
return SP_ERROR_NONE;
}
int CForward::PushNullVector()
{
if (m_curparam < m_numparams)
{
if (m_types[m_curparam] == Param_Any)
{
m_params[m_curparam].pushedas = Param_Array;
} else if (m_types[m_curparam] != Param_Array) {
return SetError(SP_ERROR_PARAM);
}
} else {
if (!m_varargs || m_numparams > SP_MAX_EXEC_PARAMS)
{
return SetError(SP_ERROR_PARAMS_MAX);
}
m_params[m_curparam].pushedas = Param_Array;
}
m_params[m_curparam++].isnull = true;
return SP_ERROR_NONE;
}
void CForward::Cancel()
{
default_args_.Reset();
if (!m_curparam)
{
return;
}
m_curparam = 0;
m_errstate = SP_ERROR_NONE;
}
@@ -516,8 +726,8 @@ bool CForward::RemoveFunction(IPluginFunction *func)
}
/* Cancel a call, if any */
if (found || default_args_.argc)
default_args_.Reset();
if (found || m_curparam)
func->Cancel();
return found;
}
@@ -537,7 +747,7 @@ unsigned int CForward::RemoveFunctionsOfPlugin(IPlugin *plugin)
bool CForward::AddFunction(IPluginFunction *func)
{
if (default_args_.argc)
if (m_curparam)
return false;
if (func->IsRunnable())
+10 -24
View File
@@ -39,18 +39,9 @@ typedef ReentrantList<IPluginFunction *>::iterator FuncIter;
/* :TODO: a global name max define for sourcepawn, should mirror compiler's sNAMEMAX */
#define FORWARDS_NAME_MAX 64
// The argument positions that hold an Address, one bit per position.
using AddressMask = uint32_t;
static_assert(SP_MAX_EXEC_PARAMS <= sizeof(AddressMask) * 8, "AddressMask must have a bit for every parameter");
// Invokes a plugin function, passing the given Address arguments as one cell to plugins compiled before SourceMod 1.13,
// and refusing to pass those plugins any other int64 argument.
bool InvokePluginFunction(IPluginFunction *func, const sp::CallArgs& args, AddressMask addresses, cell_t *result);
class CForward : public IChangeableForward
{
friend class CForwardManager;
public: //IForward
public: //ICallable
virtual int PushCell(cell_t cell);
virtual int PushCellByRef(cell_t *cell, int flags);
virtual int PushFloat(float number);
@@ -58,13 +49,12 @@ public: //IForward
virtual int PushArray(cell_t *inarray, unsigned int cells, int flags);
virtual int PushString(const char *string);
virtual int PushStringEx(char *buffer, size_t length, int sz_flags, int cp_flags);
virtual int PushInt64(int64_t value);
virtual void Cancel();
public: //IForward
virtual const char *GetForwardName();
virtual unsigned int GetFunctionCount();
virtual ExecType GetExecType();
virtual int Execute(cell_t *result, IForwardFilter *filter);
virtual int Execute(const sp::CallArgs& args, cell_t *result = nullptr, IForwardFilter *filter = nullptr);
public: //IChangeableForward
virtual bool RemoveFunction(IPluginFunction *func);
virtual unsigned int RemoveFunctionsOfPlugin(IPlugin *plugin);
@@ -82,35 +72,31 @@ private:
CForward(ExecType et, const char *name,
const ParamType *types, unsigned num_params);
int PushNullString();
int PushNullVector();
int _ExecutePushRef(IPluginFunction *func, ParamType type, FwdParamInfo *param);
void _Int_PushArray(cell_t *inarray, unsigned int cells, int flags);
void _Int_PushString(cell_t *inarray, unsigned int cells, int sz_flags, int cp_flags);
inline int SetError(int err)
{
m_errstate = err;
return err;
}
bool ProcessArguments(const sp::CallArgs& args);
protected:
mutable ReentrantList<IPluginFunction *> m_functions;
mutable ReentrantList<IPluginFunction *> m_paused;
/* Type and name information */
sp::CallArgs default_args_;
FwdParamInfo m_params[SP_MAX_EXEC_PARAMS];
ParamType m_types[SP_MAX_EXEC_PARAMS];
AddressMask m_addresses;
char m_name[FORWARDS_NAME_MAX+1];
unsigned int m_numparams;
unsigned int m_varargs;
ExecType m_ExecType;
/* State information */
unsigned int m_curparam;
int m_errstate;
/* Reentrancy protection: tracks how many nested Execute() calls are in
* progress, and whether the forward was released while still executing
* (e.g. a plugin freeing its own private forward handle from within one
* of its own callbacks). Actual destruction is deferred until the
* outermost Execute() call returns. */
unsigned int m_ExecDepth;
bool m_deleted;
};
class CForwardManager :
+18 -20
View File
@@ -31,8 +31,8 @@
#include <string.h>
#include <stdlib.h>
#include <sstream>
#include <list>
#include <string>
#include <sh_list.h>
#include <sh_string.h>
#include "GameConfigs.h"
#include "stringutil.h"
#include <IGameHelpers.h>
@@ -53,6 +53,8 @@
#include <dlfcn.h>
#endif
using namespace SourceHook;
GameConfigManager g_GameConfigs;
IGameConfig *g_pGameConf = NULL;
static char g_Game[256];
@@ -77,9 +79,9 @@ static const char *g_pParseEngine = NULL;
#define PSTATE_GAMEDEFS_ADDRESSES_ADDRESS 14
#define PSTATE_GAMEDEFS_ADDRESSES_ADDRESS_READ 15
#if defined KE_ARCH_X86
#if defined PLATFORM_X86
#define PLATFORM_ARCH_SUFFIX ""
#elif defined KE_ARCH_X64
#elif defined PLATFORM_X64
#define PLATFORM_ARCH_SUFFIX "64"
#endif
@@ -789,7 +791,7 @@ public:
(!had_game && matched_engine) ||
(matched_engine && matched_game))
{
if (std::find(fileList->begin(), fileList->end(), cur_file) == fileList->end())
if (fileList->find(cur_file) == fileList->end())
{
fileList->push_back(cur_file);
}
@@ -804,7 +806,7 @@ public:
return SMCResult_Continue;
}
public:
std::list<std::string> *fileList;
List<String> *fileList;
unsigned int state;
unsigned int ignoreLevel;
char cur_file[PLATFORM_MAX_PATH];
@@ -855,7 +857,7 @@ bool CGameConfig::Reparse(char *error, size_t maxlength)
/* Otherwise, it's time to parse the master. */
SMCError err;
SMCStates state = {0, 0};
std::list<std::string> fileList;
List<String> fileList;
master_reader.fileList = &fileList;
const char *pEngine[2] = { m_pBaseEngine, m_pEngine };
@@ -883,7 +885,8 @@ bool CGameConfig::Reparse(char *error, size_t maxlength)
}
/* Go through each file we found and parse it. */
for (auto iter = fileList.begin(); iter != fileList.end(); iter++)
List<String>::iterator iter;
for (iter = fileList.begin(); iter != fileList.end(); iter++)
{
ke::SafeSprintf(path, sizeof(path), "%s/%s", m_File, (*iter).c_str());
if (!EnterFile(path, error, maxlength))
@@ -1091,18 +1094,13 @@ void GameBinPathManager::Init()
std::istringstream iss(search_path);
for (std::string path; std::getline(iss, path, ';');)
{
if (path.length() > 0)
if (path.length() > 0
&& path.find(addons_folder) == std::string::npos
&& m_lookup.find(path) == m_lookup.cend()
)
{
const char* arch_subdir = bridge->filesystem->GetGameBinArchSubdirectory();
std::string full_path = path + arch_subdir;
if (full_path.find(addons_folder) == std::string::npos
&& m_lookup.find(full_path) == m_lookup.cend()
)
{
m_lookup.insert(full_path);
m_ordered.push_back(full_path);
}
m_lookup.insert(path);
m_ordered.push_back(path);
}
}
@@ -1176,7 +1174,7 @@ bool GameConfigManager::LoadGameConfigFile(const char *file, IGameConfig **_pCon
{
bool ret = true;
time_t modtime = GetFileModTime(file);
if (pConfig->m_ModTime != modtime || pConfig->m_ModTime == 0)
if (pConfig->m_ModTime != modtime)
{
pConfig->m_ModTime = modtime;
ret = pConfig->Reparse(error, maxlength);
+1 -1
View File
@@ -36,7 +36,7 @@
#include <IGameConfigs.h>
#include <ITextParsers.h>
#include <am-refcounting.h>
#include <sm_hashmap.h>
#include <sm_stringhashmap.h>
#include <sm_namehashset.h>
#include <unordered_set>
+1 -1
View File
@@ -70,7 +70,7 @@ HandleSystem::HandleSystem()
memset(m_Handles, 0, sizeof(QHandle) * (HANDLESYS_MAX_HANDLES + 1));
m_Types = new QHandleType[HANDLESYS_TYPEARRAY_SIZE];
memset((void *)m_Types, 0, sizeof(QHandleType) * HANDLESYS_TYPEARRAY_SIZE);
memset(m_Types, 0, sizeof(QHandleType) * HANDLESYS_TYPEARRAY_SIZE);
m_TypeTail = 0;
}
+25 -2
View File
@@ -37,7 +37,7 @@
#include <memory>
#include <amtl/am-string.h>
#include <functional>
#include <amtl/am-function.h>
#include <IHandleSys.h>
#include <sm_namehashset.h>
#include "common_logic.h"
@@ -123,7 +123,7 @@ struct QHandleType
}
};
typedef std::function<void(const char *)> HandleReporter;
typedef ke::Function<void(const char *)> HandleReporter;
class HandleSystem :
public IHandleSys
@@ -243,4 +243,27 @@ private:
extern HandleSystem g_HandleSys;
struct AutoHandleRooter
{
public:
AutoHandleRooter(Handle_t hndl)
{
if (hndl != BAD_HANDLE)
this->hndl = g_HandleSys.FastCloneHandle(hndl);
else
this->hndl = BAD_HANDLE;
}
~AutoHandleRooter()
{
if (hndl != BAD_HANDLE)
{
HandleSecurity sec(g_pCoreIdent, g_pCoreIdent);
g_HandleSys.FreeHandle(hndl, &sec);
}
}
private:
Handle_t hndl;
};
#endif //_INCLUDE_SOURCEMOD_HANDLESYSTEM_H_
+19 -40
View File
@@ -29,7 +29,6 @@
* Version: $Id$
*/
#include <string_view>
#include <time.h>
#include <cstdarg>
#include "Logger.h"
@@ -82,19 +81,6 @@ ConfigResult Logger::OnSourceModConfigChanged(const char *key,
return ConfigResult_Reject;
}
return ConfigResult_Accept;
} else if (strcasecmp(key, "LogTimeFormat") == 0) {
if (strcasecmp(value, "default") == 0)
{
m_isUsingDefaultTimeFormat = true;
m_UserTimeFormat.clear();
}
else {
// value is the time format string
m_isUsingDefaultTimeFormat = false;
m_UserTimeFormat.assign(value);
}
return ConfigResult_Accept;
}
@@ -166,7 +152,11 @@ void Logger::LogToOpenFileEx(FILE *fp, const char *msg, va_list ap)
char buffer[3072];
ke::SafeVsprintf(buffer, sizeof(buffer), msg, ap);
const char* date = GetFormattedDate();
char date[32];
time_t t = g_pSM->GetAdjustedTime();
tm *curtime = localtime(&t);
strftime(date, sizeof(date), "%m/%d/%Y - %H:%M:%S", curtime);
fprintf(fp, "L %s: %s\n", date, buffer);
if (!sv_logecho || bridge->GetCvarBool(sv_logecho))
@@ -184,7 +174,10 @@ void Logger::LogToFileOnlyEx(FILE *fp, const char *msg, va_list ap)
char buffer[3072];
ke::SafeVsprintf(buffer, sizeof(buffer), msg, ap);
const char* date = GetFormattedDate();
char date[32];
time_t t = g_pSM->GetAdjustedTime();
tm *curtime = localtime(&t);
strftime(date, sizeof(date), "%m/%d/%Y - %H:%M:%S", curtime);
fprintf(fp, "L %s: %s\n", date, buffer);
fflush(fp);
@@ -385,7 +378,11 @@ FILE *Logger::_OpenNormal()
if (!m_DamagedNormalFile)
{
const char* date = GetFormattedDate();
time_t t = g_pSM->GetAdjustedTime();
tm *curtime = localtime(&t);
char date[32];
strftime(date, sizeof(date), "%m/%d/%Y - %H:%M:%S", curtime);
fprintf(pFile, "L %s: SourceMod log file session started (file \"%s\") (Version \"%s\")\n", date, m_NormalFileName.c_str(), SOURCEMOD_VERSION);
m_DamagedNormalFile = true;
}
@@ -406,7 +403,11 @@ FILE *Logger::_OpenError()
if (!m_DamagedErrorFile)
{
const char* date = GetFormattedDate();
time_t t = g_pSM->GetAdjustedTime();
tm *curtime = localtime(&t);
char date[32];
strftime(date, sizeof(date), "%m/%d/%Y - %H:%M:%S", curtime);
fprintf(pFile, "L %s: SourceMod error session started\n", date);
fprintf(pFile, "L %s: Info (map \"%s\") (file \"%s\")\n", date, m_CurrentMapName.c_str(), m_ErrorFileName.c_str());
m_DamagedErrorFile = true;
@@ -451,25 +452,3 @@ void Logger::_CloseError()
void Logger::_CloseFatal()
{
}
const char* Logger::GetFormattedDate() const
{
static char date[256];
constexpr std::string_view DEFAULT_TIME_FORMAT{ "%m/%d/%Y - %H:%M:%S" };
time_t t = g_pSM->GetAdjustedTime();
tm *curtime = localtime(&t);
if (m_isUsingDefaultTimeFormat)
{
strftime(date, sizeof(date), DEFAULT_TIME_FORMAT.data(), curtime);
}
else
{
strftime(date, sizeof(date), m_UserTimeFormat.c_str(), curtime);
}
return date;
}
+1 -4
View File
@@ -53,7 +53,7 @@ enum LoggingMode
class Logger : public SMGlobalClass, public ILogger
{
public:
Logger() : m_Day(-1), m_Mode(LoggingMode_Daily), m_Active(true), m_DamagedNormalFile(false), m_DamagedErrorFile(false), m_isUsingDefaultTimeFormat(true)
Logger() : m_Day(-1), m_Mode(LoggingMode_Daily), m_Active(true), m_DamagedNormalFile(false), m_DamagedErrorFile(false)
{
}
public: //SMGlobalClass
@@ -95,12 +95,10 @@ private:
void _LogFatalOpen(std::string &str);
void _PrintToGameLog(const char *fmt, va_list ap);
void _UpdateFiles(bool bLevelChange = false);
const char* GetFormattedDate() const;
private:
std::string m_NormalFileName;
std::string m_ErrorFileName;
std::string m_CurrentMapName;
std::string m_UserTimeFormat;
int m_Day;
@@ -108,7 +106,6 @@ private:
bool m_Active;
bool m_DamagedNormalFile;
bool m_DamagedErrorFile;
bool m_isUsingDefaultTimeFormat;
};
extern Logger g_Logger;
+16 -50
View File
@@ -85,35 +85,6 @@ void *MemoryUtils::FindPattern(const void *libPtr, const char *pattern, size_t l
return NULL;
}
#ifdef PLATFORM_LINUX
for (const auto &segment : lib->segments)
{
if (len > segment.memorySize)
continue;
// Search each readable segment independently. This prevents patterns from
// crossing unmapped gaps between ELF load segments.
char *start = segment.originalCopy.get();
char *end = start + segment.memorySize - len + 1;
for (char *ptr = start; ptr < end; ptr++)
{
bool found = true;
for (register size_t i = 0; i < len; i++)
{
if (pattern[i] != '\x2A' && pattern[i] != ptr[i])
{
found = false;
break;
}
}
if (found)
{
return reinterpret_cast<char *>(lib->baseAddress) + segment.memoryOffset + (ptr - start);
}
}
}
#else
// Search in the original unaltered state of the binary.
char *start = lib->originalCopy.get();
char *ptr = start;
@@ -138,7 +109,6 @@ void *MemoryUtils::FindPattern(const void *libPtr, const char *pattern, size_t l
ptr++;
}
#endif
return NULL;
}
@@ -153,7 +123,7 @@ void *MemoryUtils::ResolveSymbol(void *handle, const char *symbol)
#elif defined PLATFORM_LINUX
#ifdef KE_ARCH_X86
#ifdef PLATFORM_X86
typedef Elf32_Ehdr ElfHeader;
typedef Elf32_Shdr ElfSHeader;
typedef Elf32_Sym ElfSymbol;
@@ -302,7 +272,7 @@ void *MemoryUtils::ResolveSymbol(void *handle, const char *symbol)
#elif defined PLATFORM_APPLE
#ifdef KE_ARCH_X86
#ifdef PLATFORM_X86
typedef struct mach_header MachHeader;
typedef struct segment_command MachSegment;
typedef struct nlist MachSymbol;
@@ -481,7 +451,7 @@ const DynLibInfo *MemoryUtils::GetLibraryInfo(const void *libPtr)
#ifdef PLATFORM_WINDOWS
#ifdef KE_ARCH_X86
#ifdef PLATFORM_X86
const WORD PE_FILE_MACHINE = IMAGE_FILE_MACHINE_I386;
const WORD PE_NT_OPTIONAL_HDR_MAGIC = IMAGE_NT_OPTIONAL_HDR32_MAGIC;
#else
@@ -531,7 +501,7 @@ const DynLibInfo *MemoryUtils::GetLibraryInfo(const void *libPtr)
#elif defined PLATFORM_LINUX
#ifdef KE_ARCH_X86
#ifdef PLATFORM_X86
typedef Elf32_Ehdr ElfHeader;
typedef Elf32_Phdr ElfPHeader;
const unsigned char ELF_CLASS = ELFCLASS32;
@@ -599,19 +569,24 @@ const DynLibInfo *MemoryUtils::GetLibraryInfo(const void *libPtr)
{
ElfPHeader &hdr = phdr[i];
/* Only readable segments are safe and useful to scan. */
if (hdr.p_type == PT_LOAD && (hdr.p_flags & PF_R) && hdr.p_filesz)
/* We only really care about the segment with executable code */
if (hdr.p_type == PT_LOAD && hdr.p_flags == (PF_X|PF_R))
{
DynLibInfo::Segment segment;
segment.memoryOffset = hdr.p_vaddr;
segment.memorySize = hdr.p_filesz;
lib.segments.push_back(std::move(segment));
/* From glibc, elf/dl-load.c:
* c->mapend = ((ph->p_vaddr + ph->p_filesz + GLRO(dl_pagesize) - 1)
* & ~(GLRO(dl_pagesize) - 1));
*
* In glibc, the segment file size is aligned up to the nearest page size and
* added to the virtual address of the segment. We just want the size here.
*/
lib.memorySize = PAGE_ALIGN_UP(hdr.p_filesz);
break;
}
}
#elif defined PLATFORM_APPLE
#ifdef KE_ARCH_X86
#ifdef PLATFORM_X86
typedef struct mach_header MachHeader;
typedef struct segment_command MachSegment;
const uint32_t MACH_MAGIC = MH_MAGIC;
@@ -690,17 +665,8 @@ const DynLibInfo *MemoryUtils::GetLibraryInfo(const void *libPtr)
}
// Keep a copy of the binary in its initial unpatched state for lookup.
#ifdef PLATFORM_LINUX
for (auto &segment : lib.segments)
{
segment.originalCopy = std::make_unique<char[]>(segment.memorySize);
memcpy(segment.originalCopy.get(), reinterpret_cast<char *>(lib.baseAddress) + segment.memoryOffset,
segment.memorySize);
}
#else
lib.originalCopy = std::make_unique<char[]>(lib.memorySize);
memcpy(lib.originalCopy.get(), lib.baseAddress, lib.memorySize);
#endif
m_InfoMap.add(i, lib.baseAddress, std::move(lib));
return &i->value;
+6 -13
View File
@@ -34,9 +34,11 @@
#include <IMemoryUtils.h>
#include <am-hashmap.h>
#include <memory>
#include <vector>
#if defined PLATFORM_LINUX || defined PLATFORM_APPLE
#include <sh_vector.h>
#include "sm_symtable.h"
using namespace SourceHook;
#endif
using namespace SourceMod;
@@ -47,18 +49,9 @@ using namespace SourceMod;
struct DynLibInfo
{
void *baseAddress = nullptr;
size_t memorySize = 0;
void *baseAddress;
size_t memorySize;
std::unique_ptr<char[]> originalCopy;
#ifdef PLATFORM_LINUX
struct Segment
{
size_t memoryOffset = 0;
size_t memorySize = 0;
std::unique_ptr<char[]> originalCopy;
};
std::vector<Segment> segments;
#endif
};
#if defined PLATFORM_LINUX || defined PLATFORM_APPLE
@@ -86,7 +79,7 @@ public:
const DynLibInfo *GetLibraryInfo(const void *libPtr);
#if defined PLATFORM_LINUX || defined PLATFORM_APPLE
private:
std::vector<LibSymbolTable *> m_SymTables;
CVector<LibSymbolTable *> m_SymTables;
#ifdef PLATFORM_APPLE
struct dyld_all_image_infos *m_ImageList;
SInt32 m_OSXMajor;
+1 -1
View File
@@ -36,7 +36,7 @@
#include <am-string.h>
#include <am-utility.h>
#include <am-refcounting.h>
#include <sm_hashmap.h>
#include <sm_stringhashmap.h>
#include "common_logic.h"
class CNativeOwner;
+321
View File
@@ -0,0 +1,321 @@
// vim: set sts=2 ts=8 sw=2 tw=99 et:
//
// Copyright (C) 2006-2015 AlliedModders LLC
//
// This file is part of SourcePawn. SourcePawn is free software: you can
// redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
//
// You should have received a copy of the GNU General Public License along with
// SourcePawn. If not, see http://www.gnu.org/licenses/.
//
#include <stdio.h>
#include <string.h>
#include "NativeInvoker.h"
/********************
* FUNCTION CALLING *
********************/
NativeInvoker::NativeInvoker(IPluginContext *pContext, const ke::RefPtr<Native> &native)
: context_(pContext),
m_curparam(0),
m_errorstate(SP_ERROR_NONE),
native_(native)
{
}
NativeInvoker::~NativeInvoker()
{
Cancel();
}
bool
NativeInvoker::IsRunnable()
{
return true;
}
IPluginContext *
NativeInvoker::GetParentContext()
{
return context_;
}
int NativeInvoker::PushCell(cell_t cell)
{
if (m_curparam >= SP_MAX_EXEC_PARAMS)
return SetError(SP_ERROR_PARAMS_MAX);
m_info[m_curparam].marked = false;
m_params[m_curparam] = cell;
m_curparam++;
return SP_ERROR_NONE;
}
int
NativeInvoker::PushCellByRef(cell_t *cell, int flags)
{
return PushArray(cell, 1, flags);
}
int
NativeInvoker::PushFloat(float number)
{
cell_t val = sp::FloatCellUnion(number).cell;
return PushCell(val);
}
int
NativeInvoker::PushFloatByRef(float *number, int flags)
{
return PushCellByRef((cell_t *)number, flags);
}
int
NativeInvoker::PushArray(cell_t *inarray, unsigned int cells, int copyback)
{
if (m_curparam >= SP_MAX_EXEC_PARAMS)
{
return SetError(SP_ERROR_PARAMS_MAX);
}
ParamInfo *info = &m_info[m_curparam];
info->flags = inarray ? copyback : 0;
info->marked = true;
info->size = cells;
info->str.is_sz = false;
info->orig_addr = inarray;
m_curparam++;
return SP_ERROR_NONE;
}
int
NativeInvoker::PushString(const char *string)
{
return _PushString(string, SM_PARAM_STRING_COPY, 0, strlen(string)+1);
}
int
NativeInvoker::PushStringEx(char *buffer, size_t length, int sz_flags, int cp_flags)
{
return _PushString(buffer, sz_flags, cp_flags, length);
}
int
NativeInvoker::_PushString(const char *string, int sz_flags, int cp_flags, size_t len)
{
if (m_curparam >= SP_MAX_EXEC_PARAMS)
return SetError(SP_ERROR_PARAMS_MAX);
ParamInfo *info = &m_info[m_curparam];
info->marked = true;
info->orig_addr = (cell_t *)string;
info->flags = cp_flags;
info->size = len;
info->str.sz_flags = sz_flags;
info->str.is_sz = true;
m_curparam++;
return SP_ERROR_NONE;
}
void
NativeInvoker::Cancel()
{
if (!m_curparam)
return;
m_errorstate = SP_ERROR_NONE;
m_curparam = 0;
}
int
NativeInvoker::Execute(cell_t *result, cell_t buffer, cell_t size)
{
context_->ClearLastNativeError();
// For backward compatibility, we have to clear the exception state.
// Otherwise code like this:
//
// static cell_t native(cx, params) {
// for (auto callback : callbacks) {
// callback->Execute();
// }
// }
//
// Could unintentionally leak a pending exception back to the caller,
// which wouldn't have happened before the Great Exception Refactoring.
SourcePawn::ExceptionHandler eh(context_);
eh.Debug(!size);
if (!Invoke(result)) {
if(size)
context_->StringToLocalUTF8(buffer, size, eh.Message(), NULL);
int Err = context_->GetLastNativeError();
context_->ClearLastNativeError();
return Err;
}
return SP_ERROR_NONE;
}
bool
NativeInvoker::Invoke(cell_t *result)
{
if (!IsRunnable()) {
Cancel();
context_->ReportErrorNumber(SP_ERROR_NOT_RUNNABLE);
return false;
}
if (int err = m_errorstate) {
Cancel();
context_->ReportErrorNumber(err);
return false;
}
//This is for re-entrancy!
cell_t _temp_params[SP_MAX_EXEC_PARAMS + 1];
cell_t *temp_params = &_temp_params[1];
ParamInfo temp_info[SP_MAX_EXEC_PARAMS];
unsigned int numparams = m_curparam;
unsigned int i;
if (numparams)
{
//Save the info locally, then reset it for re-entrant calls.
memcpy(temp_info, m_info, numparams * sizeof(ParamInfo));
}
m_curparam = 0;
/* Initialize 0th parameter */
_temp_params[0] = numparams;
/* Browse the parameters and build arrays */
bool ok = true;
for (i=0; i<numparams; i++) {
/* Is this marked as an array? */
if (temp_info[i].marked) {
if (!temp_info[i].str.is_sz) {
/* Allocate a normal/generic array */
int err = context_->HeapAlloc(
temp_info[i].size,
&(temp_info[i].local_addr),
&(temp_info[i].phys_addr));
if (err != SP_ERROR_NONE) {
context_->ReportErrorNumber(err);
ok = false;
break;
}
if (temp_info[i].orig_addr)
{
memcpy(temp_info[i].phys_addr, temp_info[i].orig_addr, sizeof(cell_t) * temp_info[i].size);
}
} else {
/* Calculate cells required for the string */
size_t cells = (temp_info[i].size + sizeof(cell_t) - 1) / sizeof(cell_t);
/* Allocate the buffer */
int err = context_->HeapAlloc(
cells,
&(temp_info[i].local_addr),
&(temp_info[i].phys_addr));
if (err != SP_ERROR_NONE) {
context_->ReportErrorNumber(err);
ok = false;
break;
}
/* Copy original string if necessary */
if ((temp_info[i].str.sz_flags & SM_PARAM_STRING_COPY) && (temp_info[i].orig_addr != NULL))
{
/* Cut off UTF-8 properly */
if (temp_info[i].str.sz_flags & SM_PARAM_STRING_UTF8) {
context_->StringToLocalUTF8(
temp_info[i].local_addr,
temp_info[i].size,
(const char *)temp_info[i].orig_addr,
NULL);
}
/* Copy a binary blob */
else if (temp_info[i].str.sz_flags & SM_PARAM_STRING_BINARY)
{
memmove(temp_info[i].phys_addr, temp_info[i].orig_addr, temp_info[i].size);
}
/* Copy ASCII characters */
else
{
context_->StringToLocal(
temp_info[i].local_addr,
temp_info[i].size,
(const char *)temp_info[i].orig_addr);
}
}
} /* End array/string calculation */
/* Update the pushed parameter with the byref local address */
temp_params[i] = temp_info[i].local_addr;
} else {
/* Just copy the value normally */
temp_params[i] = m_params[i];
}
}
/* Make the call if we can */
if (ok)
{
*result = native_->func()(context_, _temp_params);
}
/* i should be equal to the last valid parameter + 1 */
bool docopies = ok;
while (i--) {
if (!temp_info[i].marked)
continue;
if (docopies && (temp_info[i].flags & SM_PARAM_COPYBACK)) {
if (temp_info[i].orig_addr) {
if (temp_info[i].str.is_sz) {
memcpy(temp_info[i].orig_addr, temp_info[i].phys_addr, temp_info[i].size);
} else {
if (temp_info[i].size == 1) {
*temp_info[i].orig_addr = *(temp_info[i].phys_addr);
} else {
memcpy(temp_info[i].orig_addr,
temp_info[i].phys_addr,
temp_info[i].size * sizeof(cell_t));
}
}
}
}
if (int err = context_->HeapPop(temp_info[i].local_addr))
context_->ReportErrorNumber(err);
}
return context_->GetLastNativeError() == SP_ERROR_NONE;
}
int
NativeInvoker::SetError(int err)
{
m_errorstate = err;
return err;
}
int NativeInvoker::CallFunction(const cell_t *params, unsigned int num_params, cell_t *result) { return 0; }
funcid_t NativeInvoker::GetFunctionID() { return 0; }
int NativeInvoker::Execute2(IPluginContext *ctx, cell_t *result) { return 0; }
int NativeInvoker::CallFunction2(IPluginContext *ctx, const cell_t *params, unsigned int num_params, cell_t *result) { return 0; }
IPluginRuntime *NativeInvoker::GetParentRuntime() { return NULL; }
+79
View File
@@ -0,0 +1,79 @@
// vim: set sts=2 ts=8 sw=2 tw=99 et:
//
// Copyright (C) 2006-2015 AlliedModders LLC
//
// This file is part of SourcePawn. SourcePawn is free software: you can
// redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
//
// You should have received a copy of the GNU General Public License along with
// SourcePawn. If not, see http://www.gnu.org/licenses/.
//
#ifndef _INCLUDE_SOURCEMOD_NATIVE_INVOKER_H_
#define _INCLUDE_SOURCEMOD_NATIVE_INVOKER_H_
#include <sp_vm_api.h>
#include <amtl/am-autoptr.h>
#include <amtl/am-refcounting.h>
#include "Native.h"
struct ParamInfo
{
int flags; /* Copy-back flags */
bool marked; /* Whether this is marked as being used */
cell_t local_addr; /* Local address to free */
cell_t *phys_addr; /* Physical address of our copy */
cell_t *orig_addr; /* Original address to copy back to */
ucell_t size; /* Size of array in bytes */
struct {
bool is_sz; /* is a string */
int sz_flags; /* has sz flags */
} str;
};
class NativeInvoker : public IPluginFunction
{
public:
NativeInvoker(IPluginContext *pContext, const ke::RefPtr<Native> &native);
virtual ~NativeInvoker();
public:
int PushCell(cell_t cell);
int PushCellByRef(cell_t *cell, int flags);
int PushFloat(float number);
int PushFloatByRef(float *number, int flags);
int PushArray(cell_t *inarray, unsigned int cells, int copyback);
int PushString(const char *string);
int PushStringEx(char *buffer, size_t length, int sz_flags, int cp_flags);
int Execute(cell_t *result, cell_t buffer=0, cell_t size=0);
void Cancel();
int CallFunction(const cell_t *params, unsigned int num_params, cell_t *result);
IPluginContext *GetParentContext();
bool Invoke(cell_t *result);
bool IsRunnable();
funcid_t GetFunctionID();
int Execute2(IPluginContext *ctx, cell_t *result);
int CallFunction2(IPluginContext *ctx,
const cell_t *params,
unsigned int num_params,
cell_t *result);
IPluginRuntime *GetParentRuntime();
const char *DebugName() {
return native_->name();
}
private:
int _PushString(const char *string, int sz_flags, int cp_flags, size_t len);
int SetError(int err);
private:
IPluginContext *context_;
cell_t m_params[SP_MAX_EXEC_PARAMS];
ParamInfo m_info[SP_MAX_EXEC_PARAMS];
unsigned int m_curparam;
int m_errorstate;
ke::RefPtr<Native> native_;
};
#endif //_INCLUDE_SOURCEMOD_NATIVE_INVOKER_H_
+11 -6
View File
@@ -31,7 +31,6 @@
#include "NativeOwner.h"
#include "ShareSys.h"
#include "PluginSys.h"
#include <sourcepawn/vm/base-runtime.h>
CNativeOwner::CNativeOwner() : m_nMarkSerial(0)
{
@@ -49,7 +48,7 @@ unsigned int CNativeOwner::GetMarkSerial()
void CNativeOwner::AddDependent(CPlugin *pPlugin)
{
if (std::find(m_Dependents.begin(), m_Dependents.end(), pPlugin) == m_Dependents.end())
if (m_Dependents.find(pPlugin) == m_Dependents.end())
m_Dependents.push_back(pPlugin);
}
@@ -68,8 +67,10 @@ void CNativeOwner::AddNatives(const sp_nativeinfo_t *natives)
void CNativeOwner::UnbindWeakRef(const WeakNative &ref)
{
auto pContext = ref.pl->runtime();
pContext->UpdateNativeBinding(
IPluginContext *pContext;
pContext = ref.pl->GetBaseContext();
pContext->GetRuntime()->UpdateNativeBinding(
ref.idx,
nullptr,
SP_NTVFLAG_OPTIONAL,
@@ -78,8 +79,10 @@ void CNativeOwner::UnbindWeakRef(const WeakNative &ref)
void CNativeOwner::DropEverything()
{
List<WeakNative>::iterator iter;
/* Unbind and remove all weak references to us */
auto iter = m_WeakRefs.begin();
iter = m_WeakRefs.begin();
while (iter != m_WeakRefs.end())
{
UnbindWeakRef((*iter));
@@ -101,7 +104,9 @@ void CNativeOwner::DropEverything()
void CNativeOwner::DropWeakRefsTo(CPlugin *pPlugin)
{
auto iter = m_WeakRefs.begin();
List<WeakNative>::iterator iter;
iter = m_WeakRefs.begin();
while (iter != m_WeakRefs.end())
{
WeakNative & ref = (*iter);
+8 -6
View File
@@ -8,7 +8,7 @@
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
@@ -32,7 +32,7 @@
#define _INCLUDE_SOURCEMOD_NATIVE_OWNER_H_
#include <sp_vm_types.h>
#include <list>
#include <sh_list.h>
#include <am-vector.h>
#include "common_logic.h"
#include "Native.h"
@@ -45,16 +45,18 @@ using namespace SourceMod;
struct WeakNative
{
WeakNative(CPlugin *plugin, uint32_t index) :
WeakNative(IPlugin *plugin, uint32_t index) :
pl(plugin), idx(index)
{
pl = plugin;
idx = index;
}
CPlugin *pl;
IPlugin *pl;
uint32_t idx;
};
using namespace SourceHook;
class CNativeOwner
{
public:
@@ -74,9 +76,9 @@ private:
void DropWeakRefsTo(CPlugin *pPlugin);
void UnbindWeakRef(const WeakNative & ref);
protected:
std::list<CPlugin *> m_Dependents;
List<CPlugin *> m_Dependents;
unsigned int m_nMarkSerial;
std::list<WeakNative> m_WeakRefs;
List<WeakNative> m_WeakRefs;
std::vector<const sp_nativeinfo_t *> m_natives;
std::vector<ke::RefPtr<Native> > m_fakes;
};
+3 -2
View File
@@ -33,9 +33,10 @@
#define _INCLUDE_SOURCEMOD_PHRASECOLLECTION_H_
#include <string.h>
#include <vector>
#include <sh_vector.h>
#include <ITranslator.h>
using namespace SourceHook;
using namespace SourceMod;
class CPhraseCollection : public IPhraseCollection
@@ -59,7 +60,7 @@ public:
size_t *pOutLength,
const char **pFailPhrase);
private:
std::vector<IPhraseFile *> m_Files;
CVector<IPhraseFile *> m_Files;
};
#endif //_INCLUDE_SOURCEMOD_PHRASECOLLECTION_H_
+87 -191
View File
@@ -38,7 +38,6 @@
#include <IHandleSys.h>
#include <IForwardSys.h>
#include <IPlayerHelpers.h>
#include <sourcepawn/vm/environment.h>
#include "ExtensionSys.h"
#include "GameConfigs.h"
#include "common_logic.h"
@@ -99,8 +98,8 @@ void CPlugin::InitIdentity()
m_ident = g_ShareSys.CreateIdentity(g_PluginIdent, this);
m_handle = handlesys->CreateHandle(g_PluginType, this, g_PluginSys.GetIdentity(), g_PluginSys.GetIdentity(), NULL);
m_pRuntime->SetKey(1, m_ident);
m_pRuntime->SetKey(2, (IPlugin *)this);
m_pRuntime->GetDefaultContext()->SetKey(1, m_ident);
m_pRuntime->GetDefaultContext()->SetKey(2, (IPlugin *)this);
}
void CPlugin::DestroyIdentity()
@@ -259,54 +258,14 @@ void CPlugin::EvictWithError(PluginStatus status, const char *error_fmt, ...)
}
}
// Pstruct fields are stored in the .pstruct_glb table, not in .pubvars.
// v1 images have no pstruct table, so callers fall back to legacy reads.
static bool GetPstructStringField(sp::SmxImage* image, const sp::smx_pstruct_global* glb,
const char* field, std::string* out)
{
std::variant<std::string, cell_t> v;
if (image->GetPstructValue(glb, field, &v) != SP_ERROR_NONE ||
!std::holds_alternative<std::string>(v))
{
return false;
}
*out = std::get<std::string>(std::move(v));
return true;
}
static bool GetPstructBoolField(sp::SmxImage* image, const sp::smx_pstruct_global* glb,
const char* field, bool* out)
{
std::variant<std::string, cell_t> v;
if (image->GetPstructValue(glb, field, &v) != SP_ERROR_NONE ||
!std::holds_alternative<cell_t>(v))
{
return false;
}
*out = std::get<cell_t>(v) != 0;
return true;
}
bool CPlugin::ReadInfo()
{
/* Now grab the info */
uint32_t idx;
IPluginContext *base = GetBaseContext();
int err;
int err = base->FindPubvarByName("myinfo", &idx);
sp::SmxImage* image = base->GetBaseRuntime()->image();
if (const sp::smx_pstruct_global* myinfo = image->FindPstructGlobal("myinfo")) {
auto update_field = [&](const char* field, std::string *dest) {
if (!GetPstructStringField(image, myinfo, field, dest))
*dest = "";
};
update_field("name", &info_name_);
update_field("description", &info_description_);
update_field("author", &info_author_);
update_field("version", &info_version_);
update_field("url", &info_url_);
} else if ((err = base->FindPubvarByName("myinfo", &idx)) == SP_ERROR_NONE) {
if (err == SP_ERROR_NONE) {
struct sm_plugininfo_c_t
{
cell_t name;
@@ -371,13 +330,6 @@ bool CPlugin::ReadInfo()
else
m_MaxClientsVar = nullptr;
if (base->FindPubvarByName("Address_PointerSize", &idx) == SP_ERROR_NONE) {
sp_pubvar_t* var = nullptr;
if (base->GetPubvarByIndex(idx, &var) == SP_ERROR_NONE && var) {
*reinterpret_cast<int64_t*>(var->offs) = sizeof(void*);
}
}
return true;
}
@@ -520,15 +472,21 @@ void CPlugin::Call_OnLibraryAdded(const char *lib)
pFunction->Execute(&result);
}
void *CPlugin::GetPluginStructure()
{
return NULL;
}
// Only called during plugin construction.
bool CPlugin::TryCompile()
{
char fullpath[PLATFORM_MAX_PATH];
g_pSM->BuildPath(Path_SM, fullpath, sizeof(fullpath), "plugins/%s", m_filename);
m_pRuntime.reset(g_pPawnEnv->LoadBinaryFromFile(fullpath));
char loadmsg[255];
m_pRuntime.reset(g_pSourcePawn2->LoadBinaryFromFile(fullpath, loadmsg, sizeof(loadmsg)));
if (!m_pRuntime) {
EvictWithError(Plugin_BadLoad, "Unable to load plugin (%s)", m_filename);
EvictWithError(Plugin_BadLoad, "Unable to load plugin (%s)", loadmsg);
return false;
}
@@ -550,6 +508,11 @@ IPluginContext *CPlugin::GetBaseContext()
return m_pRuntime->GetDefaultContext();
}
sp_context_t *CPlugin::GetContext()
{
return NULL;
}
const char *CPlugin::GetFilename()
{
return m_filename;
@@ -705,7 +668,7 @@ void CPlugin::DependencyDropped(CPlugin *pOwner)
return;
for (auto lib_iter=pOwner->m_Libraries.begin(); lib_iter!=pOwner->m_Libraries.end(); lib_iter++) {
if (std::find(m_RequiredLibs.begin(), m_RequiredLibs.end(), *lib_iter) != m_RequiredLibs.end()) {
if (m_RequiredLibs.find(*lib_iter) != m_RequiredLibs.end()) {
m_LibraryMissing = true;
break;
}
@@ -776,9 +739,10 @@ void CPlugin::AddConfig(bool autoCreate, const char *cfg, const char *folder)
void CPlugin::DropEverything()
{
CPlugin *pOther;
List<WeakNative>::iterator wk_iter;
/* Tell everyone that depends on us that we're about to drop */
for (auto iter = m_Dependents.begin();
for (List<CPlugin *>::iterator iter = m_Dependents.begin();
iter != m_Dependents.end();
iter++)
{
@@ -1069,8 +1033,7 @@ void CPluginManager::LoadAutoPlugin(const char *plugin)
LoadRes res;
if ((res=LoadPlugin(&pl, plugin, false, PluginType_MapUpdated)) == LoadRes_Failure)
{
if (!pl->IsSilentlyFailed())
g_Logger.LogError("[SM] Failed to load plugin \"%s\": %s.", plugin, pl->GetErrorMsg());
g_Logger.LogError("[SM] Failed to load plugin \"%s\": %s.", plugin, pl->GetErrorMsg());
}
if (res == LoadRes_Successful || res == LoadRes_Failure)
@@ -1127,93 +1090,50 @@ bool CPluginManager::FindOrRequirePluginDeps(CPlugin *pPlugin)
uint32_t num = pBase->GetPubVarsNum();
sp_pubvar_t *pubvar;
char *name, *file;
char pathfile[PLATFORM_MAX_PATH];
libsys->GetFileFromPath(pathfile, sizeof(pathfile), pPlugin->GetFilename());
struct PluginDep
{
std::string pubvar_name;
std::string name;
std::string file;
bool required;
};
std::vector<PluginDep> deps;
sp::SmxImage* image = pBase->GetBaseRuntime()->image();
if (image->pstruct_global_count()) {
for (uint32_t i = 0; i < image->pstruct_global_count(); i++) {
const sp::smx_pstruct_global* glb = image->pstruct_globals() + i;
const char* pubvar_name = image->names() + glb->name;
if (strncmp(pubvar_name, "__pl_", 5) != 0)
continue;
PluginDep dep;
dep.pubvar_name = pubvar_name;
dep.required = false;
if (!GetPstructStringField(image, glb, "file", &dep.file))
continue;
if (!GetPstructStringField(image, glb, "name", &dep.name))
continue;
GetPstructBoolField(image, glb, "required", &dep.required);
deps.push_back(std::move(dep));
}
} else {
for (uint32_t i=0; i<num; i++) {
if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
continue;
if (strncmp(pubvar->name, "__pl_", 5) != 0)
continue;
for (uint32_t i=0; i<num; i++) {
if (pBase->GetPubvarByIndex(i, &pubvar) != SP_ERROR_NONE)
continue;
if (strncmp(pubvar->name, "__pl_", 5) == 0) {
pl = (_pl *)pubvar->offs;
if (pBase->LocalToString(pl->file, &file) != SP_ERROR_NONE)
continue;
if (pBase->LocalToString(pl->name, &name) != SP_ERROR_NONE)
continue;
libsys->GetFileFromPath(pathfile, sizeof(pathfile), pPlugin->GetFilename());
if (strcmp(pathfile, file) == 0)
continue;
if (pl->required == false) {
IPluginFunction *pFunc;
char buffer[64];
ke::SafeSprintf(buffer, sizeof(buffer), "__pl_%s_SetNTVOptional", &pubvar->name[5]);
if ((pFunc=pBase->GetFunctionByName(buffer))) {
cell_t res;
if (pFunc->Execute(&res) != SP_ERROR_NONE) {
pPlugin->EvictWithError(Plugin_Failed, "Fatal error during initializing plugin load");
return false;
}
}
} else {
/* Check that we aren't registering the same library twice */
pPlugin->AddRequiredLib(name);
PluginDep dep;
dep.pubvar_name = pubvar->name;
dep.name = name;
dep.file = file;
dep.required = !!pl->required;
deps.push_back(std::move(dep));
}
}
for (const PluginDep& dep : deps) {
if (strcmp(pathfile, dep.file.c_str()) == 0)
continue;
if (!dep.required) {
IPluginFunction *pFunc;
char buffer[64];
ke::SafeSprintf(buffer, sizeof(buffer), "__pl_%s_SetNTVOptional", &dep.pubvar_name[5]);
if ((pFunc=pBase->GetFunctionByName(buffer))) {
cell_t res;
if (pFunc->Execute(&res) != SP_ERROR_NONE) {
pPlugin->EvictWithError(Plugin_Failed, "Fatal error during initializing plugin load");
CPlugin *found = nullptr;
for (PluginIter iter(m_plugins); !iter.done(); iter.next()) {
CPlugin *pl = (*iter);
if (pl->HasLibrary(name)) {
found = pl;
break;
}
}
if (!found) {
pPlugin->EvictWithError(Plugin_Failed, "Could not find required plugin \"%s\"", name);
return false;
}
}
} else {
/* Check that we aren't registering the same library twice */
pPlugin->AddRequiredLib(dep.name.c_str());
CPlugin *found = nullptr;
for (PluginIter iter(m_plugins); !iter.done(); iter.next()) {
CPlugin *other = (*iter);
if (other->HasLibrary(dep.name.c_str())) {
found = other;
break;
}
found->AddDependent(pPlugin);
}
if (!found) {
pPlugin->EvictWithError(Plugin_Failed, "Could not find required plugin \"%s\"", dep.name.c_str());
return false;
}
found->AddDependent(pPlugin);
}
}
@@ -1231,31 +1151,6 @@ bool CPlugin::ForEachExtVar(const ExtVarCallback& callback)
} *ext;
IPluginContext *pBase = GetBaseContext();
sp::SmxImage* image = pBase->GetBaseRuntime()->image();
for (uint32_t i = 0; i < image->pstruct_global_count(); i++) {
const sp::smx_pstruct_global* glb = image->pstruct_globals() + i;
const char* pubvar_name = image->names() + glb->name;
if (strncmp(pubvar_name, "__ext_", 6) != 0)
continue;
ExtVar var;
var.autoload = false;
var.required = false;
if (!GetPstructStringField(image, glb, "file", &var.file))
continue;
if (!GetPstructStringField(image, glb, "name", &var.name))
continue;
GetPstructBoolField(image, glb, "autoload", &var.autoload);
GetPstructBoolField(image, glb, "required", &var.required);
if (!callback(pubvar_name, var))
return false;
}
if (image->pstruct_global_count())
return true;
for (uint32_t i = 0; i < pBase->GetPubVarsNum(); i++)
{
sp_pubvar_t *pubvar;
@@ -1268,23 +1163,20 @@ bool CPlugin::ForEachExtVar(const ExtVarCallback& callback)
ext = (_ext *)pubvar->offs;
ExtVar var;
char *str;
if (pBase->LocalToString(ext->file, &str) != SP_ERROR_NONE)
if (pBase->LocalToString(ext->file, &var.file) != SP_ERROR_NONE)
continue;
var.file = str;
if (pBase->LocalToString(ext->name, &str) != SP_ERROR_NONE)
if (pBase->LocalToString(ext->name, &var.name) != SP_ERROR_NONE)
continue;
var.name = str;
var.autoload = !!ext->autoload;
var.required = !!ext->required;
if (!callback(pubvar->name, var))
if (!callback(pubvar, var))
return false;
}
return true;
}
void CPlugin::ForEachLibrary(std::function<void(const char *)> callback)
void CPlugin::ForEachLibrary(ke::Function<void(const char *)> callback)
{
for (auto iter = m_Libraries.begin(); iter != m_Libraries.end(); iter++)
callback((*iter).c_str());
@@ -1292,11 +1184,11 @@ void CPlugin::ForEachLibrary(std::function<void(const char *)> callback)
void CPlugin::AddRequiredLib(const char *name)
{
if (std::find(m_RequiredLibs.begin(), m_RequiredLibs.end(), name) == m_RequiredLibs.end())
if (m_RequiredLibs.find(name) == m_RequiredLibs.end())
m_RequiredLibs.push_back(name);
}
bool CPlugin::ForEachRequiredLib(std::function<bool(const char *)> callback)
bool CPlugin::ForEachRequiredLib(ke::Function<bool(const char *)> callback)
{
for (auto iter = m_RequiredLibs.begin(); iter != m_RequiredLibs.end(); iter++) {
if (!callback((*iter).c_str()))
@@ -1320,12 +1212,12 @@ void CPlugin::SetWaitingToUnload(bool andReload)
void CPluginManager::LoadExtensions(CPlugin *pPlugin)
{
auto callback = [pPlugin] (const char *, const CPlugin::ExtVar& ext) -> bool
auto callback = [pPlugin] (const sp_pubvar_t *pubvar, const CPlugin::ExtVar& ext) -> bool
{
char path[PLATFORM_MAX_PATH];
/* Attempt to auto-load if necessary */
if (ext.autoload) {
libsys->PathFormat(path, PLATFORM_MAX_PATH, "%s", ext.file.c_str());
libsys->PathFormat(path, PLATFORM_MAX_PATH, "%s", ext.file);
g_Extensions.LoadAutoExtension(path, ext.required);
}
return true;
@@ -1336,24 +1228,24 @@ void CPluginManager::LoadExtensions(CPlugin *pPlugin)
bool CPluginManager::RequireExtensions(CPlugin *pPlugin)
{
auto callback = [pPlugin]
(const char *pubvar, const CPlugin::ExtVar& ext) -> bool
(const sp_pubvar_t *pubvar, const CPlugin::ExtVar& ext) -> bool
{
/* Is this required? */
if (ext.required) {
char path[PLATFORM_MAX_PATH];
libsys->PathFormat(path, PLATFORM_MAX_PATH, "%s", ext.file.c_str());
libsys->PathFormat(path, PLATFORM_MAX_PATH, "%s", ext.file);
IExtension *pExt = g_Extensions.FindExtensionByFile(path);
if (!pExt)
pExt = g_Extensions.FindExtensionByName(ext.name.c_str());
pExt = g_Extensions.FindExtensionByName(ext.name);
if (!pExt || !pExt->IsRunning(nullptr, 0)) {
pPlugin->EvictWithError(Plugin_Failed, "Required extension \"%s\" file(\"%s\") not running", ext.name.c_str(), ext.file.c_str());
pPlugin->EvictWithError(Plugin_Failed, "Required extension \"%s\" file(\"%s\") not running", ext.name, ext.file);
return false;
}
g_Extensions.BindChildPlugin(pExt, pPlugin);
} else {
char buffer[64];
ke::SafeSprintf(buffer, sizeof(buffer), "__ext_%s_SetNTVOptional", &pubvar[6]);
ke::SafeSprintf(buffer, sizeof(buffer), "__ext_%s_SetNTVOptional", &pubvar->name[6]);
if (IPluginFunction *pFunc = pPlugin->GetBaseContext()->GetFunctionByName(buffer)) {
cell_t res;
@@ -1393,7 +1285,7 @@ CPlugin *CPluginManager::CompileAndPrep(const char *path)
bool CPluginManager::MalwareCheckPass(CPlugin *pPlugin)
{
unsigned char *pCodeHash = pPlugin->runtime()->GetCodeHash();
unsigned char *pCodeHash = pPlugin->GetRuntime()->GetCodeHash();
char codeHashBuf[40];
ke::SafeStrcpy(codeHashBuf, sizeof(codeHashBuf), "plugin_");
@@ -1433,10 +1325,11 @@ bool CPluginManager::RunSecondPass(CPlugin *pPlugin)
g_ShareSys.BindNativesToPlugin(pPlugin, false);
// Find any unbound natives. Right now, these are not allowed.
uint32_t num = pPlugin->runtime()->GetNativesNum();
IPluginContext *pContext = pPlugin->GetBaseContext();
uint32_t num = pContext->GetNativesNum();
for (unsigned int i=0; i<num; i++)
{
const sp_native_t *native = pPlugin->runtime()->GetNative(i);
const sp_native_t *native = pContext->GetRuntime()->GetNative(i);
if (!native)
break;
if (native->status == SP_NATIVE_UNBOUND &&
@@ -1525,10 +1418,11 @@ void CPluginManager::TryRefreshDependencies(CPlugin *pPlugin)
/* Find any unbound natives
* Right now, these are not allowed
*/
uint32_t num = pPlugin->runtime()->GetNativesNum();
IPluginContext *pContext = pPlugin->GetBaseContext();
uint32_t num = pContext->GetNativesNum();
for (unsigned int i=0; i<num; i++)
{
const sp_native_t *native = pPlugin->runtime()->GetNative(i);
const sp_native_t *native = pContext->GetRuntime()->GetNative(i);
if (!native)
break;
if (native->status == SP_NATIVE_UNBOUND &&
@@ -1634,9 +1528,12 @@ void CPluginManager::UnloadPluginImpl(CPlugin *pPlugin)
delete pPlugin;
}
SMPlugin *CPluginManager::FindPluginByContext(IPluginContext *pContext)
IPlugin *CPluginManager::FindPluginByContext(const sp_context_t *ctx)
{
SMPlugin *pPlugin;
IPlugin *pPlugin;
IPluginContext *pContext;
pContext = reinterpret_cast<IPluginContext *>(const_cast<sp_context_t *>(ctx));
if (pContext->GetKey(2, (void **)&pPlugin))
{
@@ -1646,7 +1543,7 @@ SMPlugin *CPluginManager::FindPluginByContext(IPluginContext *pContext)
return NULL;
}
CPlugin *CPluginManager::GetPluginByCtx(IPluginContext *ctx)
CPlugin *CPluginManager::GetPluginByCtx(const sp_context_t *ctx)
{
return (CPlugin *)FindPluginByContext(ctx);
}
@@ -2077,7 +1974,7 @@ void CPluginManager::OnRootConsoleCommand(const char *cmdname, const ICommandArg
rootmenu->ConsolePrint(" Timestamp: %s", pl->GetDateTime());
}
if (auto runtime = pl->runtime()) {
if (IPluginRuntime *runtime = pl->GetRuntime()) {
unsigned char *pCodeHash = runtime->GetCodeHash();
unsigned char *pDataHash = runtime->GetDataHash();
@@ -2377,9 +2274,9 @@ void CPluginManager::SyncMaxClients(int max_clients)
(*iter)->SyncMaxClients(max_clients);
}
const std::vector<SMPlugin *> *CPluginManager::ListPlugins()
const CVector<SMPlugin *> *CPluginManager::ListPlugins()
{
std::vector<SMPlugin *> *list = new std::vector<SMPlugin *>();
CVector<SMPlugin *> *list = new CVector<SMPlugin *>();
for (PluginIter iter(m_plugins); !iter.done(); iter.next())
list->push_back((*iter));
@@ -2387,12 +2284,12 @@ const std::vector<SMPlugin *> *CPluginManager::ListPlugins()
return list;
}
void CPluginManager::FreePluginList(const std::vector<SMPlugin *> *list)
void CPluginManager::FreePluginList(const CVector<SMPlugin *> *list)
{
delete const_cast<std::vector<SMPlugin *> *>(list);
delete const_cast<CVector<SMPlugin *> *>(list);
}
void CPluginManager::ForEachPlugin(std::function<void(CPlugin *)> callback)
void CPluginManager::ForEachPlugin(ke::Function<void(CPlugin *)> callback)
{
for (PluginIter iter(m_plugins); !iter.done(); iter.next())
callback(*iter);
@@ -2451,9 +2348,9 @@ public:
return g_PluginSys.UnloadPlugin(plugin);
}
IPlugin *FindPluginByContext(IPluginContext *ctx) override
IPlugin *FindPluginByContext(const sp_context_t *ctx) override
{
return g_PluginSys.FindPluginByContext(ctx->GetBaseRuntime());
return g_PluginSys.FindPluginByContext(ctx);
}
unsigned int GetPluginCount() override
@@ -2514,4 +2411,3 @@ IPluginManager *CPluginManager::GetOldAPI()
{
return &sOldPluginAPI;
}
+33 -24
View File
@@ -41,13 +41,13 @@
#include <IPluginSys.h>
#include <IHandleSys.h>
#include <IForwardSys.h>
#include <list>
#include <stack>
#include <vector>
#include <string>
#include <sh_list.h>
#include <sh_stack.h>
#include <sh_vector.h>
#include <sh_string.h>
#include "common_logic.h"
#include <IRootConsoleMenu.h>
#include <sm_hashmap.h>
#include <sm_stringhashmap.h>
#include <sm_namehashset.h>
#include "ITranslator.h"
#include "IGameConfigs.h"
@@ -56,11 +56,13 @@
#include "PhraseCollection.h"
#include <am-string.h>
#include <bridge/include/IScriptManager.h>
#include <functional>
#include <am-function.h>
#include <ReentrantList.h>
class CPlayer;
using namespace SourceHook;
enum LoadRes
{
LoadRes_Successful,
@@ -103,6 +105,8 @@ public:
public:
PluginType GetType();
SourcePawn::IPluginContext *GetBaseContext();
sp_context_t *GetContext();
void *GetPluginStructure();
const char *GetFilename();
bool IsDebugging();
PluginStatus GetStatus();
@@ -116,23 +120,22 @@ public:
bool SetProperty(const char *prop, void *ptr);
bool GetProperty(const char *prop, void **ptr, bool remove=false);
void DropEverything();
IPluginRuntime *GetRuntime();
sp::BaseRuntime *runtime() const { return m_pRuntime.get(); }
SourcePawn::IPluginRuntime *GetRuntime();
CNativeOwner *ToNativeOwner() {
return this;
}
struct ExtVar {
std::string name;
std::string file;
char *name;
char *file;
bool autoload;
bool required;
};
typedef std::function<bool(const char *pubvar_name, const ExtVar& ext)> ExtVarCallback;
typedef ke::Function<bool(const sp_pubvar_t *, const ExtVar& ext)> ExtVarCallback;
bool ForEachExtVar(const ExtVarCallback& callback);
void ForEachLibrary(std::function<void(const char *)> callback);
void ForEachLibrary(ke::Function<void(const char *)> callback);
public:
/**
* Creates a plugin object with default values.
@@ -193,7 +196,7 @@ public:
m_Libraries.push_back(name);
}
inline bool HasLibrary(const char *name) {
return std::find(m_Libraries.begin(), m_Libraries.end(), name) != m_Libraries.end();
return m_Libraries.find(name) != m_Libraries.end();
}
void LibraryActions(LibraryAction action);
void SyncMaxClients(int max_clients);
@@ -215,7 +218,7 @@ public:
}
void AddRequiredLib(const char *name);
bool ForEachRequiredLib(std::function<bool(const char *)> callback);
bool ForEachRequiredLib(ke::Function<bool(const char *)> callback);
bool HasMissingFakeNatives() const {
return m_FakeNativesMissing;
@@ -267,18 +270,18 @@ private:
char m_errormsg[256];
// Internal properties that must by reset if the runtime is evicted.
std::unique_ptr<sp::BaseRuntime> m_pRuntime;
std::unique_ptr<IPluginRuntime> m_pRuntime;
std::unique_ptr<CPhraseCollection> m_pPhrases;
IPluginContext *m_pContext;
sp_pubvar_t *m_MaxClientsVar;
StringHashMap<void *> m_Props;
std::vector<AutoConfig *> m_configs;
std::list<std::string> m_Libraries;
CVector<AutoConfig *> m_configs;
List<String> m_Libraries;
bool m_bGotAllLoaded;
int m_FileVersion;
// Information that survives past eviction.
std::list<std::string> m_RequiredLibs;
List<String> m_RequiredLibs;
IdentityToken_t *m_ident;
time_t m_LastFileModTime;
Handle_t m_handle;
@@ -329,7 +332,7 @@ public: //IScriptManager
size_t maxlength,
bool *wasloaded);
bool UnloadPlugin(IPlugin *plugin);
SMPlugin *FindPluginByContext(IPluginContext *ctx);
IPlugin *FindPluginByContext(const sp_context_t *ctx);
unsigned int GetPluginCount();
IPluginIterator *GetPluginIterator();
void AddPluginsListener(IPluginsListener *listener);
@@ -342,12 +345,18 @@ public: //IScriptManager
SMPlugin *FindPluginByIdentity(IdentityToken_t *ident) {
return GetPluginFromIdentity(ident);
}
SMPlugin *FindPluginByContext(IPluginContext *ctx) {
return GetPluginByCtx(ctx->GetContext());
}
SMPlugin *FindPluginByContext(sp_context_t *ctx) {
return GetPluginByCtx(ctx);
}
SMPlugin *FindPluginByConsoleArg(const char *text);
SMPlugin *FindPluginByHandle(Handle_t hndl, HandleError *errp) {
return static_cast<SMPlugin *>(PluginFromHandle(hndl, errp));
}
const std::vector<SMPlugin *> *ListPlugins();
void FreePluginList(const std::vector<SMPlugin *> *plugins);
const CVector<SMPlugin *> *ListPlugins();
void FreePluginList(const CVector<SMPlugin *> *plugins);
public: //SMGlobalClass
void OnSourceModAllInitialized();
@@ -390,7 +399,7 @@ public:
/**
* Internal version of FindPluginByContext()
*/
CPlugin *GetPluginByCtx(IPluginContext *ctx);
CPlugin *GetPluginByCtx(const sp_context_t *ctx);
/**
* Gets status text for a status code
@@ -426,7 +435,7 @@ public:
void _SetPauseState(CPlugin *pPlugin, bool pause);
void ForEachPlugin(std::function<void(CPlugin *)> callback);
void ForEachPlugin(ke::Function<void(CPlugin *)> callback);
private:
LoadRes LoadPlugin(CPlugin **pPlugin, const char *path, bool debug, PluginType type);
@@ -504,7 +513,7 @@ private:
IdentityToken_t *m_MyIdent;
/* Dynamic native stuff */
std::list<FakeNative *> m_Natives;
List<FakeNative *> m_Natives;
bool m_LoadingLocked;
+4 -5
View File
@@ -28,7 +28,6 @@
#include "ProfileTools.h"
#include <stdarg.h>
#include <am-string.h>
#include <sourcepawn/vm/environment.h>
ProfileToolManager g_ProfileToolManager;
@@ -88,8 +87,8 @@ ProfileToolManager::StartFromConsole(IProfilingTool *tool)
return;
}
g_pPawnEnv->SetProfilingTool(active_);
g_pPawnEnv->EnableProfiling();
g_pSourcePawn2->SetProfilingTool(active_);
g_pSourcePawn2->EnableProfiling();
rootmenu->ConsolePrint("Started profiling with %s.", active_->Name());
default_ = active_;
@@ -118,8 +117,8 @@ ProfileToolManager::OnRootConsoleCommand(const char *cmdname, const ICommandArgs
rootmenu->ConsolePrint("No profiler is active.");
return;
}
g_pPawnEnv->DisableProfiling();
g_pPawnEnv->SetProfilingTool(nullptr);
g_pSourcePawn2->DisableProfiling();
g_pSourcePawn2->SetProfilingTool(nullptr);
active_->Stop(render_help);
active_ = nullptr;
return;
+169
View File
@@ -0,0 +1,169 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2017 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*/
#include "PseudoAddrManager.h"
#ifdef PLATFORM_APPLE
#include <mach/mach.h>
#include <mach/vm_region.h>
#endif
#ifdef PLATFORM_LINUX
#include <inttypes.h>
#endif
PseudoAddressManager::PseudoAddressManager() : m_NumEntries(0)
{
}
// A pseudo address consists of a table index in the upper 6 bits and an offset in the
// lower 26 bits. The table consists of memory allocation base addresses.
void *PseudoAddressManager::FromPseudoAddress(uint32_t paddr)
{
#ifdef PLATFORM_X64
uint8_t index = paddr >> PSEUDO_OFFSET_BITS;
uint32_t offset = paddr & ((1 << PSEUDO_OFFSET_BITS) - 1);
if (index >= m_NumEntries)
return nullptr;
return reinterpret_cast<void *>(uintptr_t(m_AllocBases[index]) + offset);
#else
return nullptr;
#endif
}
uint32_t PseudoAddressManager::ToPseudoAddress(void *addr)
{
#ifdef PLATFORM_X64
uint8_t index = 0;
uint32_t offset = 0;
bool hasEntry = false;
void *base = GetAllocationBase(addr);
if (base) {
for (int i = 0; i < m_NumEntries; i++) {
if (m_AllocBases[i] == base) {
index = i;
hasEntry = true;
break;
}
}
} else {
return 0;
}
if (!hasEntry) {
index = m_NumEntries;
if (m_NumEntries < SM_ARRAYSIZE(m_AllocBases))
m_AllocBases[m_NumEntries++] = base;
else
return 0; // Table is full
}
ptrdiff_t diff = uintptr_t(addr) - uintptr_t(base);
// Ensure difference fits in 26 bits
if (diff > (UINT32_MAX >> PSEUDO_INDEX_BITS))
return 0;
return (index << PSEUDO_OFFSET_BITS) | diff;
#else
return 0;
#endif
}
void *PseudoAddressManager::GetAllocationBase(void *ptr)
{
#if defined PLATFORM_WINDOWS
MEMORY_BASIC_INFORMATION info;
if (!VirtualQuery(ptr, &info, sizeof(MEMORY_BASIC_INFORMATION)))
return nullptr;
return info.AllocationBase;
#elif defined PLATFORM_APPLE
#ifdef PLATFORM_X86
typedef vm_region_info_t mach_vm_region_info_t;
typedef vm_region_basic_info_data_t mach_vm_region_basic_info_data_t;
const vm_region_flavor_t MACH_VM_REGION_BASIC_INFO = VM_REGION_BASIC_INFO;
const mach_msg_type_number_t MACH_VM_REGION_BASIC_INFO_COUNT = VM_REGION_BASIC_INFO_COUNT;
#define mach_vm_region vm_region
#elif defined PLATFORM_X64
typedef vm_region_info_64_t mach_vm_region_info_t ;
typedef vm_region_basic_info_data_64_t mach_vm_region_basic_info_data_t;
const vm_region_flavor_t MACH_VM_REGION_BASIC_INFO = VM_REGION_BASIC_INFO_64;
const mach_msg_type_number_t MACH_VM_REGION_BASIC_INFO_COUNT = VM_REGION_BASIC_INFO_COUNT_64;
#define mach_vm_region vm_region_64
#endif
vm_size_t size;
vm_address_t vmaddr = reinterpret_cast<vm_address_t>(ptr);
mach_vm_region_basic_info_data_t info;
memory_object_name_t obj;
vm_region_flavor_t flavor = MACH_VM_REGION_BASIC_INFO;
mach_msg_type_number_t count = MACH_VM_REGION_BASIC_INFO_COUNT;
kern_return_t kr = mach_vm_region(mach_task_self(), &vmaddr, &size, flavor,
reinterpret_cast<mach_vm_region_info_t>(&info),
&count, &obj);
if (kr != KERN_SUCCESS)
return nullptr;
return reinterpret_cast<void *>(vmaddr);
#elif defined PLATFORM_LINUX
uintptr_t addr = reinterpret_cast<uintptr_t>(ptr);
// Format:
// lower upper prot stuff path
// 08048000-0804c000 r-xp 00000000 03:03 1010107 /bin/cat
FILE *fp = fopen("/proc/self/maps", "r");
if (fp) {
uintptr_t lower, upper;
while (fscanf(fp, "%" PRIxPTR "-%" PRIxPTR, &lower, &upper) != EOF) {
if (addr >= lower && addr <= upper) {
fclose(fp);
return reinterpret_cast<void *>(lower);
}
// Read to end of line
int c;
while ((c = fgetc(fp)) != '\n') {
if (c == EOF)
break;
}
if (c == EOF)
break;
}
fclose(fp);
}
return nullptr;
#endif
}
+51
View File
@@ -0,0 +1,51 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2017 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*/
#ifndef _INCLUDE_SOURCEMOD_PSEUDOADDRESSMANAGER_H_
#define _INCLUDE_SOURCEMOD_PSEUDOADDRESSMANAGER_H_
#include "common_logic.h"
class PseudoAddressManager
{
public:
PseudoAddressManager();
public:
void *FromPseudoAddress(uint32_t paddr);
uint32_t ToPseudoAddress(void *addr);
private:
void *GetAllocationBase(void *ptr);
private:
static constexpr uint8_t PSEUDO_OFFSET_BITS = 26;
static constexpr uint8_t PSEUDO_INDEX_BITS = sizeof(uint32_t) * 8 - PSEUDO_OFFSET_BITS;
void *m_AllocBases[1 << PSEUDO_INDEX_BITS];
uint8_t m_NumEntries;
};
#endif // _INCLUDE_SOURCEMOD_PSEUDOADDRESSMANAGER_H_
+11 -8
View File
@@ -30,7 +30,6 @@
#include <ISourceMod.h>
#include <bridge/include/CoreProvider.h>
#include "HandleSys.h"
#include <sourcepawn/vm/environment.h>
RootConsoleMenu g_RootMenu;
@@ -43,7 +42,8 @@ RootConsoleMenu::RootConsoleMenu()
RootConsoleMenu::~RootConsoleMenu()
{
for (auto iter=m_Menu.begin(); iter!=m_Menu.end(); iter++)
List<ConsoleEntry *>::iterator iter;
for (iter=m_Menu.begin(); iter!=m_Menu.end(); iter++)
{
delete (*iter);
}
@@ -100,7 +100,7 @@ bool RootConsoleMenu::AddRootConsoleCommand3(const char *cmd,
return false;
/* Sort this into the menu */
auto iter = m_Menu.begin();
List<ConsoleEntry *>::iterator iter = m_Menu.begin();
ConsoleEntry *pEntry;
bool inserted = false;
while (iter != m_Menu.end())
@@ -137,8 +137,9 @@ bool RootConsoleMenu::RemoveRootConsoleCommand(const char *cmd, IRootConsoleComm
{
m_Commands.remove(cmd);
List<ConsoleEntry *>::iterator iter;
ConsoleEntry *pEntry;
for (auto iter=m_Menu.begin(); iter!=m_Menu.end(); iter++)
for (iter=m_Menu.begin(); iter!=m_Menu.end(); iter++)
{
pEntry = (*iter);
if (pEntry->command.compare(cmd) == 0)
@@ -199,8 +200,9 @@ void RootConsoleMenu::GotRootCmd(const ICommandArgs *cmd)
ConsolePrint("SourceMod Menu:");
ConsolePrint("Usage: sm <command> [arguments]");
List<ConsoleEntry *>::iterator iter;
ConsoleEntry *pEntry;
for (auto iter=m_Menu.begin(); iter!=m_Menu.end(); iter++)
for (iter=m_Menu.begin(); iter!=m_Menu.end(); iter++)
{
pEntry = (*iter);
DrawGenericOption(pEntry->command.c_str(), pEntry->description.c_str());
@@ -233,10 +235,11 @@ void RootConsoleMenu::OnRootConsoleCommand(const char *cmdname, const ICommandAr
{
ConsolePrint(" SourceMod Version Information:");
ConsolePrint(" SourceMod Version: %s", SOURCEMOD_VERSION);
if (g_pPawnEnv->IsJitAllowed())
ConsolePrint(" SourcePawn Engine: %s (build %s)", g_pPawnEnv->GetEngineName(), g_pPawnEnv->GetVersionString());
if (g_pSourcePawn2->IsJitEnabled())
ConsolePrint(" SourcePawn Engine: %s (build %s)", g_pSourcePawn2->GetEngineName(), g_pSourcePawn2->GetVersionString());
else
ConsolePrint(" SourcePawn Engine: %s (build %s NO JIT)", g_pPawnEnv->GetEngineName(), g_pPawnEnv->GetVersionString());
ConsolePrint(" SourcePawn Engine: %s (build %s NO JIT)", g_pSourcePawn2->GetEngineName(), g_pSourcePawn2->GetVersionString());
ConsolePrint(" SourcePawn API: v1 = %d, v2 = %d", g_pSourcePawn->GetEngineAPIVersion(), g_pSourcePawn2->GetAPIVersion());
ConsolePrint(" Compiled on: %s", SOURCEMOD_BUILD_TIME);
#if defined(SM_GENERATED_BUILD)
ConsolePrint(" Built from: https://github.com/alliedmodders/sourcemod/commit/%s", SOURCEMOD_SHA);
+6 -5
View File
@@ -29,16 +29,17 @@
#include "common_logic.h"
#include <IRootConsoleMenu.h>
#include <list>
#include <string>
#include <sh_list.h>
#include <sh_string.h>
#include <sm_namehashset.h>
using namespace SourceMod;
using namespace SourceHook;
struct ConsoleEntry
{
std::string command;
std::string description;
String command;
String description;
IRootConsoleCommand *cmd;
static inline bool matches(const char *name, const ConsoleEntry *entry)
@@ -83,7 +84,7 @@ public:
void GotRootCmd(const ICommandArgs *cmd);
private:
NameHashSet<ConsoleEntry *> m_Commands;
std::list<ConsoleEntry *> m_Menu;
List<ConsoleEntry *> m_Menu;
};
extern RootConsoleMenu g_RootMenu;
+9 -12
View File
@@ -39,7 +39,6 @@
#include "common_logic.h"
#include "PluginSys.h"
#include "HandleSys.h"
#include <sourcepawn/vm/base-runtime.h>
using namespace ke;
@@ -233,7 +232,7 @@ void ShareSystem::DestroyIdentType(IdentityType_t type)
void ShareSystem::RemoveInterfaces(IExtension *pExtension)
{
auto iter = m_Interfaces.begin();
List<IfaceInfo>::iterator iter = m_Interfaces.begin();
while (iter != m_Interfaces.end())
{
@@ -278,14 +277,14 @@ void ShareSystem::BeginBindingFor(CPlugin *pPlugin)
void ShareSystem::BindNativesToPlugin(CPlugin *pPlugin, bool bCoreOnly)
{
sp::BaseRuntime *pContext = pPlugin->GetBaseContext()->GetBaseRuntime();
IPluginContext *pContext = pPlugin->GetBaseContext();
BeginBindingFor(pPlugin);
uint32_t native_count = pContext->GetNativesNum();
for (uint32_t i = 0; i < native_count; i++)
{
const sp_native_t *native = pContext->GetNative(i);
const sp_native_t *native = pContext->GetRuntime()->GetNative(i);
if (!native)
continue;
@@ -310,13 +309,13 @@ void ShareSystem::BindNativeToPlugin(CPlugin *pPlugin, const RefPtr<Native> &ent
if (!entry->owner)
return;
sp::BaseRuntime *pContext = pPlugin->GetBaseContext()->GetBaseRuntime();
IPluginContext *pContext = pPlugin->GetBaseContext();
uint32_t i;
if (pContext->FindNativeByName(entry->name(), &i) != SP_ERROR_NONE)
return;
const sp_native_t *native = pContext->GetNative(i);
const sp_native_t *native = pContext->GetRuntime()->GetNative(i);
if (!native)
return;
@@ -365,7 +364,7 @@ void ShareSystem::BindNativeToPlugin(CPlugin *pPlugin, const sp_native_t *native
}
}
auto rt = pPlugin->runtime();
auto rt = pPlugin->GetRuntime();
if (pEntry->fake)
rt->UpdateNativeBindingObject(index, pEntry->fake->wrapper, flags, nullptr);
else
@@ -434,7 +433,7 @@ AlreadyRefed<Native> ShareSystem::AddFakeNative(IPluginFunction *pFunc, const ch
std::unique_ptr<FakeNative> fake(new FakeNative(name, pFunc));
fake->wrapper = new DynamicNative(func, fake.get());
CNativeOwner *owner = g_PluginSys.GetPluginByCtx(fake->ctx);
CNativeOwner *owner = g_PluginSys.GetPluginByCtx(fake->ctx->GetContext());
entry = new Native(owner, std::move(fake));
m_NtvCache.insert(name, entry);
@@ -486,11 +485,10 @@ FeatureStatus ShareSystem::TestFeature(IPluginRuntime *pRuntime, FeatureType fea
FeatureStatus ShareSystem::TestNative(IPluginRuntime *pRuntime, const char *name)
{
uint32_t index;
sp::BaseRuntime *pBase = pRuntime->GetBaseRuntime();
if (pBase->FindNativeByName(name, &index) == SP_ERROR_NONE)
if (pRuntime->FindNativeByName(name, &index) == SP_ERROR_NONE)
{
if (const sp_native_t *native = pBase->GetNative(index)) {
if (const sp_native_t *native = pRuntime->GetNative(index)) {
if (native->status == SP_NATIVE_BOUND)
return FeatureStatus_Available;
else
@@ -513,4 +511,3 @@ FeatureStatus ShareSystem::TestCap(const char *name)
return r->value.provider->GetFeatureStatus(FeatureType_Capability, name);
}

Some files were not shown because too many files have changed in this diff Show More