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