Coverage for /var/devmt/py/utils4_1.8.0/utils4/cutils.py: 100%
12 statements
« prev ^ index » next coverage.py v7.6.9, created at 2025-08-26 21:39 +0100
« prev ^ index » next coverage.py v7.6.9, created at 2025-08-26 21:39 +0100
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3r"""
4:Purpose: This module provides easy-access wrappers for C-based
5 utilities.
7:Developer: J Berendt
8:Email: development@s3dev.uk
10:Comments: n/a
12:Example:
14 Example for wiping a password from memory::
16 >>> from utils4 import cutils
18 >>> pwd = 'B0bsP@$$word&'
19 >>> _ = cutils.memset(pwd, 0)
20 >>> pwd
21 '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
23"""
25import ctypes
26import gc
27from utils4.reporterror import reporterror
30def memset(obj: object, fill: int=0) -> bool:
31 """Fill the memory address block occupied by ``obj`` with ``repl``.
33 Args:
34 obj (object): Object to be overwritten, usually a string, can be an
35 int. *Not* to be used with complex objects, such as lists, dicts,
36 etc.
37 fill (int, optional): Value to be filled. Defaults to 0.
39 Per the ``ctypes.memset`` documentation:
41 "Same as the standard C memset library function: fills the memory
42 block at address dst with count bytes of value c. dst must be an
43 integer specifying an address, or a ctypes instance."
45 This function is a soft wrapper around the ``ctypes.memset`` function and
46 provides a boolean return value, enabling the caller to test the success
47 of the operation.
49 Additionally, the reference to the ``obj`` object is manually deleted and
50 a garbage collection call is made.
52 Returns:
53 bool: True if the operation succeeds, otherwise False. An operation
54 is deemed successful if the return value from ``ctypes.memset`` is
55 equal to the original memory address of ``obj``.
57 """
58 try:
59 ovh = type(obj)().__sizeof__() - 1
60 loc = id(obj) + ovh
61 size = obj.__sizeof__() - ovh
62 id_ = ctypes.memset(loc, fill, size)
63 del obj
64 gc.collect()
65 except Exception as err:
66 reporterror(err)
67 return loc == id_