- 1
- 2
- 3
- 4
- 5
#define POOL_ZERO_DOWN_LEVEL_SUPPORT
#include <wdm.h>
char* p = ExAllocatePoolZero(NonPagedPool, 42, '_GK_');
ASSERT(p[0] == 0);
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
0
#define POOL_ZERO_DOWN_LEVEL_SUPPORT
#include <wdm.h>
char* p = ExAllocatePoolZero(NonPagedPool, 42, '_GK_');
ASSERT(p[0] == 0);
https://www.osr.com/blog/2020/07/14/bug-in-new-function-exallocatepoolzero-results-in-security-vulnerability-and-crashes/
microsoft_real_calloc() и 100500 способов отстрела ноги с помощью него.
0
// https://github.com/microsoft/Windows-driver-samples/blob/d3ec258921cfcef7b053b5a2c866330d43dd3f03/filesys/fastfat/dumpsup.c#L35
#define DumpLabel(Label,Width) { \
size_t i, LastPeriod=0; \
CHAR _Str[20]; \
for(i=0;i<2;i++) { _Str[i] = UCHAR_SP;} \
for(i=0;i<strlen(#Label);i++) {if (#Label[i] == '.') LastPeriod = i;} \
strncpy(&_Str[2],&#Label[LastPeriod],Width); \
for(i=strlen(_Str);i<Width;i++) {_Str[i] = UCHAR_SP;} \
_Str[Width] = '\0'; \
DbgPrint("%s", _Str); \
}
#define DumpField(Field) { \
if ((FatDumpCurrentColumn + 18 + 9 + 9) > 80) {DumpNewLine();} \
FatDumpCurrentColumn += 18 + 9 + 9; \
DumpLabel(Field,18); \
DbgPrint(":%p", Ptr->Field); \
DbgPrint(" "); \
}
#define DumpListEntry(Links) { \
if ((FatDumpCurrentColumn + 18 + 9 + 9) > 80) {DumpNewLine();} \
FatDumpCurrentColumn += 18 + 9 + 9; \
DumpLabel(Links,18); \
DbgPrint(":%p", Ptr->Links.Flink); \
DbgPrint(":%p", Ptr->Links.Blink); \
}
#define DumpName(Field,Width) { \
ULONG i; \
CHAR _String[256]; \
if ((FatDumpCurrentColumn + 18 + Width) > 80) {DumpNewLine();} \
FatDumpCurrentColumn += 18 + Width; \
DumpLabel(Field,18); \
for(i=0;i<Width;i++) {_String[i] = (CHAR)Ptr->Field[i];} \
_String[Width] = '\0'; \
DbgPrint("%s", _String); \
}
#define TestForNull(Name) { \
if (Ptr == NULL) { \
DbgPrint("%s - Cannot dump a NULL pointer\n", Name); \
return; \
} \
}
Макроговно от мекомягких для отладки файловой системы FAT
+2
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <limits.h>
typedef unsigned __int128 uint128_t;
typedef __int128 int128_t;
// в чем тут по-вашему баг ?
uint64_t add1bit_left_1_bug(const uint64_t a, int shift)
{
return ~(~(a << shift) >> shift);
}
uint64_t add1bit_left_1(const uint64_t a, int shift)
{
return ~((uint128_t)~(uint64_t)((uint128_t)a << shift) >> shift);
}
// или тут ?
uint64_t add1bit_left_2_bug(const uint64_t a, int shift)
{
return a | (uint64_t)(UINT64_MAX << (CHAR_BIT * sizeof(uint64_t) - shift));
}
uint64_t add1bit_left_2(const uint64_t a, int shift)
{
return a | (uint64_t)((uint128_t)-1 << (CHAR_BIT * sizeof(uint64_t) - shift));
}
uint64_t add1bit_left_3(const uint64_t a, int shift)
{
if (shift == 0) return a;
return (uint64_t)((int64_t)((a << (shift-1)) | ((uint64_t)1 << (CHAR_BIT * sizeof(uint64_t) - 1)) ) >> (shift-1)); // а тут вообще UB
}
int main(void)
{
// tests
for (int i = 0; i <= 64; i++) // пробуем сдвигать от 0 до 64 включительно.
{
// for (uint128_t j = 0; j < UINT64_MAX+1; j++) - какая формальная верификация )))
for (uint64_t j = 0; j < 100; j++)
{
if (add1bit_left_1(j,i) != add1bit_left_2(j,i))
{
printf("error1\n");
printf("%" PRIu64 " %d\n", j,i);
return EXIT_FAILURE;
}
if (add1bit_left_1(j,i) != add1bit_left_3(j,i))
printf("error2\n");
if (add1bit_left_2(j,i) != add1bit_left_3(j,i))
printf("error3\n");
}
}
printf("%" PRIX64 "\n", add1bit_left_1(0,0));
printf("%" PRIX64 "\n", add1bit_left_2(0,0));
printf("%" PRIX64 "\n", add1bit_left_3(0,0));
printf("%" PRIX64 " - bug\n", add1bit_left_1_bug(0,0));
printf("%" PRIX64 " - bug\n", add1bit_left_2_bug(0,0));
puts("");
printf("%" PRIX64 "\n", add1bit_left_1(0,1));
printf("%" PRIX64 "\n", add1bit_left_2(0,1));
printf("%" PRIX64 "\n", add1bit_left_3(0,1));
printf("%" PRIX64 " - bug\n", add1bit_left_1_bug(0,1));
printf("%" PRIX64 " - bug\n", add1bit_left_2_bug(0,1));
puts("");
printf("%" PRIX64 "\n", add1bit_left_1(0,2));
printf("%" PRIX64 "\n", add1bit_left_2(0,2));
printf("%" PRIX64 "\n", add1bit_left_3(0,2));
printf("%" PRIX64 " - bug\n", add1bit_left_2_bug(0,2));
printf("%" PRIX64 " - bug\n", add1bit_left_2_bug(0,2));
puts("");
printf("%" PRIX64 "\n", add1bit_left_1(0,64));
printf("%" PRIX64 "\n", add1bit_left_2(0,64));
printf("%" PRIX64 "\n", add1bit_left_3(0,64));
printf("%" PRIX64 " - bug\n", add1bit_left_1_bug(0,64));
printf("%" PRIX64 " - bug\n", add1bit_left_2_bug(0,64));
return EXIT_SUCCESS;
}
Вореанты говнофункции, которая сдвигает влево uint64_t но набрасывает единички вместо ноликов.
+5
// http://cmustdie.com/ - баттхерт анскильных лалок, неосиливших сишку
// Возьмём следующий фрагмент кода на языке Си:
int x = 1;
x = x << sizeof(int) * 8;
// Попробуем предположить, какой результат у нас получится. Допустим, мы скомпилировали этот
// код для процессоров архитектуры ARM. Инструкция битового сдвига в рамках этой аппаратной
// платформы определена так, что итоговым значением переменной "x" должен быть "0". С другой
// стороны, мы можем транслировать нашу программу в машинный код архитектуры x86. И уже там
// битовый сдвиг реализован таким образом, что значение "x" не изменится и останется равным
// "1". Мы могли бы сделать вывод, что результат работы данного фрагмента кода зависит от
// того, для какой аппаратной платформы мы его скомпилировали. Но на самом деле это не так.
// В действительности данный фрагмент кода может быть обработан компилятором любым возможным
// и невозможным образом. Причина в следующем: согласно тексту стандарта языка Си битовый
// сдвиг на величину, большую или равную размеру выражения в битах, является неопределённым
// поведением. Получается, нет никакой гарантии, что этот кусок кода вообще будет работать.
Охуеть конечно
+1
// https://github.com/j123123/sexpr_parse/blob/584fc23de71bebe02545214f819e16b720a2c1e2/my_struct_utils.c#L119
blob *
blob_scan_fromstream
(
FILE *stream
)
{
size_t st_len = 0;
size_t st_alloc;
uint8_t *st = NULL;
while(true)
{
const int fg = getc(stream);
if(fg == EOF)
{
PRV_ERR_MACRO();
}
uint8_t c = fg;
if(!isprint(fg))
{
PRV_ERR_MACRO();
}
switch(c)
{
case '\\':
{
int c2 = getc(stream);
switch(c2)
{
case 'x':
{
int c3[2] =
{
getc(stream),
getc(stream)
};
uint8_t tmp[2];
for(size_t i = 0; i < 2; ++i)
{
switch(c3[i])
{
case '0' ... '9':
tmp[i] = c3[i]-'0';
break;
case 'a' ... 'f':
tmp[i] = c3[i]+10-'a';
break;
case 'A' ... 'F':
tmp[i] = c3[i]+10-'A';
break;
default:
PRV_ERR_MACRO();
}
}
M_PUSH(tmp[1] | tmp[0] << 4);
}
break;
case '\\':
M_PUSH('\\');
break;
case 't':
M_PUSH('\t');
break;
case 'n':
M_PUSH('\n');
break;
case '"':
M_PUSH('"');
break;
default:
PRV_ERR_MACRO();
}
}
break;
// case '\t':
// case '\n':
// PRV_ERR_MACRO();
// break;
case '"':
goto end;
default:
M_PUSH(c);
}
}
end:
;
blob *tmp = blob_init(st_len, st);
PRV_FREE(st);
return tmp;
}
Эта вот хрень вычитывает из "FILE *" одно "слово".
+1
#include <stdio.h>
#define new(class) _##class##_##new
#define impl(class, method) _##class##_##method
struct Calculate
{
int(*getOne)(struct Calculate*);
};
int impl(Calculate, getOne)(struct Calculate* this) { return 1; }
void* new(Calculate)(void)
{
struct Calculate* class = malloc(sizeof(struct Calculate));
class->getOne = impl(Calculate, getOne);
return class;
}
struct CalculateProxy
{
struct Calculate;
};
int impl(CalculateProxy, getOne)(struct Calculate* this)
{
printf("Method call!\n");
return impl(Calculate, getOne)(this);
}
void* new(CalculateProxy)(void)
{
struct CalculateProxy* class = malloc(sizeof(struct CalculateProxy));
class->getOne = impl(CalculateProxy, getOne);
return class;
}
int main(void)
{
struct Calculate* calc = new(CalculateProxy)();
printf("%X!\n", calc->getOne(calc));
}
жавашок попросил реализовать паттерн прокси на Си
0
// https://github.com/dxFeed/dxfeed-c-api/blob/8f24055298c9751344db72da03ab8eb37dfeb6a5/src/DXAlgorithms.h#L63
#define CHECKED_CALL(func, param) \
do { \
if (!func(param)) { \
return false; \
} \
} while (false)
#define CHECKED_CALL_0(func) \
do { \
if (!func()) { \
return false; \
} \
} while (false)
#define CHECKED_CALL_1(func, param1) \
do { \
if (!func(param1)) { \
return false; \
} \
} while (false)
#define CHECKED_CALL_2(func, param1, param2) \
do { \
if (!func(param1, param2)) { \
return false; \
} \
} while (false)
#define CHECKED_CALL_3(func, param1, param2, param3) \
do { \
if (!func(param1, param2, param3)) { \
return false; \
} \
} while (false)
#define CHECKED_CALL_4(func, param1, param2, param3, param4) \
do { \
if (!func(param1, param2, param3, param4)) { \
return false; \
} \
} while (false)
#define CHECKED_CALL_5(func, param1, param2, param3, param4, param5) \
do { \
if (!func(param1, param2, param3, param4, param5)) { \
return false; \
} \
} while (false)
Мокроебства
0
/* https://github.com/v7unix/v7unix/blob/ed636a47207476db76d53b7869447889dee3bbad/v7/usr/src/cmd/sh/mac.h */
#
/*
* UNIX shell
*
* S. R. Bourne
* Bell Telephone Laboratories
*
*/
#define LOCAL static
#define PROC extern
#define TYPE typedef
#define STRUCT TYPE struct
#define UNION TYPE union
#define REG register
#define IF if(
#define THEN ){
#define ELSE } else {
#define ELIF } else if (
#define FI ;}
#define BEGIN {
#define END }
#define SWITCH switch(
#define IN ){
#define ENDSW }
#define FOR for(
#define WHILE while(
#define DO ){
#define OD ;}
#define REP do{
#define PER }while(
#define DONE );
#define LOOP for(;;){
#define POOL }
#define SKIP ;
#define DIV /
#define REM %
#define NEQ ^
#define ANDF &&
#define ORF ||
#define TRUE (-1)
#define FALSE 0
#define LOBYTE 0377
#define STRIP 0177
#define QUOTE 0200
#define EOF 0
#define NL '\n'
#define SP ' '
#define LQ '`'
#define RQ '\''
#define MINUS '-'
#define COLON ':'
#define MAX(a,b) ((a)>(b)?(a):(b))
0
// https://github.com/x42/darc.lv2/blob/7f1f42b879777e570c83fd566ac28cbfdd51e6fc/src/lv2.c#L508
static void
create_pattern (Darc* self, const double w)
{
const int x0 = floor (w * 0.05);
const int x1 = ceil (w * 0.95);
const int wd = x1 - x0;
#define DEF(x) ((x0 + wd * ((x) + 20.) / 60.) / w)
cairo_pattern_t* pat = cairo_pattern_create_linear (0.0, 0.0, w, 0);
/* clang-format off */
cairo_pattern_add_color_stop_rgba (pat, 1.0, .0, .5, .0, 0);
cairo_pattern_add_color_stop_rgba (pat, DEF (40), .0, .5, .0, 0.5);
cairo_pattern_add_color_stop_rgba (pat, DEF (5), .0, .5, .0, 0.5);
cairo_pattern_add_color_stop_rgba (pat, DEF (-5), .5, .0, .0, 0.5);
cairo_pattern_add_color_stop_rgba (pat, DEF (-20), .5, .0, .0, 0.5);
cairo_pattern_add_color_stop_rgba (pat, 0.0, .5, .0, .0, 0);
/* clang-format on */
self->mpat = pat;
pat = cairo_pattern_create_linear (0.0, 0.0, w, 0);
/* clang-format off */
cairo_pattern_add_color_stop_rgba (pat, 1.0, .1, .9, .1, 0);
cairo_pattern_add_color_stop_rgba (pat, DEF (40), .1, .9, .1, 1);
cairo_pattern_add_color_stop_rgba (pat, DEF (5), .1, .9, .1, 1);
cairo_pattern_add_color_stop_rgba (pat, DEF (-5), .9, .9, .1, 1);
cairo_pattern_add_color_stop_rgba (pat, DEF (-20), .9, .9, .1, 1);
cairo_pattern_add_color_stop_rgba (pat, 0.0, .9, .9, .1, 0);
/* clang-format on */
self->cpat = pat;
#undef DEF
}
Отключаем и включаем clang-формат, чтобы отступы красиво были. Да еще и такой вот локальный дефайн!
+1
#include <stdio.h>
#include <memory>
#define Property(type,name) type name;auto &set_##name(type val){name = val; return *this;}
#define Set(x,y) set_##x(y)
//#define Create(type, ...) (*(new type(__VA_ARGS__)))
template <typename T>
static inline T& Create_(const char *name)
{
return *(new T(name));
}
#define Create(type, ...) Create_<type>(__VA_ARGS__)
template <typename T>
static inline T CreateNoAlloc_(const char *name)
{
return T(name);
}
#define CreateNoAlloc(type, ...) CreateNoAlloc_<type>(__VA_ARGS__)
struct BaseItem
{
const char *Name;
BaseItem(const char *n): Name(n) {}
Property(int, Width);
Property(int, Height);
};
#include <vector>
struct Markup
{
std::vector<BaseItem*> Children;
template <typename T>
Markup &Add(T &item)
{
Children.push_back(&item);
return *this;
}
};
static inline Markup CreateMarkup(const char *n)
{
return Markup();
}
/*
struct Markup2
{
std::vector<std::shared_ptr<BaseItem>> Children;
template <typename T>
Markup2 &Add(T item)
{
Children.push_back(std::shared_ptr(&item));
return *this;
}
};
*/
template<std::size_t I = 0, typename... Tp>
inline typename std::enable_if<I == sizeof...(Tp), void>::type
print(std::tuple<Tp...>& t)
{ }
template<std::size_t I = 0, typename... Tp>
inline typename std::enable_if<I < sizeof...(Tp), void>::type
print(std::tuple<Tp...>& t)
{
printf("%s\n",std::get<I>(t).Name);
print<I + 1, Tp...>(t);
}
#include <string.h>
static BaseItem NOT_FOUND("NOT_FOUND");
template<typename T, std::size_t I = 0, typename... Tp>
inline typename std::enable_if<I == sizeof...(Tp), void>::type
print1(std::tuple<Tp...>& t, const char *n)
{ }
template<typename T, std::size_t I = 0, typename... Tp>
inline typename std::enable_if<I < sizeof...(Tp), T&>::type
print1(std::tuple<Tp...>& t, const char *n)
{
if( !strcmp(std::get<I>(t).Name, n))
return std::get<I>(t);
print1<T, I + 1, Tp...>(t,n);
return NOT_FOUND;
}
#define CreateMarkup(...) std::make_tuple(__VA_ARGS__)
#define AppendMarkup(src, ...) std::tuple_cat(src, std::make_tuple(__VA_ARGS__))
#define MarkupItem(markup,type,name,action) namespace {type &i = print1<type>(markup,name).action; }
auto markup1 = CreateMarkup(BaseItem("test").Set(Width,14), BaseItem("test2"));
auto markup2 = AppendMarkup(markup1,BaseItem("test3").Set(Width,15));
auto markup3 = markup1;
MarkupItem(markup3,BaseItem,"test2",Set(Width,16));
template <typename T>
Т.к юзается препроцессор, запощу в C