Seregon/ShadPKG

A tool for deriving PKG packet encryption keys for ps4 written in c++

C++/47.3 KB/No license
common/bit_field.h
ShadPKG / common / bit_field.h
1// SPDX-FileCopyrightText: 2014 Tony Wasserka
2// SPDX-FileCopyrightText: 2014 Dolphin Emulator Project
3// SPDX-License-Identifier: BSD-3-Clause AND GPL-2.0-or-later
4 
5#pragma once
6 
7#include <cstddef>
8#include <limits>
9#include <type_traits>
10 
11/*
12 * Abstract bitfield class
13 *
14 * Allows endianness-independent access to individual bitfields within some raw
15 * integer value. The assembly generated by this class is identical to the
16 * usage of raw bitfields, so it's a perfectly fine replacement.
17 *
18 * For BitField<X,Y,Z>, X is the distance of the bitfield to the LSB of the
19 * raw value, Y is the length in bits of the bitfield. Z is an integer type
20 * which determines the sign of the bitfield. Z must have the same size as the
21 * raw integer.
22 *
23 *
24 * General usage:
25 *
26 * Create a new union with the raw integer value as a member.
27 * Then for each bitfield you want to expose, add a BitField member
28 * in the union. The template parameters are the bit offset and the number
29 * of desired bits.
30 *
31 * Changes in the bitfield members will then get reflected in the raw integer
32 * value and vice-versa.
33 *
34 *
35 * Sample usage:
36 *
37 * union SomeRegister
38 * {
39 * u32 hex;
40 *
41 * BitField<0,7,u32> first_seven_bits; // unsigned
42 * BitField<7,8,u32> next_eight_bits; // unsigned
43 * BitField<3,15,s32> some_signed_fields; // signed
44 * };
45 *
46 * This is equivalent to the little-endian specific code:
47 *
48 * union SomeRegister
49 * {
50 * u32 hex;
51 *
52 * struct
53 * {
54 * u32 first_seven_bits : 7;
55 * u32 next_eight_bits : 8;
56 * };
57 * struct
58 * {
59 * u32 : 3; // padding
60 * s32 some_signed_fields : 15;
61 * };
62 * };
63 *
64 *
65 * Caveats:
66 *
67 * 1)
68 * BitField provides automatic casting from and to the storage type where
69 * appropriate. However, when using non-typesafe functions like printf, an
70 * explicit cast must be performed on the BitField object to make sure it gets
71 * passed correctly, e.g.:
72 * printf("Value: %d", (s32)some_register.some_signed_fields);
73 *
74 * 2)
75 * Not really a caveat, but potentially irritating: This class is used in some
76 * packed structures that do not guarantee proper alignment. Therefore we have
77 * to use #pragma pack here not to pack the members of the class, but instead
78 * to break GCC's assumption that the members of the class are aligned on
79 * sizeof(StorageType).
80 */
81#pragma pack(1)
82template <std::size_t Position, std::size_t Bits, typename T>
83struct BitField {
84 
85 using Type = T;
86 
87 // UnderlyingType is T for non-enum types and the underlying type of T if
88 // T is an enumeration. Note that T is wrapped within an enable_if in the
89 // former case to workaround compile errors which arise when using
90 // std::underlying_type<T>::type directly.
91 using UnderlyingType = typename std::conditional_t<std::is_enum_v<T>, std::underlying_type<T>,
92 std::enable_if<true, T>>::type;
93 
94 // We store the value as the unsigned type to avoid undefined behaviour on value shifting
95 using StorageType = std::make_unsigned_t<UnderlyingType>;
96 
97 /// Constants to allow limited introspection of fields if needed
98 static constexpr std::size_t position = Position;
99 static constexpr std::size_t bits = Bits;
100 static constexpr StorageType mask = (((StorageType)~0) >> (8 * sizeof(T) - bits)) << position;
101 
102 /**
103 * Formats a value by masking and shifting it according to the field parameters. A value
104 * containing several bitfields can be assembled by formatting each of their values and ORing
105 * the results together.
106 */
107 [[nodiscard]] static constexpr StorageType FormatValue(const T& value) {
108 return (static_cast<StorageType>(value) << position) & mask;
109 }
110 
111 /**
112 * Extracts a value from the passed storage. In most situations prefer use the member functions
113 * (such as Value() or operator T), but this can be used to extract a value from a bitfield
114 * union in a constexpr context.
115 */
116 [[nodiscard]] static constexpr T ExtractValue(const StorageType& storage) {
117 if constexpr (std::numeric_limits<UnderlyingType>::is_signed) {
118 std::size_t shift = 8 * sizeof(T) - bits;
119 return static_cast<T>(static_cast<UnderlyingType>(storage << (shift - position)) >>
120 shift);
121 } else {
122 return static_cast<T>((storage & mask) >> position);
123 }
124 }
125 
126 // This constructor and assignment operator might be considered ambiguous:
127 // Would they initialize the storage or just the bitfield?
128 // Hence, delete them. Use the Assign method to set bitfield values!
129 BitField(T val) = delete;
130 BitField& operator=(T val) = delete;
131 
132 constexpr BitField() noexcept = default;
133 
134 constexpr BitField(const BitField&) noexcept = default;
135 constexpr BitField& operator=(const BitField&) noexcept = default;
136 
137 constexpr BitField(BitField&&) noexcept = default;
138 constexpr BitField& operator=(BitField&&) noexcept = default;
139 
140 [[nodiscard]] constexpr operator T() const {
141 return Value();
142 }
143 
144 constexpr void Assign(const T& value) {
145 storage = (static_cast<StorageType>(storage) & ~mask) | FormatValue(value);
146 }
147 
148 [[nodiscard]] constexpr T Value() const {
149 return ExtractValue(storage);
150 }
151 
152 [[nodiscard]] constexpr explicit operator bool() const {
153 return Value() != 0;
154 }
155 
156private:
157 StorageType storage;
158 
159 static_assert(bits + position <= 8 * sizeof(T), "Bitfield out of range");
160 
161 // And, you know, just in case people specify something stupid like bits=position=0x80000000
162 static_assert(position < 8 * sizeof(T), "Invalid position");
163 static_assert(bits <= 8 * sizeof(T), "Invalid number of bits");
164 static_assert(bits > 0, "Invalid number of bits");
165 static_assert(std::is_trivially_copyable_v<T>, "T must be trivially copyable in a BitField");
166};
167#pragma pack()
168