2018-11-20 05:16:29 -05:00
|
|
|
/*
|
|
|
|
* This file is part of the "Coroutine" project and released under the MIT License.
|
|
|
|
*
|
|
|
|
* Created by Samuel Williams on 10/5/2018.
|
|
|
|
* Copyright, 2018, by Samuel Williams. All rights reserved.
|
|
|
|
*/
|
2018-11-20 04:59:10 -05:00
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <assert.h>
|
|
|
|
#include <string.h>
|
|
|
|
|
2018-11-20 05:16:41 -05:00
|
|
|
#define COROUTINE __declspec(noreturn) void __fastcall
|
2019-07-16 00:11:55 -04:00
|
|
|
#define COROUTINE_LIMITED_ADDRESS_SPACE
|
2018-11-20 04:59:10 -05:00
|
|
|
|
2018-11-20 05:17:39 -05:00
|
|
|
/* This doesn't include thread information block */
|
2019-05-16 02:51:37 -04:00
|
|
|
enum {COROUTINE_REGISTERS = 4};
|
2018-11-20 04:59:10 -05:00
|
|
|
|
2019-06-24 07:54:19 -04:00
|
|
|
struct coroutine_context
|
2018-11-20 04:59:10 -05:00
|
|
|
{
|
2018-11-20 15:09:38 -05:00
|
|
|
void **stack_pointer;
|
2019-06-24 07:54:19 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
typedef void(__fastcall * coroutine_start)(struct coroutine_context *from, struct coroutine_context *self);
|
2018-11-20 04:59:10 -05:00
|
|
|
|
2019-06-24 07:54:19 -04:00
|
|
|
static inline void coroutine_initialize_main(struct coroutine_context * context) {
|
|
|
|
context->stack_pointer = NULL;
|
|
|
|
}
|
2018-11-20 04:59:10 -05:00
|
|
|
|
2018-11-20 05:17:17 -05:00
|
|
|
static inline void coroutine_initialize(
|
2019-06-24 07:54:19 -04:00
|
|
|
struct coroutine_context *context,
|
2018-11-20 15:09:38 -05:00
|
|
|
coroutine_start start,
|
2019-06-24 07:54:19 -04:00
|
|
|
void *stack,
|
|
|
|
size_t size
|
2018-11-20 04:59:10 -05:00
|
|
|
) {
|
2019-06-24 07:54:19 -04:00
|
|
|
assert(start && stack && size >= 1024);
|
2018-11-20 04:59:10 -05:00
|
|
|
|
2019-06-24 07:54:19 -04:00
|
|
|
// Stack grows down. Force 16-byte alignment.
|
|
|
|
char * top = (char*)stack + size;
|
|
|
|
context->stack_pointer = (void**)((uintptr_t)top & ~0xF);
|
2018-11-20 04:59:10 -05:00
|
|
|
|
2018-11-20 15:09:38 -05:00
|
|
|
*--context->stack_pointer = (void*)start;
|
2018-11-20 05:17:44 -05:00
|
|
|
|
2018-11-20 15:09:38 -05:00
|
|
|
/* Windows Thread Information Block */
|
|
|
|
*--context->stack_pointer = 0; /* fs:[0] */
|
2019-06-24 07:54:19 -04:00
|
|
|
*--context->stack_pointer = (void*)top; /* fs:[4] */
|
|
|
|
*--context->stack_pointer = (void*)stack; /* fs:[8] */
|
2018-11-20 04:59:10 -05:00
|
|
|
|
2018-11-20 15:09:38 -05:00
|
|
|
context->stack_pointer -= COROUTINE_REGISTERS;
|
|
|
|
memset(context->stack_pointer, 0, sizeof(void*) * COROUTINE_REGISTERS);
|
2018-11-20 04:59:10 -05:00
|
|
|
}
|
|
|
|
|
2019-06-24 07:54:19 -04:00
|
|
|
struct coroutine_context * __fastcall coroutine_transfer(struct coroutine_context * current, struct coroutine_context * target);
|
2018-11-20 04:59:10 -05:00
|
|
|
|
2019-06-24 07:54:19 -04:00
|
|
|
static inline void coroutine_destroy(struct coroutine_context * context)
|
2018-11-20 04:59:10 -05:00
|
|
|
{
|
|
|
|
}
|