private IntPtr weaponNamePtr = 0; private HookResult OnGiveNamedItem(DynamicHook arg) {…
- User
private IntPtr _weaponNamePtr = 0;
code - Assistant
private IntPtr _weaponNamePtr = 0;
private HookResult OnGiveNamedItem(DynamicHook arg)
{
try
{
var weaponName = arg.GetParam<string>(1);
if (IsKnife(weaponName))
{
var services = arg.GetParam<CCSPlayer_WeaponServices>(0);
var player = FindPlayerByWeaponServices(services);
if (player?.TeamSettings == null)
return HookResult.Continue;
var team = player.Controller.TeamNum - 2;
if (team < 0)
return HookResult.Continue;
if (!_knifes.TryGetValue(player.TeamSettings[team].Knife ?? -1, out var knife))
return HookResult.Continue;
var strPtr = Marshal.AllocHGlobal(knife.Length + 1);
var strPtrCopy = strPtr;
foreach (var b in Encoding.ASCII.GetBytes(knife))
{
Marshal.WriteByte(strPtrCopy++, b);
}
Marshal.WriteByte(strPtrCopy, 0);
arg.SetParam<IntPtr>(1, strPtr);
_weaponNamePtr = strPtr;
return HookResult.Changed;
}
}
catch (Exception e)
{
Logger.LogError("Error while handling GiveNamedItemPre: {e}", e);
}
return HookResult.Continue;
}
private HookResult OnGiveNamedItemPost(DynamicHook arg)
{
try
{
var weapon = arg.GetReturn<CBasePlayerWeapon>();
if (weapon.Handle == 0)
return HookResult.Continue;
if (!IsKnife(weapon.DesignerName))
weapon.Entity!.DesignerName = arg.GetParam<string>(1);
var services = arg.GetParam<CCSPlayer_WeaponServices>(0);
var player = FindPlayerByWeaponServices(services);
if (player?.TeamSettings == null)
return HookResult.Continue;
var team = player.Controller.TeamNum - 2;
if (team < 0)
return HookResult.Continue;
var manager = weapon.AttributeManager;
var itemDefId = manager.Item.ItemDefinitionIndex;
if (!player.TeamSettings[team].WeaponSettings.TryGetValue(itemDefId, out var weaponSettings))
return HookResult.Continue;
manager.Item.ItemID = 16384;
manager.Item.ItemIDLow = 16384 & 0xFFFFFFFF;
manager.Item.ItemIDHigh = manager.Item.ItemIDLow >> 32;
if (!string.IsNullOrWhiteSpace(weaponSettings.Name))
manager.Item.CustomName = weaponSettings.Name;
weapon.FallbackPaintKit = weaponSettings.Paint;
weaponSettings.Quality += 0.001f;
weapon.FallbackWear = weaponSettings.Quality;
weapon.FallbackSeed = weaponSettings.Pattern;
if (weapon.CBodyComponent is { SceneNode: not null } cBodyComponent)
{
var skeleton = cBodyComponent.SceneNode.GetSkeletonInstance();
skeleton.ModelState.MeshGroupMask = 2;
}
var attributesHandle = manager.Item.NetworkedDynamicAttributes.Handle;
SetAttribute(attributesHandle, "set item texture prefab", weaponSettings.Paint);
SetAttribute(attributesHandle, "set item texture wear", weaponSettings.Quality);
SetAttribute(attributesHandle, "set item texture seed", weaponSettings.Quality);
for (var i = 0; i < weaponSettings.Stickers.Length; i++)
{
unsafe
{
var stickerId = weaponSettings.Stickers[i];
var stickerIdFloat = *(float*)&stickerId;
SetAttribute(attributesHandle, $"sticker slot {i} id", stickerIdFloat);
SetAttribute(manager.Item.AttributeList.Handle, $"sticker slot {i} id", stickerIdFloat);
}
}
}
catch (Exception e)
{
Logger.LogError("Error while handling GiveNamedItemPost: {e}", e);
}
finally
{
if (_weaponNamePtr != 0)
{
Marshal.FreeHGlobal(_weaponNamePtr);
_weaponNamePtr = 0;
}
}
return HookResult.Continue;
}
private SkinsPlayer? FindPlayerByWeaponServices(CCSPlayer_WeaponServices? services)
{
var pawn = services?.Pawn.Value;
if (pawn == null)
return null;
return _players[pawn.As<CCSPlayerPawn>().OriginalController.Value!.Slot];
}
private bool IsKnife(string weapon)
{
return weapon.Contains("knife") || weapon.Contains("bayonet");
}
what can crash there?
The code you provided can potentially crash in several places, but the most critical area prone to causing a crash is within the OnGiveNamedItemPost method, specifically in the unsafe block where you're performing pointer manipulation to reinterpret an int as a float. Here's a detailed analysis:
In the OnGiveNamedItemPost method, there's an unsafe block where you attempt to cast an int to a float using pointer manipulation:
unsafe
{
var stickerId = weaponSettings.Stickers[i];
var stickerIdFloat = *(float*)&stickerId;
SetAttribute(attributesHandle, $"sticker slot {i} id", stickerIdFloat);
SetAttribute(manager.Item.AttributeList.Handle, $"sticker slot {i} id", stickerIdFloat);
}
Issue: This operation is not safe and can lead to an AccessViolationException or other memory corruption issues.
Explanation:
int (stickerId) and casting it to a float*, then dereferencing it to get a float value.int can be safely reinterpreted as a float. The sizes might match, but the bit patterns for int and float are different and reinterpreting them can lead to invalid float values.stickerId is not properly aligned in memory for a float*, or if there's any issue with the pointer, dereferencing it can cause an AccessViolationException, which is not catchable with a regular catch (Exception e) block.Solution:
Use BitConverter to safely convert the bits of the int to a float:
var stickerId = weaponSettings.Stickers[i];
var stickerIdFloat = BitConverter.Int32BitsToSingle(stickerId);
SetAttribute(attributesHandle, $"sticker slot {i} id", stickerIdFloat);
SetAttribute(manager.Item.AttributeList.Handle, $"sticker slot {i} id", stickerIdFloat);
This method ensures the conversion is handled safely by the .NET runtime without unsafe code.
Throughout your code, there are multiple places where you access properties or methods of objects that could potentially be null without checking:
player.Controller.TeamNum: If player or player.Controller is null, accessing TeamNum will throw a NullReferenceException.player.TeamSettings[team]: If TeamSettings is null or does not contain the index team, you'll get an exception.weapon.AttributeManager: If AttributeManager is null, subsequent access will throw an exception.weapon.Entity: You use weapon.Entity! (null-forgiving operator), but if Entity is null, it will still throw an exception when accessing DesignerName.Solution:
?.) where appropriate to safely access members.In loops or array accesses, such as:
for (var i = 0; i < weaponSettings.Stickers.Length; i++)
{
// ...
}
Ensure that weaponSettings.Stickers is not null and that the Length property reflects the valid number of elements.
In the OnGiveNamedItem method, you're allocating unmanaged memory with Marshal.AllocHGlobal but only freeing it in the finally block of OnGiveNamedItemPost. If an exception occurs before you reach that point, or if OnGiveNamedItemPost is not called for some reason, you might have a memory leak.
Solution:
SafeHandle or similar constructs to manage the lifecycle of unmanaged resources.When checking if _weaponNamePtr is zero, you should compare it with IntPtr.Zero instead of 0:
if (_weaponNamePtr != IntPtr.Zero)
{
Marshal.FreeHGlobal(_weaponNamePtr);
_weaponNamePtr = IntPtr.Zero;
}
This is a more robust and idiomatic way to handle IntPtr comparisons in .NET.
Summary:
The code can crash due to unsafe pointer manipulation when converting an int to a float. Replace the unsafe code with a safe alternative like BitConverter.Int32BitsToSingle. Also, add necessary null checks and handle potential exceptions properly to prevent crashes due to unhandled NullReferenceException or IndexOutOfRangeException.
Rewritten unsafe Block Using Safe Code:
for (var i = 0; i < weaponSettings.Stickers.Length; i++)
{
var stickerId = weaponSettings.Stickers[i];
var stickerIdFloat = BitConverter.Int32BitsToSingle(stickerId);
SetAttribute(attributesHandle, $"sticker slot {i} id", stickerIdFloat);
SetAttribute(manager.Item.AttributeList.Handle, $"sticker slot {i} id", stickerIdFloat);
}
By addressing these issues, you can prevent potential crashes in your code.
Not yet included in a published release.