repo_name
string | dataset
string | owner
string | lang
string | func_name
string | code
string | docstring
string | url
string | sha
string |
|---|---|---|---|---|---|---|---|---|
BugChecker
|
github_2023
|
vitoplantamura
|
c
|
ZydisCompareRequestToInstruction
|
void ZydisCompareRequestToInstruction(const ZydisEncoderRequest *request,
const ZydisDecodedInstruction *insn, const ZydisDecodedOperand* operands, const ZyanU8 *insn_bytes)
{
// Special case, `xchg rAX, rAX` is an alias for `NOP`
if ((request->mnemonic == ZYDIS_MNEMONIC_XCHG) &&
(request->operand_count == 2) &&
(request->operands[0].type == ZYDIS_OPERAND_TYPE_REGISTER) &&
(request->operands[1].type == ZYDIS_OPERAND_TYPE_REGISTER) &&
(request->operands[0].reg.value == request->operands[1].reg.value) &&
(insn->mnemonic == ZYDIS_MNEMONIC_NOP))
{
switch (request->operands[0].reg.value)
{
case ZYDIS_REGISTER_AX:
case ZYDIS_REGISTER_EAX:
case ZYDIS_REGISTER_RAX:
return;
default:
break;
}
}
// Handle possible KNC overlap
ZydisDecodedInstruction knc_insn;
ZydisDecodedOperand knc_operands[ZYDIS_MAX_OPERAND_COUNT_VISIBLE];
if (request->mnemonic != insn->mnemonic)
{
ZydisDecoder decoder;
ZydisStackWidth stack_width = (ZydisStackWidth)(insn->stack_width >> 5);
if (!ZYAN_SUCCESS(ZydisDecoderInit(&decoder, insn->machine_mode, stack_width)))
{
fputs("Failed to initialize decoder\n", ZYAN_STDERR);
abort();
}
if (!ZYAN_SUCCESS(ZydisDecoderEnableMode(&decoder, ZYDIS_DECODER_MODE_KNC, ZYAN_TRUE)))
{
fputs("Failed to enable KNC mode\n", ZYAN_STDERR);
abort();
}
if (!ZYAN_SUCCESS(ZydisDecoderDecodeFull(&decoder, insn_bytes, insn->length, &knc_insn,
knc_operands, ZYDIS_MAX_OPERAND_COUNT_VISIBLE, ZYDIS_DFLAG_VISIBLE_OPERANDS_ONLY)))
{
fputs("Failed to decode instruction\n", ZYAN_STDERR);
abort();
}
insn = &knc_insn;
operands = knc_operands;
}
ZyanBool prefixes_match = ((insn->attributes & request->prefixes) == request->prefixes);
if (!prefixes_match &&
(request->machine_mode != ZYDIS_MACHINE_MODE_LONG_64) &&
(request->prefixes & ZYDIS_ATTRIB_HAS_SEGMENT_DS))
{
// Encoder allows specifying DS override even when it might be interpreted as NOTRACK
ZyanU64 acceptable_prefixes = (request->prefixes & (~ZYDIS_ATTRIB_HAS_SEGMENT_DS)) |
ZYDIS_ATTRIB_HAS_NOTRACK;
prefixes_match = ((insn->attributes & acceptable_prefixes) == acceptable_prefixes);
}
if ((request->machine_mode != insn->machine_mode) ||
(request->mnemonic != insn->mnemonic) ||
(request->operand_count != insn->operand_count_visible) ||
!prefixes_match)
{
fputs("Basic instruction attributes mismatch\n", ZYAN_STDERR);
abort();
}
for (ZyanU8 i = 0; i < insn->operand_count_visible; ++i)
{
const ZydisEncoderOperand *op1 = &request->operands[i];
const ZydisDecodedOperand *op2 = &operands[i];
if (op1->type != op2->type)
{
fprintf(ZYAN_STDERR, "Mismatch for operand %u\n", i);
abort();
}
switch (op1->type)
{
case ZYDIS_OPERAND_TYPE_REGISTER:
if (op1->reg.value != op2->reg.value)
{
fprintf(ZYAN_STDERR, "Mismatch for register operand %u\n", i);
abort();
}
break;
case ZYDIS_OPERAND_TYPE_MEMORY:
if ((op1->mem.base != op2->mem.base) ||
(op1->mem.index != op2->mem.index) ||
(op1->mem.scale != op2->mem.scale && op2->mem.type != ZYDIS_MEMOP_TYPE_MIB) ||
(op1->mem.displacement != op2->mem.disp.value))
{
ZyanBool acceptable_mismatch = ZYAN_FALSE;
if (op1->mem.displacement != op2->mem.disp.value)
{
if ((op2->mem.disp.has_displacement) &&
(op1->mem.index == ZYDIS_REGISTER_NONE) &&
((op1->mem.base == ZYDIS_REGISTER_NONE) ||
(op1->mem.base == ZYDIS_REGISTER_EIP) ||
(op1->mem.base == ZYDIS_REGISTER_RIP)))
{
ZyanU64 addr;
ZydisCalcAbsoluteAddress(insn, op2, 0, &addr);
acceptable_mismatch = ((ZyanU64)op1->mem.displacement == addr);
}
if ((insn->machine_mode == ZYDIS_MACHINE_MODE_REAL_16) ||
(insn->machine_mode == ZYDIS_MACHINE_MODE_LEGACY_16) ||
(insn->machine_mode == ZYDIS_MACHINE_MODE_LONG_COMPAT_16) ||
(insn->stack_width == 16) ||
(insn->address_width == 16))
{
acceptable_mismatch = ((op1->mem.displacement & 0xFFFF) ==
(op2->mem.disp.value & 0xFFFF));
}
}
if (!acceptable_mismatch)
{
fprintf(ZYAN_STDERR, "Mismatch for memory operand %u\n", i);
abort();
}
}
break;
case ZYDIS_OPERAND_TYPE_POINTER:
if ((op1->ptr.segment != op2->ptr.segment) ||
(op1->ptr.offset != op2->ptr.offset))
{
fprintf(ZYAN_STDERR, "Mismatch for pointer operand %u\n", i);
abort();
}
break;
case ZYDIS_OPERAND_TYPE_IMMEDIATE:
if (op1->imm.u != op2->imm.value.u)
{
ZyanBool acceptable_mismatch = ZYAN_FALSE;
if ((insn->meta.category == ZYDIS_CATEGORY_DATAXFER) ||
(insn->meta.category == ZYDIS_CATEGORY_LOGICAL))
{
if (op2->size < 64)
{
ZyanU64 mask = (1ULL << op2->size) - 1;
acceptable_mismatch =
(op1->imm.u & mask) == (op2->imm.value.u & mask);
}
else
{
acceptable_mismatch = op1->imm.u == op2->imm.value.u;
}
}
if (!acceptable_mismatch)
{
fprintf(ZYAN_STDERR, "Mismatch for immediate operand %u\n", i);
abort();
}
}
break;
default:
fprintf(ZYAN_STDERR, "Invalid operand type for operand %u\n", i);
abort();
}
}
}
|
/* ============================================================================================== */
/* Fuzz target */
/* ============================================================================================== */
// TODO: This could check `EVEX`/`MVEX` stuff as well
|
https://github.com/vitoplantamura/BugChecker/blob/8b81e76efe457b59be3a6e752efd43916ba0cabb/dependencies/zydis/tools/ZydisFuzzEncoder.c#L40-L200
|
8b81e76efe457b59be3a6e752efd43916ba0cabb
|
BugChecker
|
github_2023
|
vitoplantamura
|
c
|
ZydisStdinRead
|
ZyanUSize ZydisStdinRead(void *ctx, ZyanU8* buf, ZyanUSize max_len)
{
ZYAN_UNUSED(ctx);
return fread(buf, 1, max_len, ZYAN_STDIN);
}
|
/* ============================================================================================== */
/* Stream reading abstraction */
/* ============================================================================================== */
|
https://github.com/vitoplantamura/BugChecker/blob/8b81e76efe457b59be3a6e752efd43916ba0cabb/dependencies/zydis/tools/ZydisFuzzShared.c#L46-L50
|
8b81e76efe457b59be3a6e752efd43916ba0cabb
|
BugChecker
|
github_2023
|
vitoplantamura
|
c
|
ZydisValidateEnumRanges
|
void ZydisValidateEnumRanges(const ZydisDecodedInstruction* insn,
const ZydisDecodedOperand* operands, ZyanU8 operand_count)
{
# define ZYDIS_CHECK_ENUM(value, max) \
if ((ZyanU64)(value) > (ZyanU64)(max)) \
{ \
fprintf(stderr, "Value " #value " = 0x%016" PRIX64 " is above expected max " #max \
" = 0x%016" PRIX64 "\n", (ZyanU64)(value), (ZyanU64)(max)); \
abort(); \
}
ZYDIS_CHECK_ENUM(insn->length, ZYDIS_MAX_INSTRUCTION_LENGTH);
ZYDIS_CHECK_ENUM(insn->machine_mode, ZYDIS_MACHINE_MODE_MAX_VALUE);
ZYDIS_CHECK_ENUM(insn->mnemonic, ZYDIS_MNEMONIC_MAX_VALUE);
ZYDIS_CHECK_ENUM(insn->encoding, ZYDIS_INSTRUCTION_ENCODING_MAX_VALUE);
ZYDIS_CHECK_ENUM(insn->opcode_map, ZYDIS_OPCODE_MAP_MAX_VALUE);
ZYDIS_CHECK_ENUM(insn->opcode_map, ZYDIS_OPCODE_MAP_MAX_VALUE);
// Operands.
for (ZyanU32 i = 0; i < operand_count; ++i)
{
const ZydisDecodedOperand* op = &operands[i];
ZYDIS_CHECK_ENUM(op->type, ZYDIS_OPERAND_TYPE_MAX_VALUE);
ZYDIS_CHECK_ENUM(op->visibility, ZYDIS_OPERAND_VISIBILITY_MAX_VALUE);
ZYDIS_CHECK_ENUM(op->encoding, ZYDIS_OPERAND_ENCODING_MAX_VALUE);
ZYDIS_CHECK_ENUM(op->element_type, ZYDIS_ELEMENT_TYPE_MAX_VALUE);
ZYDIS_CHECK_ENUM(op->reg.value, ZYDIS_REGISTER_MAX_VALUE);
ZYDIS_CHECK_ENUM(op->mem.type, ZYDIS_MEMOP_TYPE_MAX_VALUE);
ZYDIS_CHECK_ENUM(op->mem.segment, ZYDIS_REGISTER_MAX_VALUE);
ZYDIS_CHECK_ENUM(op->mem.base, ZYDIS_REGISTER_MAX_VALUE);
ZYDIS_CHECK_ENUM(op->mem.index, ZYDIS_REGISTER_MAX_VALUE);
ZYDIS_CHECK_ENUM(op->mem.disp.has_displacement, ZYAN_TRUE);
ZYDIS_CHECK_ENUM(op->imm.is_signed, ZYAN_TRUE);
ZYDIS_CHECK_ENUM(op->imm.is_relative, ZYAN_TRUE);
}
// AVX.
ZYDIS_CHECK_ENUM(insn->avx.mask.mode, ZYDIS_MASK_MODE_MAX_VALUE);
ZYDIS_CHECK_ENUM(insn->avx.mask.reg, ZYDIS_REGISTER_MAX_VALUE);
ZYDIS_CHECK_ENUM(insn->avx.broadcast.is_static, ZYAN_TRUE);
ZYDIS_CHECK_ENUM(insn->avx.broadcast.mode, ZYDIS_BROADCAST_MODE_MAX_VALUE);
ZYDIS_CHECK_ENUM(insn->avx.rounding.mode, ZYDIS_ROUNDING_MODE_MAX_VALUE);
ZYDIS_CHECK_ENUM(insn->avx.swizzle.mode, ZYDIS_SWIZZLE_MODE_MAX_VALUE);
ZYDIS_CHECK_ENUM(insn->avx.conversion.mode, ZYDIS_CONVERSION_MODE_MAX_VALUE);
ZYDIS_CHECK_ENUM(insn->avx.has_sae, ZYAN_TRUE);
ZYDIS_CHECK_ENUM(insn->avx.has_eviction_hint, ZYAN_TRUE);
// Meta.
ZYDIS_CHECK_ENUM(insn->meta.category, ZYDIS_CATEGORY_MAX_VALUE);
ZYDIS_CHECK_ENUM(insn->meta.isa_set, ZYDIS_ISA_SET_MAX_VALUE);
ZYDIS_CHECK_ENUM(insn->meta.isa_ext, ZYDIS_ISA_SET_MAX_VALUE);
ZYDIS_CHECK_ENUM(insn->meta.branch_type, ZYDIS_BRANCH_TYPE_MAX_VALUE);
ZYDIS_CHECK_ENUM(insn->meta.exception_class, ZYDIS_EXCEPTION_CLASS_MAX_VALUE);
// Raw.
for (ZyanU32 i = 0; i < ZYAN_ARRAY_LENGTH(insn->raw.prefixes); ++i)
{
ZYDIS_CHECK_ENUM(insn->raw.prefixes[i].type, ZYDIS_PREFIX_TYPE_MAX_VALUE);
}
for (ZyanU32 i = 0; i < ZYAN_ARRAY_LENGTH(insn->raw.imm); ++i)
{
ZYDIS_CHECK_ENUM(insn->raw.imm[i].is_signed, ZYAN_TRUE);
ZYDIS_CHECK_ENUM(insn->raw.imm[i].is_relative, ZYAN_TRUE);
}
# undef ZYDIS_CHECK_ENUM
}
|
// NOTE: This function doesn't validate flag values, yet.
|
https://github.com/vitoplantamura/BugChecker/blob/8b81e76efe457b59be3a6e752efd43916ba0cabb/dependencies/zydis/tools/ZydisFuzzShared.c#L129-L196
|
8b81e76efe457b59be3a6e752efd43916ba0cabb
|
BugChecker
|
github_2023
|
vitoplantamura
|
c
|
ZydisFuzzerInit
|
int ZydisFuzzerInit()
{
if (ZydisGetVersion() != ZYDIS_VERSION)
{
fputs("Invalid Zydis version\n", ZYAN_STDERR);
return EXIT_FAILURE;
}
#ifdef ZYAN_WINDOWS
// The `stdin` pipe uses text-mode on Windows platforms by default. We need it to be opened in
// binary mode
(void)_setmode(_fileno(ZYAN_STDIN), _O_BINARY);
#endif
return EXIT_SUCCESS;
}
|
/* ============================================================================================== */
/* Entry point */
/* ============================================================================================== */
|
https://github.com/vitoplantamura/BugChecker/blob/8b81e76efe457b59be3a6e752efd43916ba0cabb/dependencies/zydis/tools/ZydisFuzzShared.c#L399-L414
|
8b81e76efe457b59be3a6e752efd43916ba0cabb
|
BugChecker
|
github_2023
|
vitoplantamura
|
c
|
main
|
int main(void)
{
if (ZydisFuzzerInit() != EXIT_SUCCESS)
{
return EXIT_FAILURE;
}
#ifdef ZYDIS_FUZZ_AFL_FAST
while (__AFL_LOOP(1000))
{
ZydisFuzzTarget(&ZydisStdinRead, ZYAN_NULL);
}
return EXIT_SUCCESS;
#else
return ZydisFuzzTarget(&ZydisStdinRead, ZYAN_NULL);
#endif
}
|
// !ZYDIS_LIBFUZZER
|
https://github.com/vitoplantamura/BugChecker/blob/8b81e76efe457b59be3a6e752efd43916ba0cabb/dependencies/zydis/tools/ZydisFuzzShared.c#L447-L463
|
8b81e76efe457b59be3a6e752efd43916ba0cabb
|
BugChecker
|
github_2023
|
vitoplantamura
|
c
|
PrintStatusError
|
static void PrintStatusError(ZyanStatus status, const char* message)
{
ZYAN_ASSERT(ZYAN_FAILED(status));
if (ZYAN_STATUS_MODULE(status) >= ZYAN_MODULE_USER)
{
ZYAN_FPRINTF(ZYAN_STDERR,
"%s%s: User defined status code [0x%" PRIx32 "]%s\n",
CVT100_ERR(COLOR_ERROR), message, status,
CVT100_ERR(ZYAN_VT100SGR_RESET));
}
else
{
ZYAN_FPRINTF(ZYAN_STDERR, "%s%s: %s [0x%" PRIx32 "]%s\n",
CVT100_ERR(COLOR_ERROR), message, FormatZyanStatus(status), status,
CVT100_ERR(ZYAN_VT100SGR_RESET));
}
}
|
/* ---------------------------------------------------------------------------------------------- */
/* Text output */
/* ---------------------------------------------------------------------------------------------- */
/**
* Prints the given error message and status code.
* @param status The status code.
* @param message The error message.
*/
|
https://github.com/vitoplantamura/BugChecker/blob/8b81e76efe457b59be3a6e752efd43916ba0cabb/dependencies/zydis/tools/ZydisInfo.c#L200-L217
|
8b81e76efe457b59be3a6e752efd43916ba0cabb
|
BugChecker
|
github_2023
|
vitoplantamura
|
c
|
PrintSectionHeader
|
static void PrintSectionHeader(const char* name)
{
ZYAN_ASSERT(ZYAN_STRLEN(name) <= 8);
ZYAN_PRINTF("%s== [ %s%8s%s ] ==============================================================" \
"==============================%s\n",
CVT100_OUT(COLOR_HEADER), CVT100_OUT(COLOR_HEADER_TITLE), name, CVT100_OUT(COLOR_HEADER),
CVT100_OUT(COLOR_DEFAULT));
}
|
/**
* Prints a section header.
*
* @param name The section name.
*/
|
https://github.com/vitoplantamura/BugChecker/blob/8b81e76efe457b59be3a6e752efd43916ba0cabb/dependencies/zydis/tools/ZydisInfo.c#L224-L231
|
8b81e76efe457b59be3a6e752efd43916ba0cabb
|
BugChecker
|
github_2023
|
vitoplantamura
|
c
|
PrintValueLabel
|
static void PrintValueLabel(const char* name)
{
ZYAN_ASSERT(ZYAN_STRLEN(name) <= 11);
ZYAN_PRINTF("%s%11s:%s ", CVT100_OUT(COLOR_VALUE_LABEL), name, CVT100_OUT(COLOR_DEFAULT));
}
|
/**
* Prints a value label.
*
* @param name The value name.
*/
|
https://github.com/vitoplantamura/BugChecker/blob/8b81e76efe457b59be3a6e752efd43916ba0cabb/dependencies/zydis/tools/ZydisInfo.c#L238-L242
|
8b81e76efe457b59be3a6e752efd43916ba0cabb
|
BugChecker
|
github_2023
|
vitoplantamura
|
c
|
PrintSegments
|
static void PrintSegments(const ZydisDecodedInstruction* instruction, const ZyanU8* buffer,
ZyanBool print_hints)
{
ZydisInstructionSegments segments;
ZydisGetInstructionSegments(instruction, &segments);
struct
{
ZyanU8 pos;
const char* color;
const char* name;
} print_info[ZYAN_ARRAY_LENGTH(segments.segments)];
ZyanU8 pos = 0;
ZyanU8 imm = 0;
for (ZyanU8 i = 0; i < segments.count; ++i)
{
print_info[i].pos = pos;
switch (segments.segments[i].type)
{
case ZYDIS_INSTR_SEGMENT_PREFIXES:
print_info[i].color = CVT100_OUT(ZYAN_VT100SGR_FG_BRIGHT_MAGENTA);
print_info[i].name = "PREFIXES";
break;
case ZYDIS_INSTR_SEGMENT_REX:
print_info[i].color = CVT100_OUT(ZYAN_VT100SGR_FG_MAGENTA);
print_info[i].name = "REX";
break;
case ZYDIS_INSTR_SEGMENT_XOP:
print_info[i].color = CVT100_OUT(ZYAN_VT100SGR_FG_MAGENTA);
print_info[i].name = "XOP";
break;
case ZYDIS_INSTR_SEGMENT_VEX:
print_info[i].color = CVT100_OUT(ZYAN_VT100SGR_FG_MAGENTA);
print_info[i].name = "VEX";
break;
case ZYDIS_INSTR_SEGMENT_EVEX:
print_info[i].color = CVT100_OUT(ZYAN_VT100SGR_FG_MAGENTA);
print_info[i].name = "EVEX";
break;
case ZYDIS_INSTR_SEGMENT_MVEX:
print_info[i].color = CVT100_OUT(ZYAN_VT100SGR_FG_MAGENTA);
print_info[i].name = "MVEX";
break;
case ZYDIS_INSTR_SEGMENT_OPCODE:
print_info[i].color = CVT100_OUT(ZYAN_VT100SGR_FG_CYAN);
print_info[i].name = "OPCODE";
break;
case ZYDIS_INSTR_SEGMENT_MODRM:
print_info[i].color = CVT100_OUT(ZYAN_VT100SGR_FG_GREEN);
print_info[i].name = "MODRM";
break;
case ZYDIS_INSTR_SEGMENT_SIB:
print_info[i].color = CVT100_OUT(ZYAN_VT100SGR_FG_BRIGHT_GREEN);
print_info[i].name = "SIB";
break;
case ZYDIS_INSTR_SEGMENT_DISPLACEMENT:
print_info[i].color = CVT100_OUT(ZYAN_VT100SGR_FG_BRIGHT_YELLOW);
print_info[i].name = "DISP";
break;
case ZYDIS_INSTR_SEGMENT_IMMEDIATE:
if (imm == 0)
{
print_info[i].color = CVT100_OUT(ZYAN_VT100SGR_FG_YELLOW);
imm = 1;
} else
{
print_info[i].color = CVT100_OUT(ZYAN_VT100SGR_FG_BRIGHT_YELLOW);
}
print_info[i].name = "IMM";
break;
default:
ZYAN_UNREACHABLE;
}
ZYAN_PRINTF("%s", print_info[i].color);
for (int j = 0; j < segments.segments[i].size; ++j)
{
if (segments.segments[i].type == ZYDIS_INSTR_SEGMENT_PREFIXES)
{
ZYAN_ASSERT(segments.segments[i].size <= instruction->raw.prefix_count);
switch (instruction->raw.prefixes[j].type)
{
case ZYDIS_PREFIX_TYPE_IGNORED:
ZYAN_PRINTF("%s%02X%s ", CVT100_OUT(ZYAN_VT100SGR_FG_BRIGHT_BLACK),
buffer[segments.segments[i].offset + j], print_info[i].color);
pos += 3;
break;
case ZYDIS_PREFIX_TYPE_EFFECTIVE:
pos += (ZyanU8)ZYAN_PRINTF("%02X ", buffer[segments.segments[i].offset + j]);
break;
case ZYDIS_PREFIX_TYPE_MANDATORY:
ZYAN_PRINTF("%s%02X%s ",
CVT100_OUT(ZYAN_VT100SGR_FG_CYAN),
buffer[segments.segments[i].offset + j], print_info[i].color);
pos += 3;
break;
default:
ZYAN_UNREACHABLE;
}
} else
{
pos += (ZyanU8)ZYAN_PRINTF("%02X ", buffer[segments.segments[i].offset + j]);
}
}
}
ZYAN_PRINTF("%s\n", CVT100_OUT(COLOR_DEFAULT));
if (!print_hints)
{
return;
}
for (ZyanU8 i = 0; i < segments.count; ++i)
{
ZyanU8 j = 0;
ZyanU8 k = 0;
while (j <= print_info[segments.count - i - 1].pos)
{
if (j == print_info[k].pos)
{
ZYAN_PRINTF("%s:", print_info[k].color);
++k;
} else
{
ZYAN_PRINTF(" ");
}
++j;
}
ZYAN_PRINTF("..%s%s\n", print_info[segments.count - i - 1].color,
print_info[segments.count - i - 1].name);
}
ZYAN_PRINTF(CVT100_OUT(COLOR_DEFAULT));
}
|
/* ---------------------------------------------------------------------------------------------- */
/* ============================================================================================== */
/* Print functions */
/* ============================================================================================== */
/**
* Prints instruction segments (parts).
*
* @param instruction A pointer to the `ZydisDecodedInstruction` struct.
* @param buffer The buffer that contains the instruction bytes.
* @param print_hints Controls the printing of descriptive hints.
*/
|
https://github.com/vitoplantamura/BugChecker/blob/8b81e76efe457b59be3a6e752efd43916ba0cabb/dependencies/zydis/tools/ZydisInfo.c#L293-L428
|
8b81e76efe457b59be3a6e752efd43916ba0cabb
|
BugChecker
|
github_2023
|
vitoplantamura
|
c
|
PrintSizeOptimizedForm
|
static void PrintSizeOptimizedForm(const ZydisDecoder* decoder,
const ZydisDecodedInstruction* instruction, const ZydisDecodedOperand* operands,
ZyanU8 operand_count)
{
ZydisEncoderRequest request;
ZyanStatus status = ZydisEncoderDecodedInstructionToEncoderRequest(instruction, operands,
operand_count, &request);
if (!ZYAN_SUCCESS(status))
{
PrintStatusError(status, "Failed to craft encoder request");
exit(status);
}
ZyanU8 data[ZYDIS_MAX_INSTRUCTION_LENGTH];
ZyanUSize len = sizeof(data);
status = ZydisEncoderEncodeInstruction(&request, data, &len);
if (!ZYAN_SUCCESS(status))
{
PrintStatusError(status, "Could not encode instruction");
exit(status);
}
ZydisDecodedInstruction new_instruction;
status = ZydisDecoderDecodeFull(decoder, &data, len, &new_instruction, ZYAN_NULL, 0, 0);
if (!ZYAN_SUCCESS(status))
{
PrintStatusError(status, "Could not decode instruction");
exit(status);
}
PrintSegments(&new_instruction, &data[0], ZYAN_FALSE);
}
|
/**
* Prints a size optimized form of the input instruction.
*
* @param decoder A pointer to the `ZydisDecoder` instance.
* @param instruction A pointer to the `ZydisDecodedInstruction` struct.
* @param operands A pointer to the `operands` array.
* @param operand_count The length of the `operands` array.
*/
|
https://github.com/vitoplantamura/BugChecker/blob/8b81e76efe457b59be3a6e752efd43916ba0cabb/dependencies/zydis/tools/ZydisInfo.c#L438-L469
|
8b81e76efe457b59be3a6e752efd43916ba0cabb
|
BugChecker
|
github_2023
|
vitoplantamura
|
c
|
PrintOperands
|
static void PrintOperands(const ZydisDecodedInstruction* instruction,
const ZydisDecodedOperand* operands)
{
PrintSectionHeader("OPERANDS");
ZYAN_PRINTF("%s## TYPE VISIBILITY ACTION ENCODING SIZE NELEM ELEMSZ ELEMTY" \
"PE VALUE%s\n", CVT100_OUT(COLOR_HEADER), CVT100_OUT(COLOR_DEFAULT));
ZYAN_PRINTF("%s-- --------- ---------- ------ ------------ ---- ----- ------ ------" \
"-- ---------------------------%s\n", CVT100_OUT(COLOR_HEADER), CVT100_OUT(COLOR_DEFAULT));
ZyanU8 imm_id = 0;
for (ZyanU8 i = 0; i < instruction->operand_count; ++i)
{
static const char* strings_operand_type[] =
{
"UNUSED",
"REGISTER",
"MEMORY",
"POINTER",
"IMMEDIATE"
};
ZYAN_ASSERT(ZYAN_ARRAY_LENGTH(strings_operand_type) == ZYDIS_OPERAND_TYPE_MAX_VALUE + 1);
static const char* strings_operand_visibility[] =
{
"INVALID",
"EXPLICIT",
"IMPLICIT",
"HIDDEN"
};
ZYAN_ASSERT(ZYAN_ARRAY_LENGTH(strings_operand_visibility) == ZYDIS_OPERAND_VISIBILITY_MAX_VALUE + 1);
static const char* strings_operand_actions[] =
{
"NONE", // 0 0 0 0
"R", // 0 0 0 1
"W", // 0 0 1 0
"RW", // 0 0 1 1
"CR", // 0 1 0 0
"-", // 0 1 0 1
"CRW", // 0 1 1 0
"-", // 0 1 1 1
"CW", // 1 0 0 0
"RCW", // 1 0 0 1
"-", // 1 0 1 0
"-", // 1 0 1 1
"CRCW", // 1 1 0 0
"-", // 1 1 0 1
"-" // 1 1 1 1
};
static const char* strings_element_type[] =
{
"INVALID",
"STRUCT",
"UINT",
"INT",
"FLOAT16",
"FLOAT32",
"FLOAT64",
"FLOAT80",
"LONGBCD",
"CC"
};
ZYAN_ASSERT(ZYAN_ARRAY_LENGTH(strings_element_type) == ZYDIS_ELEMENT_TYPE_MAX_VALUE + 1);
static const char* strings_operand_encoding[] =
{
"NONE",
"MODRM_REG",
"MODRM_RM",
"OPCODE",
"NDSNDD",
"IS4",
"MASK",
"DISP8",
"DISP16",
"DISP32",
"DISP64",
"DISP16_32_64",
"DISP32_32_64",
"DISP16_32_32",
"UIMM8",
"UIMM16",
"UIMM32",
"UIMM64",
"UIMM16_32_64",
"UIMM32_32_64",
"UIMM16_32_32",
"SIMM8",
"SIMM16",
"SIMM32",
"SIMM64",
"SIMM16_32_64",
"SIMM32_32_64",
"SIMM16_32_32",
"JIMM8",
"JIMM16",
"JIMM32",
"JIMM64",
"JIMM16_32_64",
"JIMM32_32_64",
"JIMM16_32_32"
};
ZYAN_ASSERT(ZYAN_ARRAY_LENGTH(strings_operand_encoding) == ZYDIS_OPERAND_ENCODING_MAX_VALUE + 1);
static const char* strings_memop_type[] =
{
"INVALID",
"MEM",
"AGEN",
"MIB",
"VSIB"
};
ZYAN_ASSERT(ZYAN_ARRAY_LENGTH(strings_memop_type) == ZYDIS_MEMOP_TYPE_MAX_VALUE + 1);
ZYAN_PRINTF("%s%2d %s%9s %10s %6s %12s %s%5d %4d %6d %s%8s%s",
CVT100_OUT(COLOR_VALUE_G),
i,
CVT100_OUT(COLOR_VALUE_B),
strings_operand_type[operands[i].type],
strings_operand_visibility[operands[i].visibility],
strings_operand_actions[operands[i].actions],
strings_operand_encoding[operands[i].encoding],
CVT100_OUT(COLOR_VALUE_G),
operands[i].size,
operands[i].element_count,
operands[i].element_size,
CVT100_OUT(COLOR_VALUE_B),
strings_element_type[operands[i].element_type],
CVT100_OUT(COLOR_DEFAULT));
switch (operands[i].type)
{
case ZYDIS_OPERAND_TYPE_REGISTER:
ZYAN_PRINTF(" %s%27s%s", CVT100_OUT(COLOR_VALUE_R),
ZydisRegisterGetString(operands[i].reg.value),
CVT100_OUT(COLOR_DEFAULT));
break;
case ZYDIS_OPERAND_TYPE_MEMORY:
ZYAN_PRINTF(" %sTYPE =%s%20s%s\n", CVT100_OUT(COLOR_VALUE_LABEL),
CVT100_OUT(COLOR_VALUE_B), strings_memop_type[operands[i].mem.type],
CVT100_OUT(COLOR_DEFAULT));
ZYAN_PRINTF(" %s%84s =%s%20s%s\n",
CVT100_OUT(COLOR_VALUE_LABEL), "SEG ", CVT100_OUT(COLOR_VALUE_R),
ZydisRegisterGetString(operands[i].mem.segment),
CVT100_OUT(COLOR_DEFAULT));
ZYAN_PRINTF(" %s%84s =%s%20s%s\n",
CVT100_OUT(COLOR_VALUE_LABEL), "BASE ", CVT100_OUT(COLOR_VALUE_R),
ZydisRegisterGetString(operands[i].mem.base),
CVT100_OUT(COLOR_DEFAULT));
ZYAN_PRINTF(" %s%84s =%s%20s%s\n",
CVT100_OUT(COLOR_VALUE_LABEL), "INDEX", CVT100_OUT(COLOR_VALUE_R),
ZydisRegisterGetString(operands[i].mem.index),
CVT100_OUT(COLOR_DEFAULT));
ZYAN_PRINTF(" %s%84s =%s%20d%s\n",
CVT100_OUT(COLOR_VALUE_LABEL), "SCALE", CVT100_OUT(COLOR_VALUE_G),
operands[i].mem.scale,
CVT100_OUT(COLOR_DEFAULT));
ZYAN_PRINTF(" %s%84s = %s0x%016" PRIX64 "%s",
CVT100_OUT(COLOR_VALUE_LABEL), "DISP ", CVT100_OUT(COLOR_VALUE_G),
operands[i].mem.disp.value,
CVT100_OUT(COLOR_DEFAULT));
break;
case ZYDIS_OPERAND_TYPE_POINTER:
ZYAN_PRINTF(" %sSEG = %s0x%04" PRIX16 "%s\n",
CVT100_OUT(COLOR_VALUE_LABEL), CVT100_OUT(COLOR_VALUE_G),
operands[i].ptr.segment,
CVT100_OUT(COLOR_DEFAULT));
ZYAN_PRINTF(" %s%84s = %s0x%08" PRIX32 "%s",
CVT100_OUT(COLOR_VALUE_LABEL), "OFF ", CVT100_OUT(COLOR_VALUE_G),
operands[i].ptr.offset,
CVT100_OUT(COLOR_DEFAULT));
break;
case ZYDIS_OPERAND_TYPE_IMMEDIATE:
if (operands[i].imm.is_signed)
{
ZYAN_PRINTF(" %s[%s%s %s %s%2d%s] %s0x%016" PRIX64 "%s",
CVT100_OUT(COLOR_VALUE_LABEL),
CVT100_OUT(COLOR_VALUE_B),
operands[i].imm.is_signed ? "S" : "U",
operands[i].imm.is_relative ? "R" : "A",
CVT100_OUT(COLOR_VALUE_G),
instruction->raw.imm[imm_id].size,
CVT100_OUT(COLOR_VALUE_LABEL),
CVT100_OUT(COLOR_VALUE_G),
operands[i].imm.value.s,
CVT100_OUT(COLOR_DEFAULT));
} else
{
ZYAN_PRINTF(" %s[%s%s %s %s%2d%s] %s0x%016" PRIX64 "%s",
CVT100_OUT(COLOR_VALUE_LABEL),
CVT100_OUT(COLOR_VALUE_B),
operands[i].imm.is_signed ? "S" : "U",
operands[i].imm.is_relative ? "R" : "A",
CVT100_OUT(COLOR_VALUE_G),
instruction->raw.imm[imm_id].size,
CVT100_OUT(COLOR_VALUE_LABEL),
CVT100_OUT(COLOR_VALUE_G),
operands[i].imm.value.u,
CVT100_OUT(COLOR_DEFAULT));
}
++imm_id;
break;
default:
ZYAN_UNREACHABLE;
}
ZYAN_PUTS("");
}
ZYAN_PRINTF("%s-- --------- ---------- ------ ------------ ---- ----- ------ ------" \
"-- ---------------------------%s\n", CVT100_OUT(COLOR_HEADER), CVT100_OUT(COLOR_DEFAULT));
}
|
/**
* Prints instruction operands info.
*
* @param instruction A pointer to the `ZydisDecodedInstruction` struct.
* @param operands A pointer to the first `ZydisDecodedOperand` struct of the instruction.
*/
|
https://github.com/vitoplantamura/BugChecker/blob/8b81e76efe457b59be3a6e752efd43916ba0cabb/dependencies/zydis/tools/ZydisInfo.c#L477-L687
|
8b81e76efe457b59be3a6e752efd43916ba0cabb
|
BugChecker
|
github_2023
|
vitoplantamura
|
c
|
PrintFlags
|
static void PrintFlags(const ZydisDecodedInstruction* instruction)
{
static const char* strings_cpu_flags[] =
{
"CF",
ZYAN_NULL,
"PF",
ZYAN_NULL,
"AF",
ZYAN_NULL,
"ZF",
"SF",
"TF",
"IF",
"DF",
"OF",
"IOPL",
ZYAN_NULL,
"NT",
ZYAN_NULL,
"RF",
"VM",
"AC",
"VIF",
"VIP",
"ID",
};
static const char* strings_fpu_flags[] =
{
"C0",
"C1",
"C2",
"C3",
};
typedef struct FlagInfo_
{
const char* name;
const char* action;
} FlagInfo;
FlagInfo flags[ZYAN_ARRAY_LENGTH(strings_cpu_flags) + ZYAN_ARRAY_LENGTH(strings_fpu_flags)];
ZYAN_MEMSET(flags, 0, sizeof(flags));
// CPU
for (ZyanUSize i = 0; i < ZYAN_ARRAY_LENGTH(strings_cpu_flags); ++i)
{
flags[i].name = strings_cpu_flags[i];
flags[i].action = GetAccessedFlagActionString(instruction->cpu_flags, (ZyanU8)i);
}
// FPU
const ZyanUSize offset = ZYAN_ARRAY_LENGTH(strings_cpu_flags);
for (ZyanUSize i = 0; i < ZYAN_ARRAY_LENGTH(strings_fpu_flags); ++i)
{
flags[offset + i].name = strings_fpu_flags[i];
flags[offset + i].action = GetAccessedFlagActionString(instruction->fpu_flags, (ZyanU8)i);
}
PrintSectionHeader("FLAGS");
PrintValueLabel("ACTIONS");
ZyanU8 c = 0;
for (ZyanUSize i = 0; i < ZYAN_ARRAY_LENGTH(flags); ++i)
{
if (flags[i].action == ZYAN_NULL)
{
continue;
}
if (c && (c % 8 == 0))
{
ZYAN_PRINTF("\n ");
}
++c;
ZYAN_PRINTF("%s[%s%-4s%s: %s%-3s%s]%s ",
CVT100_OUT(COLOR_VALUE_LABEL), CVT100_OUT(COLOR_VALUE_B),
flags[i].name,
CVT100_OUT(COLOR_VALUE_LABEL), CVT100_OUT(COLOR_VALUE_B),
flags[i].action,
CVT100_OUT(COLOR_VALUE_LABEL), CVT100_OUT(COLOR_DEFAULT));
}
ZYAN_PUTS("");
PRINT_VALUE_G("READ", "0x%08" PRIX32, instruction->cpu_flags->tested);
PRINT_VALUE_G("WRITTEN", "0x%08" PRIX32,
instruction->cpu_flags->modified |
instruction->cpu_flags->set_0 |
instruction->cpu_flags->set_1 |
instruction->cpu_flags->undefined);
}
|
/**
* Prints instruction flags info.
*
* @param instruction A pointer to the `ZydisDecodedInstruction` struct.
*/
|
https://github.com/vitoplantamura/BugChecker/blob/8b81e76efe457b59be3a6e752efd43916ba0cabb/dependencies/zydis/tools/ZydisInfo.c#L694-L785
|
8b81e76efe457b59be3a6e752efd43916ba0cabb
|
BugChecker
|
github_2023
|
vitoplantamura
|
c
|
PrintAVXInfo
|
static void PrintAVXInfo(const ZydisDecodedInstruction* instruction)
{
static const char* strings_broadcast_mode[] =
{
"NONE",
"1_TO_2",
"1_TO_4",
"1_TO_8",
"1_TO_16",
"1_TO_32",
"1_TO_64",
"2_TO_4",
"2_TO_8",
"2_TO_16",
"4_TO_8",
"4_TO_16",
"8_TO_16"
};
ZYAN_ASSERT(ZYAN_ARRAY_LENGTH(strings_broadcast_mode) == ZYDIS_BROADCAST_MODE_MAX_VALUE + 1);
static const char* strings_mask_mode[] =
{
"INVALID",
"DISABLED",
"MERGING",
"ZEROING",
"CONTROL",
"CONTROL_ZEROING"
};
ZYAN_ASSERT(ZYAN_ARRAY_LENGTH(strings_mask_mode) == ZYDIS_MASK_MODE_MAX_VALUE + 1);
static const char* strings_rounding_mode[] =
{
"DEFAULT",
"RN",
"RD",
"RU",
"RZ"
};
ZYAN_ASSERT(ZYAN_ARRAY_LENGTH(strings_rounding_mode) == ZYDIS_ROUNDING_MODE_MAX_VALUE + 1);
static const char* strings_swizzle_mode[] =
{
"NONE",
"DCBA",
"CDAB",
"BADC",
"DACB",
"AAAA",
"BBBB",
"CCCC",
"DDDD"
};
ZYAN_ASSERT(ZYAN_ARRAY_LENGTH(strings_swizzle_mode) == ZYDIS_SWIZZLE_MODE_MAX_VALUE + 1);
static const char* strings_conversion_mode[] =
{
"NONE",
"FLOAT16",
"SINT8",
"UINT8",
"SINT16",
"UINT16"
};
ZYAN_ASSERT(ZYAN_ARRAY_LENGTH(strings_conversion_mode) == ZYDIS_CONVERSION_MODE_MAX_VALUE + 1);
PrintSectionHeader("AVX");
PRINT_VALUE_B("VECTORLEN", "%03d", instruction->avx.vector_length);
PRINT_VALUE_B("BROADCAST", "%s%s%s", strings_broadcast_mode[instruction->avx.broadcast.mode],
CVT100_OUT(COLOR_VALUE_LABEL), instruction->avx.broadcast.is_static ? " (static)" : "");
switch (instruction->encoding)
{
case ZYDIS_INSTRUCTION_ENCODING_EVEX:
PRINT_VALUE_B("ROUNDING", "%s", strings_rounding_mode[instruction->avx.rounding.mode]);
PRINT_VALUE_B("SAE", "%s", instruction->avx.has_sae ? "Y" : "N");
PRINT_VALUE_R("MASK", "%s %s[%s%s%s]",
ZydisRegisterGetString(instruction->avx.mask.reg),
CVT100_OUT(COLOR_VALUE_LABEL), CVT100_OUT(COLOR_VALUE_B),
strings_mask_mode[instruction->avx.mask.mode], CVT100_OUT(COLOR_VALUE_LABEL));
break;
case ZYDIS_INSTRUCTION_ENCODING_MVEX:
PRINT_VALUE_B("ROUNDING", "%s", strings_rounding_mode[instruction->avx.rounding.mode]);
PRINT_VALUE_B("SAE", "%s", instruction->avx.has_sae ? "Y" : "N");
PRINT_VALUE_R("MASK", "%s %s[%sMERGING%s]",
ZydisRegisterGetString(instruction->avx.mask.reg),
CVT100_OUT(COLOR_VALUE_LABEL), CVT100_OUT(COLOR_VALUE_B),
CVT100_OUT(COLOR_VALUE_LABEL));
PRINT_VALUE_B("EH", "%s", instruction->avx.has_eviction_hint ? "Y" : "N");
PRINT_VALUE_B("SWIZZLE", "%s", strings_swizzle_mode[instruction->avx.swizzle.mode]);
PRINT_VALUE_B("CONVERT", "%s", strings_conversion_mode[instruction->avx.conversion.mode]);
break;
default:
break;
}
}
|
/**
* Prints instruction AVX info.
*
* @param instruction A pointer to the `ZydisDecodedInstruction` struct.
*/
|
https://github.com/vitoplantamura/BugChecker/blob/8b81e76efe457b59be3a6e752efd43916ba0cabb/dependencies/zydis/tools/ZydisInfo.c#L792-L888
|
8b81e76efe457b59be3a6e752efd43916ba0cabb
|
BugChecker
|
github_2023
|
vitoplantamura
|
c
|
PrintTokenizedInstruction
|
static void PrintTokenizedInstruction(const ZydisFormatterToken* token)
{
ZyanStatus status = ZYAN_STATUS_SUCCESS;
while (ZYAN_SUCCESS(status))
{
ZydisTokenType type;
ZyanConstCharPointer value;
if (!ZYAN_SUCCESS(status = ZydisFormatterTokenGetValue(token, &type, &value)))
{
PrintStatusError(status, "Failed to get token value");
exit(status);
}
const char* color;
switch (token->type)
{
case ZYDIS_TOKEN_DELIMITER:
ZYAN_FALLTHROUGH;
case ZYDIS_TOKEN_PARENTHESIS_OPEN:
ZYAN_FALLTHROUGH;
case ZYDIS_TOKEN_PARENTHESIS_CLOSE:
color = CVT100_OUT(ZYAN_VT100SGR_FG_WHITE);
break;
case ZYDIS_TOKEN_PREFIX:
case ZYDIS_TOKEN_MNEMONIC:
color = CVT100_OUT(ZYAN_VT100SGR_FG_BRIGHT_RED);
break;
case ZYDIS_TOKEN_REGISTER:
color = CVT100_OUT(ZYAN_VT100SGR_FG_CYAN);
break;
case ZYDIS_TOKEN_ADDRESS_ABS:
case ZYDIS_TOKEN_ADDRESS_REL:
case ZYDIS_TOKEN_DISPLACEMENT:
color = CVT100_OUT(ZYAN_VT100SGR_FG_BRIGHT_GREEN);
break;
case ZYDIS_TOKEN_IMMEDIATE:
color = CVT100_OUT(ZYAN_VT100SGR_FG_GREEN);
break;
case ZYDIS_TOKEN_TYPECAST:
case ZYDIS_TOKEN_DECORATOR:
color = CVT100_OUT(ZYAN_VT100SGR_FG_WHITE);
break;
default:
color = CVT100_OUT(COLOR_DEFAULT);
break;
}
ZYAN_PRINTF("%s%s", color, value);
status = ZydisFormatterTokenNext(&token);
}
ZYAN_ASSERT(status == ZYAN_STATUS_OUT_OF_RANGE);
ZYAN_PRINTF("%s\n", CVT100_OUT(COLOR_DEFAULT));
}
|
/**
* Prints the tokenized instruction.
*
* @param token A pointer to the first token.
*/
|
https://github.com/vitoplantamura/BugChecker/blob/8b81e76efe457b59be3a6e752efd43916ba0cabb/dependencies/zydis/tools/ZydisInfo.c#L895-L948
|
8b81e76efe457b59be3a6e752efd43916ba0cabb
|
BugChecker
|
github_2023
|
vitoplantamura
|
c
|
PrintDisassembly
|
static void PrintDisassembly(const ZydisDecodedInstruction* instruction,
const ZydisDecodedOperand* operands, ZydisFormatterStyle style)
{
ZyanStatus status;
ZydisFormatter formatter;
switch (style)
{
case ZYDIS_FORMATTER_STYLE_ATT:
if (!ZYAN_SUCCESS(status = ZydisFormatterInit(&formatter, ZYDIS_FORMATTER_STYLE_ATT)))
{
PrintStatusError(status, "Failed to initialize instruction-formatter");
exit(status);
}
PrintSectionHeader("ATT");
break;
case ZYDIS_FORMATTER_STYLE_INTEL:
if (!ZYAN_SUCCESS(status = ZydisFormatterInit(&formatter, ZYDIS_FORMATTER_STYLE_INTEL)) ||
!ZYAN_SUCCESS(status = ZydisFormatterSetProperty(&formatter,
ZYDIS_FORMATTER_PROP_FORCE_SEGMENT, ZYAN_TRUE)) ||
!ZYAN_SUCCESS(status = ZydisFormatterSetProperty(&formatter,
ZYDIS_FORMATTER_PROP_FORCE_SIZE, ZYAN_TRUE)))
{
PrintStatusError(status, "Failed to initialize instruction-formatter");
exit(status);
}
PrintSectionHeader("INTEL");
break;
default:
ZYAN_UNREACHABLE;
}
ZyanU8 buffer[256];
const ZydisFormatterToken* token;
PrintValueLabel("ABSOLUTE");
if (!ZYAN_SUCCESS(status = ZydisFormatterTokenizeInstruction(&formatter, instruction, operands,
instruction->operand_count_visible, buffer, sizeof(buffer), 0, &token)))
{
PrintStatusError(status, "Failed to tokenize instruction");
exit(status);
}
PrintTokenizedInstruction(token);
PrintValueLabel("RELATIVE");
if (!ZYAN_SUCCESS(status = ZydisFormatterTokenizeInstruction(&formatter, instruction, operands,
instruction->operand_count_visible, buffer, sizeof(buffer), ZYDIS_RUNTIME_ADDRESS_NONE,
&token)))
{
PrintStatusError(status, "Failed to tokenize instruction");
exit(status);
}
PrintTokenizedInstruction(token);
}
|
/**
* Prints the formatted instruction disassembly.
*
* @param instruction A pointer to the `ZydisDecodedInstruction` struct.
* @param operands A pointer to the first `ZydisDecodedOperand` struct of the instruction.
* @param style The formatter style.
*/
|
https://github.com/vitoplantamura/BugChecker/blob/8b81e76efe457b59be3a6e752efd43916ba0cabb/dependencies/zydis/tools/ZydisInfo.c#L957-L1009
|
8b81e76efe457b59be3a6e752efd43916ba0cabb
|
BugChecker
|
github_2023
|
vitoplantamura
|
c
|
PrintInstruction
|
static void PrintInstruction(const ZydisDecoder* decoder,
const ZydisDecodedInstruction* instruction, const ZydisDecodedOperand* operands)
{
static const char* opcode_maps[] =
{
"DEFAULT",
"0F",
"0F38",
"0F3A",
"MAP4",
"MAP5",
"MAP6",
"MAP7",
"0F0F",
"XOP8",
"XOP9",
"XOPA"
};
ZYAN_ASSERT(ZYAN_ARRAY_LENGTH(opcode_maps) == ZYDIS_OPCODE_MAP_MAX_VALUE + 1);
static const char* instr_encodings[] =
{
"DEFAULT",
"3DNOW",
"XOP",
"VEX",
"EVEX",
"MVEX"
};
ZYAN_ASSERT(ZYAN_ARRAY_LENGTH(instr_encodings) == ZYDIS_INSTRUCTION_ENCODING_MAX_VALUE + 1);
static const char* exception_classes[] =
{
"NONE",
"SSE1",
"SSE2",
"SSE3",
"SSE4",
"SSE5",
"SSE7",
"AVX1",
"AVX2",
"AVX3",
"AVX4",
"AVX5",
"AVX6",
"AVX7",
"AVX8",
"AVX11",
"AVX12",
"E1",
"E1NF",
"E2",
"E2NF",
"E3",
"E3NF",
"E4",
"E4NF",
"E5",
"E5NF",
"E6",
"E6NF",
"E7NM",
"E7NM128",
"E9NF",
"E10",
"E10NF",
"E11",
"E11NF",
"E12",
"E12NP",
"K20",
"K21",
"AMXE1",
"AMXE2",
"AMXE3",
"AMXE4",
"AMXE5",
"AMXE6"
};
ZYAN_ASSERT(ZYAN_ARRAY_LENGTH(exception_classes) == ZYDIS_EXCEPTION_CLASS_MAX_VALUE + 1);
static const struct
{
ZydisInstructionAttributes attribute_mask;
const char* str;
} attribute_map[] =
{
{ ZYDIS_ATTRIB_HAS_MODRM, "HAS_MODRM" },
{ ZYDIS_ATTRIB_HAS_SIB, "HAS_SIB" },
{ ZYDIS_ATTRIB_HAS_REX, "HAS_REX" },
{ ZYDIS_ATTRIB_HAS_XOP, "HAS_XOP" },
{ ZYDIS_ATTRIB_HAS_VEX, "HAS_VEX" },
{ ZYDIS_ATTRIB_HAS_EVEX, "HAS_EVEX" },
{ ZYDIS_ATTRIB_HAS_MVEX, "HAS_MVEX" },
{ ZYDIS_ATTRIB_IS_RELATIVE, "IS_RELATIVE" },
{ ZYDIS_ATTRIB_IS_PRIVILEGED, "IS_PRIVILEGED" },
{ ZYDIS_ATTRIB_CPUFLAG_ACCESS, "CPUFLAG_ACCESS" },
{ ZYDIS_ATTRIB_CPU_STATE_CR, "CPU_STATE_CR" },
{ ZYDIS_ATTRIB_CPU_STATE_CW, "CPU_STATE_CW" },
{ ZYDIS_ATTRIB_FPU_STATE_CR, "FPU_STATE_CR" },
{ ZYDIS_ATTRIB_FPU_STATE_CW, "FPU_STATE_CW" },
{ ZYDIS_ATTRIB_XMM_STATE_CR, "XMM_STATE_CR" },
{ ZYDIS_ATTRIB_XMM_STATE_CW, "XMM_STATE_CW" },
{ ZYDIS_ATTRIB_ACCEPTS_LOCK, "ACCEPTS_LOCK" },
{ ZYDIS_ATTRIB_ACCEPTS_REP, "ACCEPTS_REP" },
{ ZYDIS_ATTRIB_ACCEPTS_REPE, "ACCEPTS_REPE" },
{ ZYDIS_ATTRIB_ACCEPTS_REPZ, "ACCEPTS_REPZ" },
{ ZYDIS_ATTRIB_ACCEPTS_REPNE, "ACCEPTS_REPNE" },
{ ZYDIS_ATTRIB_ACCEPTS_REPNZ, "ACCEPTS_REPNZ" },
{ ZYDIS_ATTRIB_ACCEPTS_BND, "ACCEPTS_BND" },
{ ZYDIS_ATTRIB_ACCEPTS_XACQUIRE, "ACCEPTS_XACQUIRE" },
{ ZYDIS_ATTRIB_ACCEPTS_XRELEASE, "ACCEPTS_XRELEASE" },
{ ZYDIS_ATTRIB_ACCEPTS_HLE_WITHOUT_LOCK, "ACCEPTS_HLE_WITHOUT_LOCK" },
{ ZYDIS_ATTRIB_ACCEPTS_BRANCH_HINTS, "ACCEPTS_BRANCH_HINTS" },
{ ZYDIS_ATTRIB_ACCEPTS_SEGMENT, "ACCEPTS_SEGMENT" },
{ ZYDIS_ATTRIB_HAS_LOCK, "HAS_LOCK" },
{ ZYDIS_ATTRIB_HAS_REP, "HAS_REP" },
{ ZYDIS_ATTRIB_HAS_REPE, "HAS_REPE" },
{ ZYDIS_ATTRIB_HAS_REPZ, "HAS_REPZ" },
{ ZYDIS_ATTRIB_HAS_REPNE, "HAS_REPNE" },
{ ZYDIS_ATTRIB_HAS_REPNZ, "HAS_REPNZ" },
{ ZYDIS_ATTRIB_HAS_BND, "HAS_BND" },
{ ZYDIS_ATTRIB_HAS_XACQUIRE, "HAS_XACQUIRE" },
{ ZYDIS_ATTRIB_HAS_XRELEASE, "HAS_XRELEASE" },
{ ZYDIS_ATTRIB_HAS_BRANCH_NOT_TAKEN, "HAS_BRANCH_NOT_TAKEN" },
{ ZYDIS_ATTRIB_HAS_BRANCH_TAKEN, "HAS_BRANCH_TAKEN" },
{ ZYDIS_ATTRIB_HAS_SEGMENT, "HAS_SEGMENT" },
{ ZYDIS_ATTRIB_HAS_SEGMENT_CS, "HAS_SEGMENT_CS" },
{ ZYDIS_ATTRIB_HAS_SEGMENT_SS, "HAS_SEGMENT_SS" },
{ ZYDIS_ATTRIB_HAS_SEGMENT_DS, "HAS_SEGMENT_DS" },
{ ZYDIS_ATTRIB_HAS_SEGMENT_ES, "HAS_SEGMENT_ES" },
{ ZYDIS_ATTRIB_HAS_SEGMENT_FS, "HAS_SEGMENT_FS" },
{ ZYDIS_ATTRIB_HAS_SEGMENT_GS, "HAS_SEGMENT_GS" },
{ ZYDIS_ATTRIB_HAS_OPERANDSIZE, "HAS_OPERANDSIZE" },
{ ZYDIS_ATTRIB_HAS_ADDRESSSIZE, "HAS_ADDRESSSIZE" },
{ ZYDIS_ATTRIB_ACCEPTS_NOTRACK, "ACCEPTS_NOTRACK" },
{ ZYDIS_ATTRIB_HAS_NOTRACK, "HAS_NOTRACK" }
};
PrintSectionHeader("BASIC");
PrintValueLabel("MNEMONIC");
ZYAN_PRINTF("%s%s%s [ENC: %s%s%s, MAP: %s%s%s, OPC: %s0x%02X%s]%s\n",
CVT100_OUT(COLOR_VALUE_R), ZydisMnemonicGetString(instruction->mnemonic),
CVT100_OUT(COLOR_VALUE_LABEL),
CVT100_OUT(COLOR_VALUE_B), instr_encodings[instruction->encoding],
CVT100_OUT(COLOR_VALUE_LABEL),
CVT100_OUT(COLOR_VALUE_B), opcode_maps[instruction->opcode_map],
CVT100_OUT(COLOR_VALUE_LABEL),
CVT100_OUT(COLOR_VALUE_G), instruction->opcode,
CVT100_OUT(COLOR_VALUE_LABEL), CVT100_OUT(COLOR_DEFAULT));
PRINT_VALUE_G("LENGTH" , "%2d", instruction->length);
PRINT_VALUE_G("SSZ" , "%2d", instruction->stack_width);
PRINT_VALUE_G("EOSZ" , "%2d", instruction->operand_width);
PRINT_VALUE_G("EASZ" , "%2d", instruction->address_width);
PRINT_VALUE_B("CATEGORY" , "%s" , ZydisCategoryGetString(instruction->meta.category));
PRINT_VALUE_B("ISA-SET" , "%s" , ZydisISASetGetString(instruction->meta.isa_set));
PRINT_VALUE_B("ISA-EXT" , "%s" , ZydisISAExtGetString(instruction->meta.isa_ext));
PRINT_VALUE_B("EXCEPTIONS", "%s" , exception_classes[instruction->meta.exception_class]);
if (instruction->attributes)
{
PrintValueLabel("ATTRIBUTES");
ZYAN_FPUTS(CVT100_OUT(COLOR_VALUE_B), ZYAN_STDOUT);
ZyanUSize len_total = 13;
for (ZyanUSize i = 0; i < ZYAN_ARRAY_LENGTH(attribute_map); ++i)
{
if (instruction->attributes & attribute_map[i].attribute_mask)
{
const ZyanUSize len = ZYAN_STRLEN(attribute_map[i].str);
if (len_total + len > 109)
{
len_total = 13;
ZYAN_PRINTF("\n ");
}
len_total += ZYAN_PRINTF("%s ", attribute_map[i].str);
}
}
ZYAN_PUTS(CVT100_OUT(COLOR_DEFAULT));
}
PrintValueLabel("OPTIMIZED");
PrintSizeOptimizedForm(decoder, instruction, operands, instruction->operand_count_visible);
if (instruction->operand_count > 0)
{
ZYAN_PUTS("");
PrintOperands(instruction, operands);
}
if (instruction->attributes & ZYDIS_ATTRIB_CPUFLAG_ACCESS)
{
ZYAN_PUTS("");
PrintFlags(instruction);
}
if ((instruction->encoding == ZYDIS_INSTRUCTION_ENCODING_XOP) ||
(instruction->encoding == ZYDIS_INSTRUCTION_ENCODING_VEX) ||
(instruction->encoding == ZYDIS_INSTRUCTION_ENCODING_EVEX) ||
(instruction->encoding == ZYDIS_INSTRUCTION_ENCODING_MVEX))
{
ZYAN_PUTS("");
PrintAVXInfo(instruction);
}
ZYAN_PUTS("");
PrintDisassembly(instruction, operands, ZYDIS_FORMATTER_STYLE_ATT);
ZYAN_PUTS("");
PrintDisassembly(instruction, operands, ZYDIS_FORMATTER_STYLE_INTEL);
}
|
/**
* Dumps basic instruction info.
*
* @param decoder A pointer to the `ZydisDecoder` instance.
* @param instruction A pointer to the `ZydisDecodedInstruction` struct.
* @param operands A pointer to the first `ZydisDecodedOperand` struct of the instruction.
*/
|
https://github.com/vitoplantamura/BugChecker/blob/8b81e76efe457b59be3a6e752efd43916ba0cabb/dependencies/zydis/tools/ZydisInfo.c#L1018-L1227
|
8b81e76efe457b59be3a6e752efd43916ba0cabb
|
BugChecker
|
github_2023
|
vitoplantamura
|
c
|
PrintUsage
|
void PrintUsage(int argc, char *argv[])
{
ZYAN_FPRINTF(ZYAN_STDERR, "%sUsage: %s <machine_mode> [stack_width] <hexbytes>\n\n"
"Machine mode: -real|-16|-32|-64\n"
"Stack width: -16|-32|-64%s\n",
CVT100_ERR(COLOR_ERROR), (argc > 0 ? argv[0] : "ZydisInfo"),
CVT100_ERR(ZYAN_VT100SGR_RESET));
}
|
/* ============================================================================================== */
/* Entry point */
/* ============================================================================================== */
|
https://github.com/vitoplantamura/BugChecker/blob/8b81e76efe457b59be3a6e752efd43916ba0cabb/dependencies/zydis/tools/ZydisInfo.c#L1233-L1240
|
8b81e76efe457b59be3a6e752efd43916ba0cabb
|
night-owl.nvim
|
github_2023
|
oxfist
|
c
|
printFooBar
|
void printFooBar(FooBar foobar) {
printf("Foo: %s, Bar: %d\n", foobar.foo, foobar.bar);
}
|
// Function
|
https://github.com/oxfist/night-owl.nvim/blob/86ed124c2f7e118670649701288e024444bf91e5/samples/sample.c#L11-L13
|
86ed124c2f7e118670649701288e024444bf91e5
|
night-owl.nvim
|
github_2023
|
oxfist
|
c
|
printArray
|
void printArray(int arr[], int size) {
for(int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
|
// Loop
|
https://github.com/oxfist/night-owl.nvim/blob/86ed124c2f7e118670649701288e024444bf91e5/samples/sample.c#L19-L24
|
86ed124c2f7e118670649701288e024444bf91e5
|
night-owl.nvim
|
github_2023
|
oxfist
|
c
|
swap
|
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
|
// Pointers
|
https://github.com/oxfist/night-owl.nvim/blob/86ed124c2f7e118670649701288e024444bf91e5/samples/sample.c#L27-L31
|
86ed124c2f7e118670649701288e024444bf91e5
|
dynamicgo
|
github_2023
|
cloudwego
|
c
|
atof_eisel_lemire64
|
bool atof_eisel_lemire64(uint64_t mant, int exp10, int sgn, double *val)
{
if (exp10 < -348 || exp10 > 347)
{
return false;
}
/* Calculate the 2-base exponent of float */
int clz = count_leading_zeroes_u64(mant);
mant <<= clz;
/* lg10/lg2 ≈ 217706>>16 */
uint64_t ret_exp2 = ((uint64_t)((217706 * exp10) >> 16) + 64 + 1023) - ((uint64_t)clz);
/* Calculate the mantissa of float */
u128_output x = mul_u64(mant, POW10_M128_TAB[exp10 + 348][1]); // higher 64 bits of POW10 mantissa
uint64_t x_hi = x.hi;
uint64_t x_lo = x.lo;
/* Wider approximation for the float.
* mant * PWO10_M * exp2 <= ret float < mant * (PWO10_M + 1) * exp2.
* mant * PWO10_M <= ret_man < mant * (PWO10_M + 1)
* If the lower 9 bits of x_hi is 0x1FF and the mant + x_lo is overflow,
* x_hi needs to add 1 for the upper bound, and it is ambiguous for higher 54 bits of ret_man.
*/
if ((x_hi & 0x1FF) == 0x1FF && (x_lo + mant) < mant)
{
/* lower 64 bits of POW10 mantissa */
u128_output y = mul_u64(mant, POW10_M128_TAB[exp10 + 348][0]);
uint64_t merged_hi = x_hi;
uint64_t merged_lo = x_lo + y.hi;
/* lower 64 bits of multiply output overflow */
if (merged_lo < x_lo)
{
merged_hi++;
}
/* Still ambigunous */
if ((merged_hi & 0x1FF) == 0x1FF && (merged_lo + 1) == 0 && (y.lo + mant) < mant)
{
return false;
}
x_hi = merged_hi;
x_lo = merged_lo;
}
/* Remain 54 bits */
int msb = x_hi >> 63;
uint64_t ret_man = x_hi >> (msb + 9);
ret_exp2 -= 1 ^ msb;
/* Half-way Ambiguity */
if ((x_lo == 0) && ((x_hi & 0x1FF) == 0) && ((ret_man & 3) == 1))
{
return false;
}
/* If not half-way, then it's rounding to-nearest
* Remain 53 bits.
*/
ret_man += ret_man & 1;
ret_man >>= 1;
/* If rounding overflowed, shift again */
if ((ret_man >> 53) > 0)
{
ret_man >>= 1;
ret_exp2 += 1;
}
/* ret_exp2 < 0 means subnormal double.
* ret_exp2 >= 0x7FF means INF/inf.
*/
if ((ret_exp2 - 1) >= (0x7FF - 1))
{
return false;
}
/* Get the lower 52 bits as finnal mantissa */
uint64_t bits = (ret_exp2 << 52) | (ret_man & 0x000FFFFFFFFFFFFF);
if (sgn == -1)
{
bits |= 1ull << 63;
}
*(int64_t *)val = bits;
return true;
}
|
/* This is Eisel Lemire ParseFloat algorithm implemented in C.
* reference: https://nigeltao.github.io/blog/2020/eisel-lemire.html
*/
|
https://github.com/cloudwego/dynamicgo/blob/d58b94fc7d71935c30f4716517e1d392149e2666/native/atof_eisel_lemire.c#L74-L161
|
d58b94fc7d71935c30f4716517e1d392149e2666
|
dynamicgo
|
github_2023
|
cloudwego
|
c
|
trim
|
static inline void trim(Decimal *d) {
while (d->nd > 0 && d->d[d->nd - 1] == '0') {
d->nd--;
}
if (d->nd == 0) {
d->dp = 0;
}
}
|
/* trim trailing zeros from number */
|
https://github.com/cloudwego/dynamicgo/blob/d58b94fc7d71935c30f4716517e1d392149e2666/native/atof_native.c#L130-L137
|
d58b94fc7d71935c30f4716517e1d392149e2666
|
dynamicgo
|
github_2023
|
cloudwego
|
c
|
right_shift
|
static inline void right_shift(Decimal *d, uint32_t k) {
int r = 0; // read pointer
int w = 0; // write pointer
uint64_t n = 0;
/* Pick up enough leading digits to cover first shift */
for (; n >> k == 0; r++) {
if (r >= d->nd) {
if (n == 0) {
d->nd = 0; // no digits for this num
return;
}
/* until n has enough bits for right shift */
while (n >> k == 0) {
n *= 10;
r++;
}
break;
}
n = n * 10 + d->d[r] - '0'; // read the value from d.d
}
d->dp -= r - 1; // point shift left
uint64_t mask = (1ull << k) - 1;
uint64_t dig = 0;
/* Pick up a digit, put down a digit */
for (; r < d->nd; r++) {
dig = n >> k;
n &= mask;
d->d[w++] = (char)(dig + '0');
n = n * 10 + d->d[r] - '0';
}
/* Put down extra digits */
while (n > 0) {
dig = n >> k;
n &= mask;
if (w < d->cap) {
d->d[w] = (char)(dig + '0');
w++;
} else if (dig > 0) {
/* truncated */
d->trunc = 1;
}
n *= 10;
}
d->nd = w;
trim(d);
}
|
/* Binary shift right (/ 2) by k bits. k <= maxShift to avoid overflow */
|
https://github.com/cloudwego/dynamicgo/blob/d58b94fc7d71935c30f4716517e1d392149e2666/native/atof_native.c#L140-L190
|
d58b94fc7d71935c30f4716517e1d392149e2666
|
dynamicgo
|
github_2023
|
cloudwego
|
c
|
prefix_is_less
|
static inline bool prefix_is_less(const char *b, const char *s, uint64_t bn) {
int i = 0;
for (; i < bn; i++) {
if (s[i] == '\0') {
return false;
}
if (b[i] != s[i]) {
return b[i] < s[i];
}
}
return s[i] != '\0';
}
|
/* Compare the leading prefix, if b is lexicographically less, return 0 */
|
https://github.com/cloudwego/dynamicgo/blob/d58b94fc7d71935c30f4716517e1d392149e2666/native/atof_native.c#L193-L204
|
d58b94fc7d71935c30f4716517e1d392149e2666
|
dynamicgo
|
github_2023
|
cloudwego
|
c
|
left_shift
|
static inline void left_shift(Decimal *d, uint32_t k) {
int delta = LSHIFT_TAB[k].delta;
if (prefix_is_less(d->d, LSHIFT_TAB[k].cutoff, d->nd)){
delta--;
}
int r = d->nd; // read index
int w = d->nd + delta; // write index
uint64_t n = 0;
uint64_t quo = 0;
uint64_t rem = 0;
/* Pick up a digit, put down a digit */
for (r--; r >= 0; r--) {
n += (uint64_t)(d->d[r] - '0') << k;
quo = n / 10;
rem = n - 10 * quo;
w--;
if (w < d->cap) {
d->d[w] = (char)(rem + '0');
} else if (rem != 0) {
/* truncated */
d->trunc = 1;
}
n = quo;
}
/* Put down extra digits */
while (n > 0) {
quo = n / 10;
rem = n - 10 * quo;
w--;
if (w < d->cap) {
d->d[w] = (char)(rem + '0');
} else if (rem != 0) {
/* truncated */
d->trunc = 1;
}
n = quo;
}
d->nd += delta;
if (d->nd >= d->cap) {
d->nd = d->cap;
}
d->dp += delta;
trim(d);
}
|
/* Binary shift left (* 2) by k bits. k <= maxShift to avoid overflow */
|
https://github.com/cloudwego/dynamicgo/blob/d58b94fc7d71935c30f4716517e1d392149e2666/native/atof_native.c#L207-L255
|
d58b94fc7d71935c30f4716517e1d392149e2666
|
dynamicgo
|
github_2023
|
cloudwego
|
c
|
rounded_integer
|
static inline uint64_t rounded_integer(Decimal *d) {
if (d->dp > 20) { // overflow
return 0xFFFFFFFFFFFFFFFF; //64 bits
}
int i = 0;
uint64_t n = 0;
for (i = 0; i < d->dp && i < d->nd; i++) {
n = n * 10 + (d->d[i] - '0');
}
for (; i < d->dp; i++) {
n *= 10;
}
if (should_roundup(d, d->dp)) {
n++;
}
return n;
}
|
/* Extract integer part, rounded appropriately */
|
https://github.com/cloudwego/dynamicgo/blob/d58b94fc7d71935c30f4716517e1d392149e2666/native/atof_native.c#L302-L319
|
d58b94fc7d71935c30f4716517e1d392149e2666
|
dynamicgo
|
github_2023
|
cloudwego
|
c
|
b64encode
|
void b64encode(GoSlice *out, const GoSlice *src, int mode)
{
char *ob = out->buf + out->len;
char *op = out->buf + out->len;
const char *ip = src->buf;
const char *ie = src->buf + src->len;
const char *st = TabEncodeCharsetStd;
const uint8_t *vt = VecEncodeCharsetStd;
/* check for empty string */
if (src->len == 0)
{
return;
}
/* check for URL encoding */
if (mode & MODE_URL)
{
st = TabEncodeCharsetURL;
vt = VecEncodeCharsetURL;
}
#if USE_AVX2
/* SIMD 24 bytes loop, but the SIMD instruction will load 4 bytes
* past the end, so it's safe only if there are 28 bytes or more left */
while ((ip <= ie - 28) && (mode & MODE_AVX2) != 0)
{
__m128i v0 = _mm_loadu_si128(as_m128c(ip));
__m128i v1 = _mm_loadu_si128(as_m128c(ip + 12));
__m256i vv = encode_avx2(v0, v1, vt);
/* store the result, and advance buffer pointers */
_mm256_storeu_si256(as_m256p(op), vv);
op += 32;
ip += 24;
}
/* can do one more 24 bytes round, but needs special handling */
if ((ip <= ie - 24) && (mode & MODE_AVX2) != 0)
{
__m128i v0 = _mm_loadu_si128(as_m128c(ip));
__m128i v1 = _mm_loadu_si128(as_m128c(ip + 8));
__m128i v2 = _mm_srli_si128(v1, 4);
__m256i vv = encode_avx2(v0, v2, vt);
/* store the result, and advance buffer pointers */
_mm256_storeu_si256(as_m256p(op), vv);
op += 32;
ip += 24;
}
#endif
/* no more bytes */
if (ip == ie)
{
out->len += op - ob;
return;
}
/* handle the remaining bytes with scalar code (with 4 bytes load) */
while (ip <= ie - 4)
{
uint32_t v0 = __builtin_bswap32(*(const uint32_t *)ip);
uint8_t v1 = (v0 >> 26) & 0x3f;
uint8_t v2 = (v0 >> 20) & 0x3f;
uint8_t v3 = (v0 >> 14) & 0x3f;
uint8_t v4 = (v0 >> 8) & 0x3f;
/* encode the characters, and move to next block */
ip += 3;
*op++ = st[v1];
*op++ = st[v2];
*op++ = st[v3];
*op++ = st[v4];
}
/* load the last bytes */
size_t dp = ie - ip;
uint32_t v0 = (uint32_t)(uint8_t)ip[0] << 16;
#define B2 v0 |= (uint32_t)(uint8_t)ip[2]
#define B1 v0 |= (uint32_t)(uint8_t)ip[1] << 8
#define R4 *op++ = st[(v0 >> 0) & 0x3f]
#define R3 *op++ = st[(v0 >> 6) & 0x3f]
#define R2 *op++ = st[(v0 >> 12) & 0x3f]
#define R1 *op++ = st[(v0 >> 18) & 0x3f]
#define NB \
{ \
out->len += op - ob; \
}
#define PD \
{ \
if ((mode & MODE_RAW) == 0) \
{ \
*op++ = '='; \
} \
}
/* encode the last few bytes */
switch (dp)
{
case 3:
B2;
B1;
R1;
R2;
R3;
R4;
NB;
break;
case 2:
B1;
R1;
R2;
R3;
PD;
NB;
break;
case 1:
R1;
R2;
PD;
PD;
NB;
break;
default:
NB;
break;
}
#undef PD
#undef NB
#undef R1
#undef R2
#undef R3
#undef R4
#undef B1
#undef B2
}
|
/** Function Implementations **/
|
https://github.com/cloudwego/dynamicgo/blob/d58b94fc7d71935c30f4716517e1d392149e2666/native/base64.c#L173-L313
|
d58b94fc7d71935c30f4716517e1d392149e2666
|
dynamicgo
|
github_2023
|
cloudwego
|
c
|
decode_block
|
static inline int64_t decode_block(
const uint8_t *ie,
const uint8_t **ipp,
char **opp,
const uint8_t *tab,
int mode)
{
int nb = 0;
uint32_t v0 = 0;
/* buffer pointers */
char *op = *opp;
const uint8_t *ip = *ipp;
/* load up to 4 characters */
while (nb < 4 && ip < ie)
{
uint8_t id;
uint8_t ch = *ip;
/* skip new lines */
if (ch == '\r' || ch == '\n')
{
ip++;
continue;
}
/* lookup the index, and check for invalid characters */
if ((id = tab[ch]) == 0xff)
{
break;
}
/* move to next character */
ip++;
nb++;
v0 = (v0 << 6) | id;
}
/* never ends with 1 characer */
if (nb == 1)
{
return ip - *ipp + 1;
}
#define P2() \
{ \
E2() \
P1() \
P1() \
}
#define P1() \
{ \
if (*ip++ != '=') \
return ip - *ipp; \
} // ip has been added 1
#define E2() \
{ \
if (ip >= ie - 1) \
return ip - *ipp + 1; \
}
#define R1() \
{ \
if ((mode & MODE_RAW) == 0) \
return ip - *ipp + 1; \
}
#define align_val() \
{ \
v0 <<= 6 * (4 - nb); \
}
#define parse_eof() \
{ \
if (ip < ie) \
return ip - *ipp + 1; \
}
#define check_pad() \
{ \
if (ip == ie) \
R1() \
else if (nb == 3) \
P1() \
else \
P2() \
}
/* not enough characters, can either be EOF or paddings or illegal characters */
if (nb < 4)
{
check_pad()
parse_eof()
align_val()
}
#undef check_pad
#undef parse_eof
#undef align_val
#undef R1
#undef E2
#undef P1
#undef P2
/* decode into output */
switch (nb)
{
case 4:
op[2] = (v0 >> 0) & 0xff;
case 3:
op[1] = (v0 >> 8) & 0xff;
case 2:
op[0] = (v0 >> 16) & 0xff;
}
/* update the pointers */
*ipp = ip;
*opp = op + nb - 1;
return 0;
}
|
/* Return 0 if success, otherwise return the error position + 1 */
|
https://github.com/cloudwego/dynamicgo/blob/d58b94fc7d71935c30f4716517e1d392149e2666/native/base64.c#L539-L657
|
d58b94fc7d71935c30f4716517e1d392149e2666
|
dynamicgo
|
github_2023
|
cloudwego
|
c
|
f64todec
|
static inline f64_dec f64todec(uint64_t rsig, int32_t rexp, uint64_t c, int32_t q) {
uint64_t cbl, cb, cbr, vbl, vb, vbr, lower, upper, s;
int32_t k, h;
bool even, irregular, w_inside, u_inside;
f64_dec dec;
even = !(c & 1);
irregular = rsig == 0 && rexp > 1;
cbl = 4 * c - 2 + irregular;
cb = 4 * c;
cbr = 4 * c + 2;
/* q is in [-1500, 1500]
k = irregular ? floor(log_10(3/4 * 2^q)) : floor(log10(pow(2^q)))
floor(log10(3/4 * 2^q)) = (q * 1262611 - 524031) >> 22
floor(log10(pow(2^q))) = (q * 1262611) >> 22 */
k = (q * 1262611 - (irregular ? 524031 : 0)) >> 22;
/* k is in [-1233, 1233]
s = floor(V) = floor(c * 2^q * 10^-k)
vb = 4V = 4 * c * 2^q * 10^-k */
h = q + ((-k) * 1741647 >> 19) + 1;
uint64x2 pow10 = pow10_ceil_sig(-k);
vbl = round_odd(pow10, cbl << h);
vb = round_odd(pow10, cb << h);
vbr = round_odd(pow10, cbr << h);
lower = vbl + !even;
upper = vbr - !even;
s = vb / 4;
if (s >= 10) {
/* R_k+1 interval contains at most one: up or wp */
uint64_t sp = s / 10;
bool up_inside = lower <= (40 * sp);
bool wp_inside = (40 * sp + 40) <= upper;
if (up_inside != wp_inside) {
dec.sig = sp + wp_inside;
dec.exp = k + 1;
return dec;
}
}
/* R_k interval contains at least one: u or w */
u_inside = lower <= (4 * s);
w_inside = (4 * s + 4) <= upper;
if (u_inside != w_inside) {
dec.sig = s + w_inside;
dec.exp = k;
return dec;
}
/* R_k interval contains both u or w */
uint64_t mid = 4 * s + 2;
bool round_up = vb > mid || (vb == mid && (s & 1) != 0);
dec.sig = s + round_up;
dec.exp = k;
return dec;
}
|
/**
Rendering float point number into decimal.
The function used Schubfach algorithm, reference:
The Schubfach way to render doubles, Raffaello Giulietti, 2022-03-20.
https://drive.google.com/file/d/1gp5xv4CAa78SVgCeWfGqqI4FfYYYuNFb
https://mail.openjdk.java.net/pipermail/core-libs-dev/2021-November/083536.html
https://github.com/openjdk/jdk/pull/3402 (Java implementation)
https://github.com/abolz/Drachennest (C++ implementation)
*/
|
https://github.com/cloudwego/dynamicgo/blob/d58b94fc7d71935c30f4716517e1d392149e2666/native/fastfloat.c#L288-L347
|
d58b94fc7d71935c30f4716517e1d392149e2666
|
dynamicgo
|
github_2023
|
cloudwego
|
c
|
_mm_cchars_mask
|
static inline int _mm_cchars_mask(__m128i v)
{
__m128i e1 = _mm_cmpgt_epi8(v, _mm_set1_epi8(-1));
__m128i e2 = _mm_cmpgt_epi8(v, _mm_set1_epi8(31));
return _mm_movemask_epi8(_mm_andnot_si128(e2, e1));
}
|
// contrl char: 0x00 ~ 0x1F
|
https://github.com/cloudwego/dynamicgo/blob/d58b94fc7d71935c30f4716517e1d392149e2666/native/scanning.c#L383-L388
|
d58b94fc7d71935c30f4716517e1d392149e2666
|
dynamicgo
|
github_2023
|
cloudwego
|
c
|
_mm256_cchars_mask
|
static inline int _mm256_cchars_mask(__m256i v)
{
__m256i e1 = _mm256_cmpgt_epi8(v, _mm256_set1_epi8(-1));
__m256i e2 = _mm256_cmpgt_epi8(v, _mm256_set1_epi8(31));
return _mm256_movemask_epi8(_mm256_andnot_si256(e2, e1));
}
|
// contrl char: 0x00 ~ 0x1F
|
https://github.com/cloudwego/dynamicgo/blob/d58b94fc7d71935c30f4716517e1d392149e2666/native/scanning.c#L398-L403
|
d58b94fc7d71935c30f4716517e1d392149e2666
|
dynamicgo
|
github_2023
|
cloudwego
|
c
|
value
|
long value(const char *s, size_t n, long p, JsonState *ret, int allow_control)
{
long q = p;
GoString m = {.buf = s, .len = n};
/* parse the next identifier, q is UNSAFE, may cause out-of-bounds accessing */
switch (advance_ns(&m, &q))
{
case '-': /* fallthrough */
case '0': /* fallthrough */
case '1': /* fallthrough */
case '2': /* fallthrough */
case '3': /* fallthrough */
case '4': /* fallthrough */
case '5': /* fallthrough */
case '6': /* fallthrough */
case '7': /* fallthrough */
case '8': /* fallthrough */
case '9':
vdigits(&m, &q, ret);
return q;
case '"':
vstring(&m, &q, ret);
return q;
case 'n':
ret->vt = advance_dword(&m, &q, 1, V_NULL, VS_NULL);
return q;
case 't':
ret->vt = advance_dword(&m, &q, 1, V_TRUE, VS_TRUE);
return q;
case 'f':
ret->vt = advance_dword(&m, &q, 0, V_FALSE, VS_ALSE);
return q;
case '[':
ret->vt = V_ARRAY;
return q;
case '{':
ret->vt = V_OBJECT;
return q;
case ':':
ret->vt = allow_control ? V_KEY_SEP : -ERR_INVAL;
return allow_control ? q : q - 1;
case ',':
ret->vt = allow_control ? V_ELEM_SEP : -ERR_INVAL;
return allow_control ? q : q - 1;
case ']':
ret->vt = allow_control ? V_ARRAY_END : -ERR_INVAL;
return allow_control ? q : q - 1;
case '}':
ret->vt = allow_control ? V_OBJECT_END : -ERR_INVAL;
return allow_control ? q : q - 1;
case 0:
ret->vt = V_EOF;
return q;
default:
ret->vt = -ERR_INVAL;
return q - 1;
}
}
|
/** Value Scanning Routines **/
|
https://github.com/cloudwego/dynamicgo/blob/d58b94fc7d71935c30f4716517e1d392149e2666/native/scanning.c#L667-L725
|
d58b94fc7d71935c30f4716517e1d392149e2666
|
dynamicgo
|
github_2023
|
cloudwego
|
c
|
check_eof
|
init_ret(V_INTEGER) \
check_eof() \
check_sign(on_neg) \
\
/* check for leading zero or any digits */ \
check_digit() \
check_leading_zero() \
parse_integer_digits(val, sgn, ovf) \
\
/* check for overflow */ \
if (ovf) \
{ \
*p = i - 1; \
ret->vt = -ERR_OVERFLOW; \
return; \
}
|
/* initialize the result, and check for '-' */
|
https://github.com/cloudwego/dynamicgo/blob/d58b94fc7d71935c30f4716517e1d392149e2666/native/scanning.c
|
d58b94fc7d71935c30f4716517e1d392149e2666
|
dynamicgo
|
github_2023
|
cloudwego
|
c
|
is_atof_exact
|
static inline bool is_atof_exact(uint64_t man, int exp, int sgn, double *val)
{
*val = (double)man;
if (man >> 52 != 0)
{
return false;
}
/* equal to if (sgn == -1) { *val *= -1; } */
*(uint64_t *)val |= ((uint64_t)(sgn) >> 63 << 63);
if (exp == 0 || man == 0)
{
return true;
}
else if (exp > 0 && exp <= 15 + 22)
{
/* uint64 integers: accurate range <= 10^15 *
* Powers of 10: accurate range <= 10^22, as P10_TAB *
* Example: man 1, exp 36, is ok */
if (exp > 22)
{
*val *= P10_TAB[exp - 22];
exp = 22;
}
/* f is not accurate when too larger */
if (*val > 1e15 || *val < -1e15)
{
return false;
}
*val *= P10_TAB[exp];
return true;
}
else if (exp < 0 && exp >= -22)
{
*val /= P10_TAB[-exp];
return true;
}
return false;
}
|
/** check whether float can represent the val exactly **/
|
https://github.com/cloudwego/dynamicgo/blob/d58b94fc7d71935c30f4716517e1d392149e2666/native/scanning.c#L883-L926
|
d58b94fc7d71935c30f4716517e1d392149e2666
|
dynamicgo
|
github_2023
|
cloudwego
|
c
|
check_eof
|
init_ret(V_INTEGER)
check_eof()
check_sign(sgn = -1)
/* check for leading zero */
check_digit()
check_leading_zero()
/* parse the integer part */
while (i < n && is_digit(s[i]))
{
add_integer_to_mantissa(man, man_nd, exp10, (s[i] - '0'))
i++;
}
if (exp10 > 0)
{
trunc = 1;
}
/* check for decimal points */
if (i < n && s[i] == '.')
{
i++;
set_vt(V_DOUBLE)
check_eof()
check_digit()
}
|
/* initialize the result, and check for EOF */
|
https://github.com/cloudwego/dynamicgo/blob/d58b94fc7d71935c30f4716517e1d392149e2666/native/scanning.c#L975-L1002
|
d58b94fc7d71935c30f4716517e1d392149e2666
|
dynamicgo
|
github_2023
|
cloudwego
|
c
|
fsm_exec
|
static inline long fsm_exec(StateMachine *self, const GoString *src, long *p, int validate_flag)
{
int vt;
char ch;
long vi = -1;
/* run until no more nested values */
while (self->sp)
{
ch = advance_ns(src, p);
vt = self->vt[self->sp - 1];
/* set the start address if any */
if (vi == -1)
{
vi = *p - 1;
}
/* check for special types */
switch (vt)
{
default:
{
FSM_DROP(self);
break;
}
/* arrays */
case FSM_ARR:
{
switch (ch)
{
case ']':
FSM_DROP(self);
continue;
case ',':
FSM_PUSH(self, FSM_VAL);
continue;
default:
return -ERR_INVAL;
}
}
/* objects */
case FSM_OBJ:
{
switch (ch)
{
case '}':
FSM_DROP(self);
continue;
case ',':
FSM_PUSH(self, FSM_KEY);
continue;
default:
return -ERR_INVAL;
}
}
/* object keys */
case FSM_KEY:
{
FSM_CHAR('"');
FSM_REPL(self, FSM_ELEM);
FSM_XERR(skip_string(src, p));
continue;
}
/* object element */
case FSM_ELEM:
{
FSM_CHAR(':');
FSM_REPL(self, FSM_VAL);
continue;
}
/* arrays, first element */
case FSM_ARR_0:
{
if (ch == ']')
{
FSM_DROP(self);
continue;
}
else
{
FSM_REPL(self, FSM_ARR);
break;
}
}
/* objects, first pair */
case FSM_OBJ_0:
{
switch (ch)
{
default:
{
return -ERR_INVAL;
}
/* empty object */
case '}':
{
FSM_DROP(self);
continue;
}
/* the quote of the first key */
case '"':
{
FSM_REPL(self, FSM_OBJ);
if (validate_flag == VALID_DEFAULT)
{
FSM_XERR(skip_string(src, p));
}
else if (validate_flag == VALID_FULL)
{
FSM_XERR(validate_string(src, p));
}
FSM_PUSH(self, FSM_ELEM);
continue;
}
}
}
}
/* simple values */
switch (ch)
{
case '0': /* fallthrough */
case '1': /* fallthrough */
case '2': /* fallthrough */
case '3': /* fallthrough */
case '4': /* fallthrough */
case '5': /* fallthrough */
case '6': /* fallthrough */
case '7': /* fallthrough */
case '8': /* fallthrough */
case '9':
FSM_XERR(skip_positive(src, p));
break;
case '-':
FSM_XERR(skip_negative(src, p));
break;
case 'n':
FSM_XERR(advance_dword(src, p, 1, *p - 1, VS_NULL));
break;
case 't':
FSM_XERR(advance_dword(src, p, 1, *p - 1, VS_TRUE));
break;
case 'f':
FSM_XERR(advance_dword(src, p, 0, *p - 1, VS_ALSE));
break;
case '[':
FSM_PUSH(self, FSM_ARR_0);
break;
case '{':
FSM_PUSH(self, FSM_OBJ_0);
break;
case '"':
{
if (validate_flag == VALID_DEFAULT)
{
FSM_XERR(skip_string(src, p));
}
else if (validate_flag == VALID_FULL)
{
FSM_XERR(validate_string(src, p));
}
break;
}
case 0:
return -ERR_EOF;
default:
return -ERR_INVAL;
}
}
/* all done */
return vi;
}
|
/** Value Skipping FSM **/
// static inline void FSM_INIT(StateMachine *self, int vt)
// {
// self->sp = 1;
// self->vt[0] = vt;
// }
// static inline long fsm_push(StateMachine *self, int vt)
// {
// if (self->sp >= MAX_RECURSE)
// {
// return -ERR_RECURSE_MAX;
// }
// else
// {
// self->vt[self->sp++] = vt;
// return 0;
// }
// }
|
https://github.com/cloudwego/dynamicgo/blob/d58b94fc7d71935c30f4716517e1d392149e2666/native/scanning.c#L1134-L1315
|
d58b94fc7d71935c30f4716517e1d392149e2666
|
dynamicgo
|
github_2023
|
cloudwego
|
c
|
check_bits
|
check_bits(md)
check_bits(me)
check_bits(ms)
check_vidx(di, md)
check_vidx(ei, me)
check_vidx(si, ms)
/* check for valid number */
if (i != 32)
{
sp += i;
_mm256_zeroupper();
goto check_index;
}
|
/* check & update decimal point, exponent and sign index */
|
https://github.com/cloudwego/dynamicgo/blob/d58b94fc7d71935c30f4716517e1d392149e2666/native/scanning.c#L1385-L1398
|
d58b94fc7d71935c30f4716517e1d392149e2666
|
dynamicgo
|
github_2023
|
cloudwego
|
c
|
check_bits
|
check_bits(md)
check_bits(me)
check_bits(ms)
check_vidx(di, md)
check_vidx(ei, me)
check_vidx(si, ms)
/* check for valid number */
if (i != 16)
{
sp += i;
goto check_index;
}
|
/* check & update exponent and sign index */
|
https://github.com/cloudwego/dynamicgo/blob/d58b94fc7d71935c30f4716517e1d392149e2666/native/scanning.c#L1458-L1470
|
d58b94fc7d71935c30f4716517e1d392149e2666
|
dynamicgo
|
github_2023
|
cloudwego
|
c
|
_mm_ascii_mask
|
static inline int _mm_ascii_mask(__m128i vv)
{
return _mm_movemask_epi8(vv);
}
|
// ascii: 0x00 ~ 0x7F
|
https://github.com/cloudwego/dynamicgo/blob/d58b94fc7d71935c30f4716517e1d392149e2666/native/utf8.c#L21-L24
|
d58b94fc7d71935c30f4716517e1d392149e2666
|
dynamicgo
|
github_2023
|
cloudwego
|
c
|
_mm256_ascii_mask
|
static inline int _mm256_ascii_mask(__m256i vv)
{
return _mm256_movemask_epi8(vv);
}
|
// ascii: 0x00 ~ 0x7F
|
https://github.com/cloudwego/dynamicgo/blob/d58b94fc7d71935c30f4716517e1d392149e2666/native/utf8.c#L29-L32
|
d58b94fc7d71935c30f4716517e1d392149e2666
|
dynamicgo
|
github_2023
|
cloudwego
|
c
|
nonascii_is_utf8
|
static inline ssize_t nonascii_is_utf8(const uint8_t *sp, size_t n)
{
uint8_t mask = first[sp[0]];
uint8_t size = mask & 7;
if (n < size)
{
return 0;
}
struct AcceptRange accept = ranges[mask >> 4];
switch (size)
{
case 4:
if (sp[3] < locb || hicb < sp[3])
return 0;
case 3:
if (sp[2] < locb || hicb < sp[2])
return 0;
case 2:
if (sp[1] < accept.lo || accept.hi < sp[1])
return 0;
break;
case 1:
return 0; // invalid chars
case 0:
return 1; // ascii chars
default:
return 0;
}
return size;
}
|
// UTF-8 code point | first byte | second byte | third byte | fourth byte
// U+0000 - U+007F | 0___ ____
// U+0080 - U+07FF | 110_ ____ | 10__ ____
// U+0800 - U+D7FF | 1110 ____ | 10__ ____ | 10__ ____
// U+D800 - U+DFFF | reserved for UTF-16 surrogate pairs
// U+E000 - U+FFFF | 1110 ____ | 10__ ____ | 10__ ____
// U+10000 - U+10FFFF | 1111 0___ | 10__ ____ | 10__ ____ | 10__ ____
// checks non-ascii characters, and returns the utf-8 length
|
https://github.com/cloudwego/dynamicgo/blob/d58b94fc7d71935c30f4716517e1d392149e2666/native/utf8.c#L101-L130
|
d58b94fc7d71935c30f4716517e1d392149e2666
|
dynamicgo
|
github_2023
|
cloudwego
|
c
|
utf8_validate
|
ssize_t utf8_validate(const char *sp, ssize_t nb)
{
const uint8_t *p = (const uint8_t *)sp;
const uint8_t *s = (const uint8_t *)sp;
ssize_t n;
ssize_t b;
// Optimize for the continuous non-ascii chars */
while (nb > 0 && (n = (!is_ascii(*p) ? 0 : find_non_ascii(p, nb))) != -1)
{
/* not found non-ascii in string */
if (n >= nb)
{
return -1;
}
nb -= n;
p += n;
/* validate the non-ascii */
if (unlikely((b = nonascii_is_utf8(p, nb)) == 0))
{
return p - s;
}
nb -= b;
p += b;
}
return -1;
}
|
// utf8_validate validates whether the JSON string is valid UTF-8.
// return -1 if validate, otherwise, return the error postion.
|
https://github.com/cloudwego/dynamicgo/blob/d58b94fc7d71935c30f4716517e1d392149e2666/native/utf8.c#L183-L213
|
d58b94fc7d71935c30f4716517e1d392149e2666
|
rp2040-psram
|
github_2023
|
polpo
|
c
|
psram_spi_init_clkdiv
|
psram_spi_inst_t psram_spi_init_clkdiv(PIO pio, int sm, float clkdiv, bool fudge) {
psram_spi_inst_t spi;
spi.pio = pio;
spi.offset = pio_add_program(spi.pio, fudge ? &spi_psram_fudge_program : &spi_psram_program);
if (sm == -1) {
spi.sm = pio_claim_unused_sm(spi.pio, true);
} else {
spi.sm = sm;
}
#if defined(PSRAM_MUTEX)
mutex_init(&spi.mtx);
#elif defined(PSRAM_SPINLOCK)
int spin_id = spin_lock_claim_unused(true);
spi.spinlock = spin_lock_init(spin_id);
#endif
gpio_set_drive_strength(PSRAM_PIN_CS, GPIO_DRIVE_STRENGTH_4MA);
gpio_set_drive_strength(PSRAM_PIN_SCK, GPIO_DRIVE_STRENGTH_4MA);
gpio_set_drive_strength(PSRAM_PIN_MOSI, GPIO_DRIVE_STRENGTH_4MA);
/* gpio_set_slew_rate(PSRAM_PIN_CS, GPIO_SLEW_RATE_FAST); */
/* gpio_set_slew_rate(PSRAM_PIN_SCK, GPIO_SLEW_RATE_FAST); */
/* gpio_set_slew_rate(PSRAM_PIN_MOSI, GPIO_SLEW_RATE_FAST); */
pio_spi_psram_cs_init(spi.pio, spi.sm, spi.offset, 8 /*n_bits*/, clkdiv, fudge, PSRAM_PIN_CS, PSRAM_PIN_MOSI, PSRAM_PIN_MISO);
// Write DMA channel setup
spi.write_dma_chan = dma_claim_unused_channel(true);
spi.write_dma_chan_config = dma_channel_get_default_config(spi.write_dma_chan);
channel_config_set_transfer_data_size(&spi.write_dma_chan_config, DMA_SIZE_8);
channel_config_set_read_increment(&spi.write_dma_chan_config, true);
channel_config_set_write_increment(&spi.write_dma_chan_config, false);
channel_config_set_dreq(&spi.write_dma_chan_config, pio_get_dreq(spi.pio, spi.sm, true));
dma_channel_set_write_addr(spi.write_dma_chan, &spi.pio->txf[spi.sm], false);
dma_channel_set_config(spi.write_dma_chan, &spi.write_dma_chan_config, false);
// Read DMA channel setup
spi.read_dma_chan = dma_claim_unused_channel(true);
spi.read_dma_chan_config = dma_channel_get_default_config(spi.read_dma_chan);
channel_config_set_transfer_data_size(&spi.read_dma_chan_config, DMA_SIZE_8);
channel_config_set_read_increment(&spi.read_dma_chan_config, false);
channel_config_set_write_increment(&spi.read_dma_chan_config, true);
channel_config_set_dreq(&spi.read_dma_chan_config, pio_get_dreq(spi.pio, spi.sm, false));
dma_channel_set_read_addr(spi.read_dma_chan, &spi.pio->rxf[spi.sm], false);
dma_channel_set_config(spi.read_dma_chan, &spi.read_dma_chan_config, false);
#if defined(PSRAM_ASYNC)
// Asynchronous DMA channel setup
spi.async_dma_chan = dma_claim_unused_channel(true);
spi.async_dma_chan_config = dma_channel_get_default_config(spi.async_dma_chan);
channel_config_set_transfer_data_size(&spi.async_dma_chan_config, DMA_SIZE_8);
channel_config_set_read_increment(&spi.async_dma_chan_config, true);
channel_config_set_write_increment(&spi.async_dma_chan_config, false);
channel_config_set_dreq(&spi.async_dma_chan_config, pio_get_dreq(spi.pio, spi.sm, true));
dma_channel_set_write_addr(spi.async_dma_chan, &spi.pio->txf[spi.sm], false);
dma_channel_set_config(spi.async_dma_chan, &spi.async_dma_chan_config, false);
#if defined(PSRAM_ASYNC_COMPLETE)
irq_set_exclusive_handler(DMA_IRQ_0 + PSRAM_ASYNC_DMA_IRQ, psram_dma_complete_handler);
dma_irqn_set_channel_enabled(PSRAM_ASYNC_DMA_IRQ, spi.async_dma_chan, true);
irq_set_enabled(DMA_IRQ_0 + PSRAM_ASYNC_DMA_IRQ, true);
#endif // defined(PSRAM_ASYNC_COMPLETE)
#endif // defined(PSRAM_ASYNC)
uint8_t psram_reset_en_cmd[] = {
8, // 8 bits to write
0, // 0 bits to read
0x66u // Reset enable command
};
pio_spi_write_read_dma_blocking(&spi, psram_reset_en_cmd, 3, 0, 0);
busy_wait_us(50);
uint8_t psram_reset_cmd[] = {
8, // 8 bits to write
0, // 0 bits to read
0x99u // Reset command
};
pio_spi_write_read_dma_blocking(&spi, psram_reset_cmd, 3, 0, 0);
busy_wait_us(100);
return spi;
}
|
// defined(PSRAM_ASYNC) && defined(PSRAM_ASYNC_SYNCHRONIZE)
|
https://github.com/polpo/rp2040-psram/blob/febdaf81ac638d711c6ec9efa410d45d20ba9fe9/psram_spi.c
|
febdaf81ac638d711c6ec9efa410d45d20ba9fe9
|
LeetCode_DailyChallenge_2023
|
github_2023
|
7oSkaaa
|
c
|
compare_ints
|
int compare_ints(const int *a, const int *b) {
return *a - *b;
}
|
// Author: Ahmed Gamal
// for this problem we need to sort the array first then check if the difference between each two adjacent elements is the same
// if it is the same then we return true else we return false
// compare function for qsort
|
https://github.com/7oSkaaa/LeetCode_DailyChallenge_2023/blob/e00960b9f5cbfaf813572c366e16d4fef5fa6b8d/06- June/06- Can Make Arithmetic Progression From Sequence/06- Can Make Arithmetic Progression From Sequence (Ahmed Gamal).c#L7-L9
|
e00960b9f5cbfaf813572c366e16d4fef5fa6b8d
|
Whisper
|
github_2023
|
Const-me
|
c
|
LZ4_read16
|
static U16 LZ4_read16(const void* memPtr) { return *(const U16*) memPtr; }
|
/* lie to the compiler about data alignment; use with caution */
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/Utils/LZ4/lz4.c#L371-L371
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
LZ4_read16
|
static U16 LZ4_read16(const void* memPtr)
{
U16 val; LZ4_memcpy(&val, memPtr, sizeof(val)); return val;
}
|
/* safe and portable access using memcpy() */
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/Utils/LZ4/lz4.c#L393-L396
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
LZ4_wildCopy32
|
LZ4_FORCE_INLINE void
LZ4_wildCopy32(void* dstPtr, const void* srcPtr, void* dstEnd)
{
BYTE* d = (BYTE*)dstPtr;
const BYTE* s = (const BYTE*)srcPtr;
BYTE* const e = (BYTE*)dstEnd;
do { LZ4_memcpy(d,s,16); LZ4_memcpy(d+16,s+16,16); d+=32; s+=32; } while (d<e);
}
|
/* customized variant of memcpy, which can overwrite up to 32 bytes beyond dstEnd
* this version copies two times 16 bytes (instead of one time 32 bytes)
* because it must be compatible with offsets >= 16. */
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/Utils/LZ4/lz4.c#L500-L508
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
LZ4_memcpy_using_offset
|
LZ4_FORCE_INLINE void
LZ4_memcpy_using_offset(BYTE* dstPtr, const BYTE* srcPtr, BYTE* dstEnd, const size_t offset)
{
BYTE v[8];
assert(dstEnd >= dstPtr + MINMATCH);
switch(offset) {
case 1:
MEM_INIT(v, *srcPtr, 8);
break;
case 2:
LZ4_memcpy(v, srcPtr, 2);
LZ4_memcpy(&v[2], srcPtr, 2);
#if defined(_MSC_VER) && (_MSC_VER <= 1933) /* MSVC 2022 ver 17.3 or earlier */
# pragma warning(push)
# pragma warning(disable : 6385) /* warning C6385: Reading invalid data from 'v'. */
#endif
LZ4_memcpy(&v[4], v, 4);
#if defined(_MSC_VER) && (_MSC_VER <= 1933) /* MSVC 2022 ver 17.3 or earlier */
# pragma warning(pop)
#endif
break;
case 4:
LZ4_memcpy(v, srcPtr, 4);
LZ4_memcpy(&v[4], srcPtr, 4);
break;
default:
LZ4_memcpy_using_offset_base(dstPtr, srcPtr, dstEnd, offset);
return;
}
LZ4_memcpy(dstPtr, v, 8);
dstPtr += 8;
while (dstPtr < dstEnd) {
LZ4_memcpy(dstPtr, v, 8);
dstPtr += 8;
}
}
|
/* LZ4_memcpy_using_offset() presumes :
* - dstEnd >= dstPtr + MINMATCH
* - there is at least 8 bytes available to write after dstEnd */
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/Utils/LZ4/lz4.c#L513-L551
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
LZ4_decompress_safe
|
LZ4_FORCE_O2
int LZ4_decompress_safe(const char* source, char* dest, int compressedSize, int maxDecompressedSize)
{
return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize,
decode_full_block, noDict,
(BYTE*)dest, NULL, 0);
}
|
/*===== Instantiate the API decoding functions. =====*/
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/Utils/LZ4/lz4.c#L2344-L2350
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
LZ4_decompress_safe_withPrefix64k
|
LZ4_FORCE_O2 /* Exported, an obsolete API function. */
int LZ4_decompress_safe_withPrefix64k(const char* source, char* dest, int compressedSize, int maxOutputSize)
{
return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
decode_full_block, withPrefix64k,
(BYTE*)dest - 64 KB, NULL, 0);
}
|
/*===== Instantiate a few more decoding cases, used more than once. =====*/
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/Utils/LZ4/lz4.c#L2372-L2378
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
LZ4_decompress_fast_withPrefix64k
|
int LZ4_decompress_fast_withPrefix64k(const char* source, char* dest, int originalSize)
{
return LZ4_decompress_unsafe_generic(
(const BYTE*)source, (BYTE*)dest, originalSize,
64 KB, NULL, 0);
}
|
/* Another obsolete API function, paired with the previous one. */
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/Utils/LZ4/lz4.c#L2390-L2395
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
LZ4_decompress_safe_doubleDict
|
LZ4_FORCE_INLINE
int LZ4_decompress_safe_doubleDict(const char* source, char* dest, int compressedSize, int maxOutputSize,
size_t prefixSize, const void* dictStart, size_t dictSize)
{
return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
decode_full_block, usingExtDict,
(BYTE*)dest-prefixSize, (const BYTE*)dictStart, dictSize);
}
|
/* The "double dictionary" mode, for use with e.g. ring buffers: the first part
* of the dictionary is passed as prefix, and the second via dictStart + dictSize.
* These routines are used only once, in LZ4_decompress_*_continue().
*/
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/Utils/LZ4/lz4.c#L2450-L2457
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
LZ4_setStreamDecode
|
int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize)
{
LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse;
lz4sd->prefixSize = (size_t)dictSize;
if (dictSize) {
assert(dictionary != NULL);
lz4sd->prefixEnd = (const BYTE*) dictionary + dictSize;
} else {
lz4sd->prefixEnd = (const BYTE*) dictionary;
}
lz4sd->externalDict = NULL;
lz4sd->extDictSize = 0;
return 1;
}
|
/*! LZ4_setStreamDecode() :
* Use this function to instruct where to find the dictionary.
* This function is not necessary if previous data is still available where it was decoded.
* Loading a size of 0 is allowed (same effect as no dictionary).
* @return : 1 if OK, 0 if error
*/
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/Utils/LZ4/lz4.c#L2482-L2495
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
LZ4_decoderRingBufferSize
|
int LZ4_decoderRingBufferSize(int maxBlockSize)
{
if (maxBlockSize < 0) return 0;
if (maxBlockSize > LZ4_MAX_INPUT_SIZE) return 0;
if (maxBlockSize < 16) maxBlockSize = 16;
return LZ4_DECODER_RING_BUFFER_SIZE(maxBlockSize);
}
|
/*! LZ4_decoderRingBufferSize() :
* when setting a ring buffer for streaming decompression (optional scenario),
* provides the minimum size of this ring buffer
* to be compatible with any source respecting maxBlockSize condition.
* Note : in a ring buffer scenario,
* blocks are presumed decompressed next to each other.
* When not enough space remains for next block (remainingSize < maxBlockSize),
* decoding resumes from beginning of ring buffer.
* @return : minimum ring buffer size,
* or 0 if there is an error (invalid maxBlockSize).
*/
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/Utils/LZ4/lz4.c#L2508-L2514
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
LZ4_decompress_safe_continue
|
LZ4_FORCE_O2
int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxOutputSize)
{
LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse;
int result;
if (lz4sd->prefixSize == 0) {
/* The first call, no dictionary yet. */
assert(lz4sd->extDictSize == 0);
result = LZ4_decompress_safe(source, dest, compressedSize, maxOutputSize);
if (result <= 0) return result;
lz4sd->prefixSize = (size_t)result;
lz4sd->prefixEnd = (BYTE*)dest + result;
} else if (lz4sd->prefixEnd == (BYTE*)dest) {
/* They're rolling the current segment. */
if (lz4sd->prefixSize >= 64 KB - 1)
result = LZ4_decompress_safe_withPrefix64k(source, dest, compressedSize, maxOutputSize);
else if (lz4sd->extDictSize == 0)
result = LZ4_decompress_safe_withSmallPrefix(source, dest, compressedSize, maxOutputSize,
lz4sd->prefixSize);
else
result = LZ4_decompress_safe_doubleDict(source, dest, compressedSize, maxOutputSize,
lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize);
if (result <= 0) return result;
lz4sd->prefixSize += (size_t)result;
lz4sd->prefixEnd += result;
} else {
/* The buffer wraps around, or they're switching to another buffer. */
lz4sd->extDictSize = lz4sd->prefixSize;
lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize;
result = LZ4_decompress_safe_forceExtDict(source, dest, compressedSize, maxOutputSize,
lz4sd->externalDict, lz4sd->extDictSize);
if (result <= 0) return result;
lz4sd->prefixSize = (size_t)result;
lz4sd->prefixEnd = (BYTE*)dest + result;
}
return result;
}
|
/*
*_continue() :
These decoding functions allow decompression of multiple blocks in "streaming" mode.
Previously decoded blocks must still be available at the memory position where they were decoded.
If it's not possible, save the relevant part of decoded data into a safe buffer,
and indicate where it stands using LZ4_setStreamDecode()
*/
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/Utils/LZ4/lz4.c#L2523-L2561
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
LZ4_decompress_safe_usingDict
|
int LZ4_decompress_safe_usingDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize)
{
if (dictSize==0)
return LZ4_decompress_safe(source, dest, compressedSize, maxOutputSize);
if (dictStart+dictSize == dest) {
if (dictSize >= 64 KB - 1) {
return LZ4_decompress_safe_withPrefix64k(source, dest, compressedSize, maxOutputSize);
}
assert(dictSize >= 0);
return LZ4_decompress_safe_withSmallPrefix(source, dest, compressedSize, maxOutputSize, (size_t)dictSize);
}
assert(dictSize >= 0);
return LZ4_decompress_safe_forceExtDict(source, dest, compressedSize, maxOutputSize, dictStart, (size_t)dictSize);
}
|
/*
Advanced decoding functions :
*_usingDict() :
These decoding functions work the same as "_continue" ones,
the dictionary must be explicitly provided within parameters
*/
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/Utils/LZ4/lz4.c#L2612-L2625
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
LZ4_compress_limitedOutput
|
int LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize)
{
return LZ4_compress_default(source, dest, inputSize, maxOutputSize);
}
|
/*=*************************************************
* Obsolete Functions
***************************************************/
/* obsolete compression functions */
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/Utils/LZ4/lz4.c#L2657-L2660
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
LZ4_uncompress
|
int LZ4_uncompress (const char* source, char* dest, int outputSize)
{
return LZ4_decompress_fast(source, dest, outputSize);
}
|
/*
These decompression functions are deprecated and should no longer be used.
They are only provided here for compatibility with older user programs.
- LZ4_uncompress is totally equivalent to LZ4_decompress_fast
- LZ4_uncompress_unknownOutputSize is totally equivalent to LZ4_decompress_safe
*/
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/Utils/LZ4/lz4.c#L2688-L2691
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
LZ4_sizeofStreamState
|
int LZ4_sizeofStreamState(void) { return sizeof(LZ4_stream_t); }
|
/* Obsolete Streaming functions */
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/Utils/LZ4/lz4.c#L2699-L2699
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
fp32_from_bits
|
static inline float fp32_from_bits(uint32_t w) {
union {
uint32_t as_bits;
float as_value;
} fp32;
fp32.as_bits = w;
return fp32.as_value;
}
|
// FP16 <-> FP32
// ref: https://github.com/Maratyszcza/FP16
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L166-L173
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_vec_set_i8
|
inline static void ggml_vec_set_i8(const int n, int8_t * x, const int8_t v) { for (int i = 0; i < n; ++i) x[i] = v; }
|
//
// fundamental operations
//
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L696-L696
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_vec_scale_f32
|
inline static void ggml_vec_scale_f32(const int n, float * y, const float v) {
#if defined(GGML_SIMD)
const int np = (n & ~(GGML_F32_STEP - 1));
GGML_F32_VEC vx = GGML_F32_VEC_SET1(v);
GGML_F32_VEC ay[GGML_F32_ARR];
for (int i = 0; i < np; i += GGML_F32_STEP) {
for (int j = 0; j < GGML_F32_ARR; j++) {
ay[j] = GGML_F32_VEC_LOAD(y + i + j*GGML_F32_EPR);
ay[j] = GGML_F32_VEC_MUL(ay[j], vx);
GGML_F32_VEC_STORE(y + i + j*GGML_F32_EPR, ay[j]);
}
}
// leftovers
for (int i = np; i < n; ++i) {
y[i] *= v;
}
#else
// scalar
for (int i = 0; i < n; ++i) {
y[i] *= v;
}
#endif
}
|
//inline static void ggml_vec_scale_f32(const int n, float * y, const float v) { for (int i = 0; i < n; ++i) y[i] *= v; }
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L962-L989
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_critical_section_start
|
inline static void ggml_critical_section_start() {
int processing = atomic_fetch_add(&g_state_barrier, 1);
while (processing > 0) {
// wait for other threads to finish
atomic_fetch_sub(&g_state_barrier, 1);
sched_yield(); // TODO: reconsider this
processing = atomic_fetch_add(&g_state_barrier, 1);
}
}
|
// barrier via spin lock
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L1221-L1230
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_critical_section_end
|
inline static void ggml_critical_section_end() {
atomic_fetch_sub(&g_state_barrier, 1);
}
|
// TODO: make this somehow automatically executed
// some sort of "sentry" mechanism
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L1234-L1236
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_print_object
|
void ggml_print_object(const struct ggml_object * obj) {
GGML_PRINT(" - ggml_object: offset = %zu, size = %zu, next = %p\n",
obj->offset, obj->size, (const void *) obj->next);
}
|
////////////////////////////////////////////////////////////////////////////////
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L1240-L1243
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_can_repeat
|
bool ggml_can_repeat(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
return
(t1->ne[0]%t0->ne[0] == 0) &&
(t1->ne[1]%t0->ne[1] == 0) &&
(t1->ne[2]%t0->ne[2] == 0) &&
(t1->ne[3]%t0->ne[3] == 0);
}
|
// check if t1 can be represented as a repeatition of t0
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L1341-L1349
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_set_param
|
void ggml_set_param(
struct ggml_context * ctx,
struct ggml_tensor * tensor) {
tensor->is_param = true;
assert(tensor->grad == NULL);
tensor->grad = ggml_dup_tensor(ctx, tensor);
}
|
////////////////////////////////////////////////////////////////////////////////
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L3046-L3053
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_dup_f16
|
static void ggml_compute_forward_dup_f16(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(ggml_is_contiguous(dst));
assert(ggml_nelements(dst) == ggml_nelements(src0));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int ne00 = src0->ne[0];
const int ne01 = src0->ne[1];
const int ne02 = src0->ne[2];
const int ne03 = src0->ne[3];
const size_t nb00 = src0->nb[0];
const size_t nb01 = src0->nb[1];
const size_t nb02 = src0->nb[2];
const size_t nb03 = src0->nb[3];
if (ggml_is_contiguous(src0) && src0->type == dst->type) {
memcpy(dst->data, src0->data, ggml_nelements(dst) * GGML_TYPE_SIZE[src0->type]);
return;
}
if (src0->nb[0] == sizeof(ggml_fp16_t)) {
if (dst->type == GGML_TYPE_F16) {
int id = 0;
const size_t rs = ne00*nb00;
for (int i03 = 0; i03 < ne03; i03++) {
for (int i02 = 0; i02 < ne02; i02++) {
for (int i01 = 0; i01 < ne01; i01++) {
const char * src0_ptr = (char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03;
char * dst_ptr = (char *) dst->data + id*rs;
memcpy(dst_ptr, src0_ptr, rs);
id++;
}
}
}
} else if (dst->type == GGML_TYPE_F32) {
int id = 0;
float * dst_ptr = (float *) dst->data;
for (int i03 = 0; i03 < ne03; i03++) {
for (int i02 = 0; i02 < ne02; i02++) {
for (int i01 = 0; i01 < ne01; i01++) {
for (int i00 = 0; i00 < ne00; i00++) {
const ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
dst_ptr[id] = GGML_FP16_TO_FP32(*src0_ptr);
id++;
}
}
}
}
} else {
GGML_ASSERT(false); // TODO: implement
}
} else {
//printf("%s: this is not optimal - fix me\n", __func__);
if (dst->type == GGML_TYPE_F32) {
int id = 0;
float * dst_ptr = (float *) dst->data;
for (int i03 = 0; i03 < ne03; i03++) {
for (int i02 = 0; i02 < ne02; i02++) {
for (int i01 = 0; i01 < ne01; i01++) {
for (int i00 = 0; i00 < ne00; i00++) {
const ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
dst_ptr[id] = GGML_FP16_TO_FP32(*src0_ptr);
id++;
}
}
}
}
} else if (dst->type == GGML_TYPE_F16) {
int id = 0;
ggml_fp16_t * dst_ptr = (ggml_fp16_t *) dst->data;
for (int i03 = 0; i03 < ne03; i03++) {
for (int i02 = 0; i02 < ne02; i02++) {
for (int i01 = 0; i01 < ne01; i01++) {
for (int i00 = 0; i00 < ne00; i00++) {
const ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
dst_ptr[id] = *src0_ptr;
id++;
}
}
}
}
} else {
GGML_ASSERT(false); // TODO: implement
}
}
}
|
// ggml_compute_forward_dup
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L3057-L3159
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_add_f32
|
static void ggml_compute_forward_add_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
GGML_ASSERT(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int ith = params->ith;
const int nth = params->nth;
const int n = ggml_nrows(src0);
const int nc = src0->ne[0];
const size_t nb00 = src0->nb[0];
const size_t nb01 = src0->nb[1];
const size_t nb10 = src1->nb[0];
const size_t nb11 = src1->nb[1];
const size_t nb0 = dst->nb[0];
const size_t nb1 = dst->nb[1];
GGML_ASSERT( nb0 == sizeof(float));
GGML_ASSERT(nb00 == sizeof(float));
if (nb10 == sizeof(float)) {
const int j0 = (n/nth)*ith;
const int j1 = ith == nth - 1 ? n : (n/nth)*(ith + 1);
for (int j = j0; j < j1; j++) {
ggml_vec_add_f32(nc,
(float *) ((char *) dst->data + j*nb1),
(float *) ((char *) src0->data + j*nb01),
(float *) ((char *) src1->data + j*nb11));
}
} else {
// src1 is not contiguous
for (int j = ith; j < n; j += nth) {
float * dst_ptr = (float *) ((char *) dst->data + j*nb1);
float * src0_ptr = (float *) ((char *) src0->data + j*nb01);
for (int i = 0; i < nc; i++) {
float * src1_ptr = (float *) ((char *) src1->data + j*nb11 + i*nb10);
dst_ptr[i] = src0_ptr[i] + *src1_ptr;
}
}
}
}
|
// ggml_compute_forward_add
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L3290-L3341
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_sub_f32
|
static void ggml_compute_forward_sub_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int n = ggml_nrows(src0);
const int nc = src0->ne[0];
assert( dst->nb[0] == sizeof(float));
assert(src0->nb[0] == sizeof(float));
assert(src1->nb[0] == sizeof(float));
for (int i = 0; i < n; i++) {
ggml_vec_sub_f32(nc,
(float *) ((char *) dst->data + i*( dst->nb[1])),
(float *) ((char *) src0->data + i*(src0->nb[1])),
(float *) ((char *) src1->data + i*(src1->nb[1])));
}
}
|
// ggml_compute_forward_sub
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L3366-L3391
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_mul_f32
|
static void ggml_compute_forward_mul_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int n = ggml_nrows(src0);
const int nc = src0->ne[0];
assert( dst->nb[0] == sizeof(float));
assert(src0->nb[0] == sizeof(float));
assert(src1->nb[0] == sizeof(float));
for (int i = 0; i < n; i++) {
ggml_vec_mul_f32(nc,
(float *) ((char *) dst->data + i*( dst->nb[1])),
(float *) ((char *) src0->data + i*(src0->nb[1])),
(float *) ((char *) src1->data + i*(src1->nb[1])));
}
}
|
// ggml_compute_forward_mul
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L3416-L3441
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_div_f32
|
static void ggml_compute_forward_div_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int n = ggml_nrows(src0);
const int nc = src0->ne[0];
assert( dst->nb[0] == sizeof(float));
assert(src0->nb[0] == sizeof(float));
assert(src1->nb[0] == sizeof(float));
for (int i = 0; i < n; i++) {
ggml_vec_div_f32(nc,
(float *) ((char *) dst->data + i*( dst->nb[1])),
(float *) ((char *) src0->data + i*(src0->nb[1])),
(float *) ((char *) src1->data + i*(src1->nb[1])));
}
}
|
// ggml_compute_forward_div
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L3466-L3491
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_sqr_f32
|
static void ggml_compute_forward_sqr_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int n = ggml_nrows(src0);
const int nc = src0->ne[0];
assert( dst->nb[0] == sizeof(float));
assert(src0->nb[0] == sizeof(float));
for (int i = 0; i < n; i++) {
ggml_vec_sqr_f32(nc,
(float *) ((char *) dst->data + i*( dst->nb[1])),
(float *) ((char *) src0->data + i*(src0->nb[1])));
}
}
|
// ggml_compute_forward_sqr
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L3516-L3538
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_sqrt_f32
|
static void ggml_compute_forward_sqrt_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int n = ggml_nrows(src0);
const int nc = src0->ne[0];
assert( dst->nb[0] == sizeof(float));
assert(src0->nb[0] == sizeof(float));
for (int i = 0; i < n; i++) {
ggml_vec_sqrt_f32(nc,
(float *) ((char *) dst->data + i*( dst->nb[1])),
(float *) ((char *) src0->data + i*(src0->nb[1])));
}
}
|
// ggml_compute_forward_sqrt
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L3562-L3584
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_sum_f32
|
static void ggml_compute_forward_sum_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(ggml_is_scalar(dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
assert(ggml_is_scalar(dst));
assert(src0->nb[0] == sizeof(float));
*(float *) (dst->data) = 0.0f;
const int ne00 = src0->ne[0];
const int ne01 = src0->ne[1];
const int ne02 = src0->ne[2];
const int ne03 = src0->ne[3];
const size_t nb01 = src0->nb[1];
const size_t nb02 = src0->nb[2];
const size_t nb03 = src0->nb[3];
for (int i03 = 0; i03 < ne03; i03++) {
for (int i02 = 0; i02 < ne02; i02++) {
for (int i01 = 0; i01 < ne01; i01++) {
ggml_vec_sum_f32(ne00,
(float *) (dst->data),
(float *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03));
}
}
}
}
|
// ggml_compute_forward_sum
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L3608-L3642
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_mean_f32
|
static void ggml_compute_forward_mean_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
assert(params->ith == 0);
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
assert(src0->nb[0] == sizeof(float));
const int ne00 = src0->ne[0];
const int ne01 = src0->ne[1];
const int ne02 = src0->ne[2];
const int ne03 = src0->ne[3];
const size_t nb01 = src0->nb[1];
const size_t nb02 = src0->nb[2];
const size_t nb03 = src0->nb[3];
const int ne0 = dst->ne[0];
const int ne1 = dst->ne[1];
const int ne2 = dst->ne[2];
const int ne3 = dst->ne[3];
assert(ne0 == 1);
assert(ne1 == ne01);
assert(ne2 == ne02);
assert(ne3 == ne03);
UNUSED(ne0);
UNUSED(ne1);
UNUSED(ne2);
UNUSED(ne3);
const size_t nb1 = dst->nb[1];
const size_t nb2 = dst->nb[2];
const size_t nb3 = dst->nb[3];
for (int i03 = 0; i03 < ne03; i03++) {
for (int i02 = 0; i02 < ne02; i02++) {
for (int i01 = 0; i01 < ne01; i01++) {
*(float *) ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3) = 0.0f;
ggml_vec_sum_f32(ne00,
(float *) ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3),
(float *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03));
*(float *) ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3) /= (float) ne00;
}
}
}
}
|
// ggml_compute_forward_mean
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L3666-L3719
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_repeat_f32
|
static void ggml_compute_forward_repeat_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(ggml_can_repeat(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
// TODO: implement support for rank > 2 tensors
assert(src0->ne[2] == 1);
assert(src0->ne[3] == 1);
assert( dst->ne[2] == 1);
assert( dst->ne[3] == 1);
const int nc = dst->ne[0];
const int nr = dst->ne[1];
const int nc0 = src0->ne[0];
const int nr0 = src0->ne[1];
const int ncr = nc/nc0; // guaranteed to be an integer due to the check in ggml_can_repeat
const int nrr = nr/nr0; // guaranteed to be an integer due to the check in ggml_can_repeat
// TODO: support for transposed / permuted tensors
assert( dst->nb[0] == sizeof(float));
assert(src0->nb[0] == sizeof(float));
// TODO: maybe this is not optimal?
for (int i = 0; i < nrr; i++) {
for (int j = 0; j < ncr; j++) {
for (int k = 0; k < nr0; k++) {
ggml_vec_cpy_f32(nc0,
(float *) ((char *) dst->data + (i*nr0 + k)*( dst->nb[1]) + j*nc0*( dst->nb[0])),
(float *) ((char *) src0->data + ( k)*(src0->nb[1])));
}
}
}
}
|
// ggml_compute_forward_repeat
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L3743-L3781
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_abs_f32
|
static void ggml_compute_forward_abs_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int n = ggml_nrows(src0);
const int nc = src0->ne[0];
assert(dst->nb[0] == sizeof(float));
assert(src0->nb[0] == sizeof(float));
for (int i = 0; i < n; i++) {
ggml_vec_abs_f32(nc,
(float *) ((char *) dst->data + i*( dst->nb[1])),
(float *) ((char *) src0->data + i*(src0->nb[1])));
}
}
|
// ggml_compute_forward_abs
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L3805-L3827
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_sgn_f32
|
static void ggml_compute_forward_sgn_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int n = ggml_nrows(src0);
const int nc = src0->ne[0];
assert(dst->nb[0] == sizeof(float));
assert(src0->nb[0] == sizeof(float));
for (int i = 0; i < n; i++) {
ggml_vec_sgn_f32(nc,
(float *) ((char *) dst->data + i*( dst->nb[1])),
(float *) ((char *) src0->data + i*(src0->nb[1])));
}
}
|
// ggml_compute_forward_sgn
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L3851-L3873
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_neg_f32
|
static void ggml_compute_forward_neg_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int n = ggml_nrows(src0);
const int nc = src0->ne[0];
assert(dst->nb[0] == sizeof(float));
assert(src0->nb[0] == sizeof(float));
for (int i = 0; i < n; i++) {
ggml_vec_neg_f32(nc,
(float *) ((char *) dst->data + i*( dst->nb[1])),
(float *) ((char *) src0->data + i*(src0->nb[1])));
}
}
|
// ggml_compute_forward_neg
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L3897-L3919
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_step_f32
|
static void ggml_compute_forward_step_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int n = ggml_nrows(src0);
const int nc = src0->ne[0];
assert(dst->nb[0] == sizeof(float));
assert(src0->nb[0] == sizeof(float));
for (int i = 0; i < n; i++) {
ggml_vec_step_f32(nc,
(float *) ((char *) dst->data + i*( dst->nb[1])),
(float *) ((char *) src0->data + i*(src0->nb[1])));
}
}
|
// ggml_compute_forward_step
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L3943-L3965
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_relu_f32
|
static void ggml_compute_forward_relu_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int n = ggml_nrows(src0);
const int nc = src0->ne[0];
assert(dst->nb[0] == sizeof(float));
assert(src0->nb[0] == sizeof(float));
for (int i = 0; i < n; i++) {
ggml_vec_relu_f32(nc,
(float *) ((char *) dst->data + i*( dst->nb[1])),
(float *) ((char *) src0->data + i*(src0->nb[1])));
}
}
|
// ggml_compute_forward_relu
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L3989-L4011
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_gelu_f32
|
static void ggml_compute_forward_gelu_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
GGML_ASSERT(ggml_is_contiguous(src0));
GGML_ASSERT(ggml_is_contiguous(dst));
GGML_ASSERT(ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int ith = params->ith;
const int nth = params->nth;
const int nc = src0->ne[0];
const int nr = ggml_nrows(src0);
// rows per thread
const int dr = (nr + nth - 1)/nth;
// row range for this thread
const int ir0 = dr*ith;
const int ir1 = MIN(ir0 + dr, nr);
for (int i1 = ir0; i1 < ir1; i1++) {
ggml_vec_gelu_f32(nc,
(float *) ((char *) dst->data + i1*( dst->nb[1])),
(float *) ((char *) src0->data + i1*(src0->nb[1])));
#ifndef NDEBUG
for (int k = 0; k < nc; k++) {
const float x = ((float *) ((char *) dst->data + i1*( dst->nb[1])))[k];
UNUSED(x);
assert(!isnan(x));
assert(!isinf(x));
}
#endif
}
}
|
// ggml_compute_forward_gelu
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L4035-L4074
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_norm_f32
|
static void ggml_compute_forward_norm_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
GGML_ASSERT(ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
GGML_ASSERT(src0->nb[0] == sizeof(float));
const int ith = params->ith;
const int nth = params->nth;
const int ne00 = src0->ne[0];
const int ne01 = src0->ne[1];
const int ne02 = src0->ne[2];
const int ne03 = src0->ne[3];
const size_t nb01 = src0->nb[1];
const size_t nb02 = src0->nb[2];
const size_t nb03 = src0->nb[3];
const size_t nb1 = dst->nb[1];
const size_t nb2 = dst->nb[2];
const size_t nb3 = dst->nb[3];
const ggml_float eps = 1e-5f; // TODO: make this a parameter
// TODO: optimize
for (int i03 = 0; i03 < ne03; i03++) {
for (int i02 = 0; i02 < ne02; i02++) {
for (int i01 = ith; i01 < ne01; i01 += nth) {
const float * x = (float *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03);
ggml_float mean = 0.0;
for (int i00 = 0; i00 < ne00; i00++) {
mean += x[i00];
}
mean /= ne00;
float * y = (float *) ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3);
ggml_float sum2 = 0.0;
for (int i00 = 0; i00 < ne00; i00++) {
ggml_float v = x[i00] - mean;
y[i00] = v;
sum2 += v*v;
}
const float scale = 1.0/sqrt(sum2/ne00 + eps);
ggml_vec_scale_f32(ne00, y, scale);
}
}
}
}
|
// ggml_compute_forward_norm
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L4098-L4156
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_mul_mat_use_blas
|
static bool ggml_compute_forward_mul_mat_use_blas(
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
UNUSED(src0);
const int ne10 = src1->ne[0];
const int ne0 = dst->ne[0];
const int ne1 = dst->ne[1];
// TODO: find the optimal values for these
if (ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ne0 >= 32 && ne1 >= 32 && ne10 >= 32) {
//printf("BLAS: %d %d %d\n", ne0, ne1, ne10);
return true;
}
return false;
}
|
// helper function to determine if it is better to use BLAS or not
// for large matrices, BLAS is faster
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L4183-L4201
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_scale_f32
|
static void ggml_compute_forward_scale_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
GGML_ASSERT(ggml_is_contiguous(src0));
GGML_ASSERT(ggml_is_contiguous(dst));
GGML_ASSERT(ggml_are_same_shape(src0, dst));
GGML_ASSERT(ggml_is_scalar(src1));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
// scale factor
const float v = *(float *) src1->data;
const int ith = params->ith;
const int nth = params->nth;
const int nc = src0->ne[0];
const int nr = ggml_nrows(src0);
// rows per thread
const int dr = (nr + nth - 1)/nth;
// row range for this thread
const int ir0 = dr*ith;
const int ir1 = MIN(ir0 + dr, nr);
for (int i1 = ir0; i1 < ir1; i1++) {
ggml_vec_scale_f32(nc, (float *) ((char *) dst->data + i1*(dst->nb[1])), v);
}
}
|
// ggml_compute_forward_scale
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L4777-L4810
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_cpy
|
static void ggml_compute_forward_cpy(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
ggml_compute_forward_dup(params, src0, dst);
}
|
// ggml_compute_forward_cpy
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L4835-L4840
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_reshape
|
static void ggml_compute_forward_reshape(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
// NOP
UNUSED(params);
UNUSED(src0);
UNUSED(dst);
}
|
// ggml_compute_forward_reshape
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L4844-L4852
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_view
|
static void ggml_compute_forward_view(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0) {
// NOP
UNUSED(params);
UNUSED(src0);
}
|
// ggml_compute_forward_view
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L4856-L4862
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_permute
|
static void ggml_compute_forward_permute(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0) {
// NOP
UNUSED(params);
UNUSED(src0);
}
|
// ggml_compute_forward_permute
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L4866-L4872
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_transpose
|
static void ggml_compute_forward_transpose(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0) {
// NOP
UNUSED(params);
UNUSED(src0);
}
|
// ggml_compute_forward_transpose
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L4876-L4882
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_get_rows_f16
|
static void ggml_compute_forward_get_rows_f16(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
assert(params->ith == 0);
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int nc = src0->ne[0];
const int nr = ggml_nelements(src1);
assert( dst->ne[0] == nc);
assert( dst->ne[1] == nr);
assert(src0->nb[0] == sizeof(ggml_fp16_t));
for (int i = 0; i < nr; ++i) {
const int r = ((int32_t *) src1->data)[i];
for (int j = 0; j < nc; ++j) {
ggml_fp16_t v = ((ggml_fp16_t *) ((char *) src0->data + r*src0->nb[1]))[j];
((float *) ((char *) dst->data + i*dst->nb[1]))[j] = GGML_FP16_TO_FP32(v);
}
}
}
|
// ggml_compute_forward_get_rows
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L4886-L4912
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_diag_mask_inf_f32
|
static void ggml_compute_forward_diag_mask_inf_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(src1->type == GGML_TYPE_I32);
assert(ggml_nelements(src1) == 1);
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int n_past = ((int32_t *) src1->data)[0];
// TODO: handle transposed/permuted matrices
const int n = ggml_nrows(src0);
const int nc = src0->ne[0];
const int nr = src0->ne[1];
const int nz = n/nr;
assert( dst->nb[0] == sizeof(float));
assert(src0->nb[0] == sizeof(float));
for (int k = 0; k < nz; k++) {
for (int j = 0; j < nr; j++) {
for (int i = n_past; i < nc; i++) {
if (i > n_past + j) {
*(float *)((char *) dst->data + k*dst->nb[2] + j*dst->nb[1] + i*dst->nb[0]) = -INFINITY;
}
}
}
}
}
|
// ggml_compute_forward_diag_mask_inf
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L4967-L5001
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_soft_max_f32
|
static void ggml_compute_forward_soft_max_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
GGML_ASSERT(ggml_is_contiguous(src0));
GGML_ASSERT(ggml_is_contiguous(dst));
GGML_ASSERT(ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
// TODO: handle transposed/permuted matrices
const int ith = params->ith;
const int nth = params->nth;
const int nc = src0->ne[0];
const int nr = ggml_nrows(src0);
// rows per thread
const int dr = (nr + nth - 1)/nth;
// row range for this thread
const int ir0 = dr*ith;
const int ir1 = MIN(ir0 + dr, nr);
for (int i1 = ir0; i1 < ir1; i1++) {
float *p = (float *)((char *) dst->data + i1*dst->nb[1]);
#ifndef NDEBUG
for (int i = 0; i < nc; ++i) {
assert(!isnan(p[i]));
}
#endif
float max = -INFINITY;
for (int i = 0; i < nc; i++) {
max = MAX(max, p[i]);
}
ggml_float sum = 0.0;
uint16_t ss;
for (int i = 0; i < nc; i++) {
if (p[i] == -INFINITY) {
p[i] = 0.0;
} else {
//const float val = (p[i] == -INFINITY) ? 0.0 : exp(p[i] - max);
ggml_fp16_t s = GGML_FP32_TO_FP16(p[i] - max);
memcpy(&ss, &s, sizeof(ss));
const float val = GGML_FP16_TO_FP32(table_exp_f16[ss]);
sum += val;
p[i] = val;
}
}
assert(sum > 0.0f);
sum = 1.0/sum;
ggml_vec_scale_f32(nc, p, sum);
#ifndef NDEBUG
for (int i = 0; i < nc; ++i) {
assert(!isnan(p[i]));
assert(!isinf(p[i]));
}
#endif
}
}
|
// ggml_compute_forward_soft_max
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L5026-L5095
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_rope_f32
|
static void ggml_compute_forward_rope_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(src1->type == GGML_TYPE_I32);
assert(ggml_nelements(src1) == 3);
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int n_past = ((int32_t *) src1->data)[0];
const int n_dims = ((int32_t *) src1->data)[1];
const int mode = ((int32_t *) src1->data)[2];
//const int ne0 = src0->ne[0];
const int ne1 = src0->ne[1];
const int ne2 = src0->ne[2];
const int ne3 = src0->ne[3];
const int nb0 = src0->nb[0];
const int nb1 = src0->nb[1];
const int nb2 = src0->nb[2];
const int nb3 = src0->nb[3];
//printf("ne0: %d, ne1: %d, ne2: %d, ne3: %d\n", ne0, ne1, ne2, ne3);
//printf("n_past = %d, ne2 = %d\n", n_past, ne2);
assert(nb0 == sizeof(float));
// TODO: optimize
for (int i3 = 0; i3 < ne3; i3++) {
for (int i2 = (mode == 0 ? 0 : n_past); i2 < ne2; i2++) {
const int p = (mode == 0 ? n_past + i2 : i2);
for (int i1 = 0; i1 < ne1; i1++) {
for (int i0 = 0; i0 < n_dims; i0 += 2) {
const double theta = pow(10000.0, ((double)-i0)/n_dims);
const double cos_theta = cos(p*theta);
const double sin_theta = sin(p*theta);
const float * const src = (float *)((char *) src0->data + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
float * dst_data = (float *)((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
double x0 = src[0];
double x1 = src[1];
dst_data[0] = x0*cos_theta - x1*sin_theta;
dst_data[1] = x0*sin_theta + x1*cos_theta;
}
}
}
}
}
|
// ggml_compute_forward_rope
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L5119-L5174
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_conv_1d_1s_f16_f32
|
static void ggml_compute_forward_conv_1d_1s_f16_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
GGML_ASSERT(src0->type == GGML_TYPE_F16);
GGML_ASSERT(src1->type == GGML_TYPE_F32);
GGML_ASSERT( dst->type == GGML_TYPE_F32);
int64_t t0 = ggml_perf_time_us();
UNUSED(t0);
const int ne00 = src0->ne[0];
const int ne01 = src0->ne[1];
const int ne02 = src0->ne[2];
//const int ne03 = src0->ne[3];
const int ne10 = src1->ne[0];
const int ne11 = src1->ne[1];
//const int ne12 = src1->ne[2];
//const int ne13 = src1->ne[3];
//const int ne0 = dst->ne[0];
//const int ne1 = dst->ne[1];
//const int ne2 = dst->ne[2];
//const int ne3 = dst->ne[3];
//const int ne = ne0*ne1*ne2*ne3;
const int nb00 = src0->nb[0];
const int nb01 = src0->nb[1];
const int nb02 = src0->nb[2];
//const int nb03 = src0->nb[3];
const int nb10 = src1->nb[0];
const int nb11 = src1->nb[1];
//const int nb12 = src1->nb[2];
//const int nb13 = src1->nb[3];
//const int nb0 = dst->nb[0];
const int nb1 = dst->nb[1];
//const int nb2 = dst->nb[2];
//const int nb3 = dst->nb[3];
const int ith = params->ith;
const int nth = params->nth;
const int nk = ne00;
const int nh = nk/2;
const int ew0 = ggml_up32(ne01);
GGML_ASSERT(ne00 % 2 == 1); // TODO: support even kernel sizes
GGML_ASSERT(nb00 == sizeof(ggml_fp16_t));
GGML_ASSERT(nb10 == sizeof(float));
if (params->type == GGML_TASK_INIT) {
// TODO: fix this memset (wsize is overestimated)
memset(params->wdata, 0, params->wsize);
// prepare kernel data (src0)
{
ggml_fp16_t * const wdata = (ggml_fp16_t *) params->wdata + 0;
for (int i02 = 0; i02 < ne02; i02++) {
for (int i01 = 0; i01 < ne01; i01++) {
const ggml_fp16_t * const src = (ggml_fp16_t *)((char *) src0->data + i02*nb02 + i01*nb01);
ggml_fp16_t * dst_data = wdata + i02*ew0*ne00;
for (int i00 = 0; i00 < ne00; i00++) {
dst_data[i00*ew0 + i01] = src[i00];
}
}
}
}
// prepare source data (src1)
{
ggml_fp16_t * const wdata = (ggml_fp16_t *) params->wdata + ne02*ew0*ne00;
for (int i11 = 0; i11 < ne11; i11++) {
const float * const src = (float *)((char *) src1->data + i11*nb11);
ggml_fp16_t * dst_data = wdata;
for (int i10 = 0; i10 < ne10; i10++) {
dst_data[(i10 + nh)*ew0 + i11] = GGML_FP32_TO_FP16(src[i10]);
}
}
}
return;
}
if (params->type == GGML_TASK_FINALIZE) {
return;
}
// total rows in dst
const int nr = ne02;
// rows per thread
const int dr = (nr + nth - 1)/nth;
// row range for this thread
const int ir0 = dr*ith;
const int ir1 = MIN(ir0 + dr, nr);
for (int i1 = ir0; i1 < ir1; i1++) {
float * dst_data = (float *)((char *) dst->data + i1*nb1);
for (int i0 = 0; i0 < ne10; ++i0) {
dst_data[i0] = 0;
for (int k = -nh; k <= nh; k++) {
float v = 0.0f;
ggml_vec_dot_f16(ew0, &v,
(ggml_fp16_t *) params->wdata + i1*ew0*ne00 + (nh + k)*ew0,
(ggml_fp16_t *) params->wdata + ne02*ew0*ne00 + (i0 + nh + k)*ew0);
dst_data[i0] += v;
}
}
}
}
|
// ggml_compute_forward_conv_1d_1s
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L5199-L5317
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_conv_1d_2s_f16_f32
|
static void ggml_compute_forward_conv_1d_2s_f16_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
GGML_ASSERT(src0->type == GGML_TYPE_F16);
GGML_ASSERT(src1->type == GGML_TYPE_F32);
GGML_ASSERT( dst->type == GGML_TYPE_F32);
int64_t t0 = ggml_perf_time_us();
UNUSED(t0);
const int ne00 = src0->ne[0];
const int ne01 = src0->ne[1];
const int ne02 = src0->ne[2];
//const int ne03 = src0->ne[3];
const int ne10 = src1->ne[0];
const int ne11 = src1->ne[1];
//const int ne12 = src1->ne[2];
//const int ne13 = src1->ne[3];
//const int ne0 = dst->ne[0];
//const int ne1 = dst->ne[1];
//const int ne2 = dst->ne[2];
//const int ne3 = dst->ne[3];
//const int ne = ne0*ne1*ne2*ne3;
const int nb00 = src0->nb[0];
const int nb01 = src0->nb[1];
const int nb02 = src0->nb[2];
//const int nb03 = src0->nb[3];
const int nb10 = src1->nb[0];
const int nb11 = src1->nb[1];
//const int nb12 = src1->nb[2];
//const int nb13 = src1->nb[3];
//const int nb0 = dst->nb[0];
const int nb1 = dst->nb[1];
//const int nb2 = dst->nb[2];
//const int nb3 = dst->nb[3];
const int ith = params->ith;
const int nth = params->nth;
const int nk = ne00;
const int nh = nk/2;
const int ew0 = ggml_up32(ne01);
GGML_ASSERT(ne00 % 2 == 1); // TODO: support even kernel sizes
GGML_ASSERT(nb00 == sizeof(ggml_fp16_t));
GGML_ASSERT(nb10 == sizeof(float));
if (params->type == GGML_TASK_INIT) {
// TODO: fix this memset (wsize is overestimated)
memset(params->wdata, 0, params->wsize);
// prepare kernel data (src0)
{
ggml_fp16_t * const wdata = (ggml_fp16_t *) params->wdata + 0;
for (int i02 = 0; i02 < ne02; i02++) {
for (int i01 = 0; i01 < ne01; i01++) {
const ggml_fp16_t * const src = (ggml_fp16_t *)((char *) src0->data + i02*nb02 + i01*nb01);
ggml_fp16_t * dst_data = wdata + i02*ew0*ne00;
for (int i00 = 0; i00 < ne00; i00++) {
dst_data[i00*ew0 + i01] = src[i00];
}
}
}
}
// prepare source data (src1)
{
ggml_fp16_t * const wdata = (ggml_fp16_t *) params->wdata + ne02*ew0*ne00;
for (int i11 = 0; i11 < ne11; i11++) {
const float * const src = (float *)((char *) src1->data + i11*nb11);
ggml_fp16_t * dst_data = wdata;
for (int i10 = 0; i10 < ne10; i10++) {
dst_data[(i10 + nh)*ew0 + i11] = GGML_FP32_TO_FP16(src[i10]);
}
}
}
return;
}
if (params->type == GGML_TASK_FINALIZE) {
return;
}
// total rows in dst
const int nr = ne02;
// rows per thread
const int dr = (nr + nth - 1)/nth;
// row range for this thread
const int ir0 = dr*ith;
const int ir1 = MIN(ir0 + dr, nr);
for (int i1 = ir0; i1 < ir1; i1++) {
float * dst_data = (float *)((char *) dst->data + i1*nb1);
for (int i0 = 0; i0 < ne10; i0 += 2) {
dst_data[i0/2] = 0;
for (int k = -nh; k <= nh; k++) {
float v = 0.0f;
ggml_vec_dot_f16(ew0, &v,
(ggml_fp16_t *) params->wdata + i1*ew0*ne00 + (nh + k)*ew0,
(ggml_fp16_t *) params->wdata + ne02*ew0*ne00 + (i0 + nh + k)*ew0);
dst_data[i0/2] += v;
}
}
}
}
|
// ggml_compute_forward_conv_1d_2s
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L5465-L5583
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_flash_attn_f32
|
static void ggml_compute_forward_flash_attn_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * q,
const struct ggml_tensor * k,
const struct ggml_tensor * v,
const bool masked,
struct ggml_tensor * dst) {
int64_t t0 = ggml_perf_time_us();
UNUSED(t0);
const int neq0 = q->ne[0];
const int neq1 = q->ne[1];
const int neq2 = q->ne[2];
const int neq3 = q->ne[3];
const int nek0 = k->ne[0];
const int nek1 = k->ne[1];
//const int nek2 = k->ne[2];
//const int nek3 = k->ne[3];
//const int nev0 = v->ne[0];
const int nev1 = v->ne[1];
//const int nev2 = v->ne[2];
//const int nev3 = v->ne[3];
const int ne0 = dst->ne[0];
const int ne1 = dst->ne[1];
//const int ne2 = dst->ne[2];
//const int ne3 = dst->ne[3];
const int nbk0 = k->nb[0];
const int nbk1 = k->nb[1];
const int nbk2 = k->nb[2];
const int nbk3 = k->nb[3];
const int nbq0 = q->nb[0];
const int nbq1 = q->nb[1];
const int nbq2 = q->nb[2];
const int nbq3 = q->nb[3];
const int nbv0 = v->nb[0];
const int nbv1 = v->nb[1];
const int nbv2 = v->nb[2];
const int nbv3 = v->nb[3];
const int nb0 = dst->nb[0];
const int nb1 = dst->nb[1];
const int nb2 = dst->nb[2];
const int nb3 = dst->nb[3];
const int ith = params->ith;
const int nth = params->nth;
const int D = neq0;
const int N = neq1;
const int P = nek1 - N;
const int M = P + N;
GGML_ASSERT(ne0 == D);
GGML_ASSERT(ne1 == N);
GGML_ASSERT(P >= 0);
GGML_ASSERT(nbq0 == sizeof(float));
GGML_ASSERT(nbk0 == sizeof(float));
GGML_ASSERT(nbv0 == sizeof(float));
GGML_ASSERT(neq0 == D);
GGML_ASSERT(nek0 == D);
GGML_ASSERT(nev1 == D);
GGML_ASSERT(neq1 == N);
GGML_ASSERT(nek1 == N + P);
GGML_ASSERT(nev1 == D);
// dst cannot be transposed or permuted
GGML_ASSERT(nb0 == sizeof(float));
GGML_ASSERT(nb0 <= nb1);
GGML_ASSERT(nb1 <= nb2);
GGML_ASSERT(nb2 <= nb3);
if (params->type == GGML_TASK_INIT) {
return;
}
if (params->type == GGML_TASK_FINALIZE) {
return;
}
// parallelize by q rows using ggml_vec_dot_f32
// total rows in q
const int nr = neq1*neq2*neq3;
// rows per thread
const int dr = (nr + nth - 1)/nth;
// row range for this thread
const int ir0 = dr*ith;
const int ir1 = MIN(ir0 + dr, nr);
const float scale = 1.0/sqrt((double) D);
//printf("P=%d N=%d D=%d ir0=%d ir1=%d scale = %f\n", P, N, D, ir0, ir1, scale);
for (int ir = ir0; ir < ir1; ++ir) {
// q indices
const int iq3 = ir/(neq2*neq1);
const int iq2 = (ir - iq3*neq2*neq1)/neq1;
const int iq1 = (ir - iq3*neq2*neq1 - iq2*neq1);
float * S = (float *) params->wdata + ith*(M + CACHE_LINE_SIZE_F32);
for (int ic = 0; ic < nek1; ++ic) {
// k indices
const int ik3 = iq3;
const int ik2 = iq2;
const int ik1 = ic;
// S indices
const int i1 = ik1;
ggml_vec_dot_f32(neq0,
S + i1,
(float *) ((char *) k->data + (ik1*nbk1 + ik2*nbk2 + ik3*nbk3)),
(float *) ((char *) q->data + (iq1*nbq1 + iq2*nbq2 + iq3*nbq3)));
}
// scale
ggml_vec_scale_f32(nek1, S, scale);
if (masked) {
for (int i = P; i < M; i++) {
if (i > P + iq1) {
S[i] = -INFINITY;
}
}
}
// softmax
{
float max = -INFINITY;
for (int i = 0; i < M; i++) {
max = MAX(max, S[i]);
}
ggml_float sum = 0.0;
uint16_t ss;
for (int i = 0; i < M; i++) {
if (S[i] == -INFINITY) {
S[i] = 0.0;
} else {
//const float val = (S[i] == -INFINITY) ? 0.0 : exp(S[i] - max);
ggml_fp16_t s = GGML_FP32_TO_FP16(S[i] - max);
memcpy(&ss, &s, sizeof(ss));
const float val = GGML_FP16_TO_FP32(table_exp_f16[ss]);
sum += val;
S[i] = val;
}
}
assert(sum > 0.0f);
sum = 1.0/sum;
ggml_vec_scale_f32(M, S, sum);
}
for (int ic = 0; ic < nev1; ++ic) {
// dst indices
const int i1 = iq1;
const int i2 = iq2;
const int i3 = iq3;
ggml_vec_dot_f32(nek1,
(float *) ((char *) dst->data + (ic*nb0 + i1*nb1 + i2*nb2 + i3*nb3)),
(float *) ((char *) v->data + ( ic*nbv1 + i2*nbv2 + i3*nbv3)),
S);
}
}
}
|
// ggml_compute_forward_flash_attn
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L5731-L5910
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward_flash_ff_f16
|
static void ggml_compute_forward_flash_ff_f16(
const struct ggml_compute_params * params,
const struct ggml_tensor * a, // F16
const struct ggml_tensor * b0, // F16 fc_w
const struct ggml_tensor * b1, // F32 fc_b
const struct ggml_tensor * c0, // F16 proj_w
const struct ggml_tensor * c1, // F32 proj_b
struct ggml_tensor * dst) {
int64_t t0 = ggml_perf_time_us();
UNUSED(t0);
const int nea0 = a->ne[0];
const int nea1 = a->ne[1];
const int nea2 = a->ne[2];
const int nea3 = a->ne[3];
const int neb00 = b0->ne[0];
const int neb01 = b0->ne[1];
//const int neb02 = b0->ne[2];
//const int neb03 = b0->ne[3];
const int neb10 = b1->ne[0];
const int neb11 = b1->ne[1];
//const int neb12 = b1->ne[2];
//const int neb13 = b1->ne[3];
const int nec00 = c0->ne[0];
const int nec01 = c0->ne[1];
//const int nec02 = c0->ne[2];
//const int nec03 = c0->ne[3];
const int nec10 = c1->ne[0];
const int nec11 = c1->ne[1];
//const int nec12 = c1->ne[2];
//const int nec13 = c1->ne[3];
const int ne0 = dst->ne[0];
const int ne1 = dst->ne[1];
const int ne2 = dst->ne[2];
//const int ne3 = dst->ne[3];
const int nba0 = a->nb[0];
const int nba1 = a->nb[1];
const int nba2 = a->nb[2];
const int nba3 = a->nb[3];
const int nbb00 = b0->nb[0];
const int nbb01 = b0->nb[1];
const int nbb02 = b0->nb[2];
const int nbb03 = b0->nb[3];
const int nbb10 = b1->nb[0];
//const int nbb11 = b1->nb[1];
//const int nbb12 = b1->nb[2];
//const int nbb13 = b1->nb[3];
const int nbc00 = c0->nb[0];
const int nbc01 = c0->nb[1];
const int nbc02 = c0->nb[2];
const int nbc03 = c0->nb[3];
const int nbc10 = c1->nb[0];
//const int nbc11 = c1->nb[1];
//const int nbc12 = c1->nb[2];
//const int nbc13 = c1->nb[3];
const int nb0 = dst->nb[0];
const int nb1 = dst->nb[1];
const int nb2 = dst->nb[2];
const int nb3 = dst->nb[3];
const int ith = params->ith;
const int nth = params->nth;
const int D = nea0;
//const int N = nea1;
const int M = neb01;
GGML_ASSERT(ne0 == nea0);
GGML_ASSERT(ne1 == nea1);
GGML_ASSERT(ne2 == nea2);
GGML_ASSERT(nba0 == sizeof(ggml_fp16_t));
GGML_ASSERT(nbb00 == sizeof(ggml_fp16_t));
GGML_ASSERT(nbb10 == sizeof(float));
GGML_ASSERT(nbc00 == sizeof(ggml_fp16_t));
GGML_ASSERT(nbc10 == sizeof(float));
GGML_ASSERT(neb00 == D);
GGML_ASSERT(neb01 == M);
GGML_ASSERT(neb10 == M);
GGML_ASSERT(neb11 == 1);
GGML_ASSERT(nec00 == M);
GGML_ASSERT(nec01 == D);
GGML_ASSERT(nec10 == D);
GGML_ASSERT(nec11 == 1);
// dst cannot be transposed or permuted
GGML_ASSERT(nb0 == sizeof(float));
GGML_ASSERT(nb0 <= nb1);
GGML_ASSERT(nb1 <= nb2);
GGML_ASSERT(nb2 <= nb3);
if (params->type == GGML_TASK_INIT) {
return;
}
if (params->type == GGML_TASK_FINALIZE) {
return;
}
// parallelize by a rows using ggml_vec_dot_f32
// total rows in a
const int nr = nea1*nea2*nea3;
// rows per thread
const int dr = (nr + nth - 1)/nth;
// row range for this thread
const int ir0 = dr*ith;
const int ir1 = MIN(ir0 + dr, nr);
for (int ir = ir0; ir < ir1; ++ir) {
// a indices
const int ia3 = ir/(nea2*nea1);
const int ia2 = (ir - ia3*nea2*nea1)/nea1;
const int ia1 = (ir - ia3*nea2*nea1 - ia2*nea1);
float * S = (float *) params->wdata + ith*(2*M + CACHE_LINE_SIZE_F32);
for (int ic = 0; ic < neb01; ++ic) {
// b0 indices
const int ib03 = ia3;
const int ib02 = ia2;
const int ib01 = ic;
// S indices
const int i1 = ib01;
ggml_vec_dot_f16(nea0,
S + i1,
(ggml_fp16_t *) ((char *) b0->data + (ib01*nbb01 + ib02*nbb02 + ib03*nbb03)),
(ggml_fp16_t *) ((char *) a->data + ( ia1*nba1 + ia2*nba2 + ia3*nba3)));
}
ggml_vec_add_f32(neb01, S, S, (float *) b1->data);
//ggml_vec_gelu_f32(neb01, S, S);
ggml_fp16_t * S16 = (ggml_fp16_t *) ((float *) params->wdata + ith*(2*M + CACHE_LINE_SIZE_F32) + M);
for (int i = 0; i < M; i++) {
S16[i] = GGML_FP32_TO_FP16(S[i]);
}
ggml_vec_gelu_f16(neb01, S16, S16);
{
// dst indices
const int i1 = ia1;
const int i2 = ia2;
const int i3 = ia3;
for (int ic = 0; ic < nec01; ++ic) {
ggml_vec_dot_f16(neb01,
(float *) ((char *) dst->data + (ic*nb0 + i1*nb1 + i2*nb2 + i3*nb3)),
(ggml_fp16_t *) ((char *) c0->data + ( ic*nbc01 + i2*nbc02 + i3*nbc03)),
S16);
}
ggml_vec_add_f32(nec01,
(float *) ((char *) dst->data + (i1*nb1 + i2*nb2 + i3*nb3)),
(float *) ((char *) dst->data + (i1*nb1 + i2*nb2 + i3*nb3)),
(float *) c1->data);
}
}
}
|
// ggml_compute_forward_flash_ff
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L6127-L6305
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Whisper
|
github_2023
|
Const-me
|
c
|
ggml_compute_forward
|
static void ggml_compute_forward(struct ggml_compute_params * params, struct ggml_tensor * tensor) {
assert(params);
switch (tensor->op) {
case GGML_OP_DUP:
{
ggml_compute_forward_dup(params, tensor->src0, tensor);
} break;
case GGML_OP_ADD:
{
ggml_compute_forward_add(params, tensor->src0, tensor->src1, tensor);
} break;
case GGML_OP_SUB:
{
ggml_compute_forward_sub(params, tensor->src0, tensor->src1, tensor);
} break;
case GGML_OP_MUL:
{
ggml_compute_forward_mul(params, tensor->src0, tensor->src1, tensor);
} break;
case GGML_OP_DIV:
{
ggml_compute_forward_div(params, tensor->src0, tensor->src1, tensor);
} break;
case GGML_OP_SQR:
{
ggml_compute_forward_sqr(params, tensor->src0, tensor);
} break;
case GGML_OP_SQRT:
{
ggml_compute_forward_sqrt(params, tensor->src0, tensor);
} break;
case GGML_OP_SUM:
{
ggml_compute_forward_sum(params, tensor->src0, tensor);
} break;
case GGML_OP_MEAN:
{
ggml_compute_forward_mean(params, tensor->src0, tensor);
} break;
case GGML_OP_REPEAT:
{
ggml_compute_forward_repeat(params, tensor->src0, tensor);
} break;
case GGML_OP_ABS:
{
ggml_compute_forward_abs(params, tensor->src0, tensor);
} break;
case GGML_OP_SGN:
{
ggml_compute_forward_sgn(params, tensor->src0, tensor);
} break;
case GGML_OP_NEG:
{
ggml_compute_forward_neg(params, tensor->src0, tensor);
} break;
case GGML_OP_STEP:
{
ggml_compute_forward_step(params, tensor->src0, tensor);
} break;
case GGML_OP_RELU:
{
ggml_compute_forward_relu(params, tensor->src0, tensor);
} break;
case GGML_OP_GELU:
{
ggml_compute_forward_gelu(params, tensor->src0, tensor);
} break;
case GGML_OP_NORM:
{
ggml_compute_forward_norm(params, tensor->src0, tensor);
} break;
case GGML_OP_MUL_MAT:
{
ggml_compute_forward_mul_mat(params, tensor->src0, tensor->src1, tensor);
} break;
case GGML_OP_SCALE:
{
ggml_compute_forward_scale(params, tensor->src0, tensor->src1, tensor);
} break;
case GGML_OP_CPY:
{
ggml_compute_forward_cpy(params, tensor->src0, tensor);
} break;
case GGML_OP_RESHAPE:
{
ggml_compute_forward_reshape(params, tensor->src0, tensor);
} break;
case GGML_OP_VIEW:
{
ggml_compute_forward_view(params, tensor->src0);
} break;
case GGML_OP_PERMUTE:
{
ggml_compute_forward_permute(params, tensor->src0);
} break;
case GGML_OP_TRANSPOSE:
{
ggml_compute_forward_transpose(params, tensor->src0);
} break;
case GGML_OP_GET_ROWS:
{
ggml_compute_forward_get_rows(params, tensor->src0, tensor->src1, tensor);
} break;
case GGML_OP_DIAG_MASK_INF:
{
ggml_compute_forward_diag_mask_inf(params, tensor->src0, tensor->src1, tensor);
} break;
case GGML_OP_SOFT_MAX:
{
ggml_compute_forward_soft_max(params, tensor->src0, tensor);
} break;
case GGML_OP_ROPE:
{
ggml_compute_forward_rope(params, tensor->src0, tensor->src1, tensor);
} break;
case GGML_OP_CONV_1D_1S:
{
ggml_compute_forward_conv_1d_1s(params, tensor->src0, tensor->src1, tensor);
} break;
case GGML_OP_CONV_1D_2S:
{
ggml_compute_forward_conv_1d_2s(params, tensor->src0, tensor->src1, tensor);
} break;
case GGML_OP_FLASH_ATTN:
{
int32_t t = ggml_get_i32_1d(tensor->opt[1], 0);
GGML_ASSERT(t == 0 || t == 1);
bool masked = t != 0;
ggml_compute_forward_flash_attn(params, tensor->src0, tensor->src1, tensor->opt[0], masked, tensor);
} break;
case GGML_OP_FLASH_FF:
{
ggml_compute_forward_flash_ff(params, tensor->src0, tensor->src1, tensor->opt[0], tensor->opt[1], tensor->opt[2], tensor);
} break;
case GGML_OP_NONE:
{
// nop
} break;
case GGML_OP_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
|
/////////////////////////////////
|
https://github.com/Const-me/Whisper/blob/306aadd1fce4b168cd38659236f4ba7c1603cebd/Whisper/source/ggml.c#L6336-L6480
|
306aadd1fce4b168cd38659236f4ba7c1603cebd
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.