repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
reinvanimschoot/c-programming-a-modern-approach-solutions
|
chapter_7/projects/12/12.c
|
<filename>chapter_7/projects/12/12.c
#include <stdio.h>
int main(void)
{
char c, operation;
float operand_1, operand_2, total;
printf("Enter an expression: ");
scanf("%f", &operand_1);
while ((c = getchar()) != '\n')
{
operation = c;
scanf("%f", &operand_2);
switch (operation)
{
case '+':
total = operand_1 + operand_2;
break;
case '-':
total = operand_1 - operand_2;
break;
case '/':
total = operand_1 / operand_2;
break;
case '*':
total = operand_1 * operand_2;
break;
}
operand_1 = total;
}
printf("Value of expression: %.1f", total);
return 0;
}
|
reinvanimschoot/c-programming-a-modern-approach-solutions
|
chapter_5/projects/04/04.c
|
<filename>chapter_5/projects/04/04.c
#include <stdio.h>
int main(void)
{
int windspeed;
printf("Enter windspeed in knots:");
scanf("%d", &windspeed);
if (windspeed < 1)
printf("Windspeed is currently categorized as Calm.");
else if (windspeed < 4)
printf("Windspeed is currently categorized as Light air.");
else if (windspeed < 28)
printf("Windspeed is currently categorized as Breeze.");
else if (windspeed < 28)
printf("Windspeed is currently categorized as Breeze.");
return 0;
}
|
reinvanimschoot/c-programming-a-modern-approach-solutions
|
chapter_13/projects/07/7.c
|
<reponame>reinvanimschoot/c-programming-a-modern-approach-solutions<filename>chapter_13/projects/07/7.c
#include <stdio.h>
int main(void) {
int n;
char *tens[] = {"twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninety"},
*teens[] = {"ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen"},
*ones[] = {"", "-one", "-two", "-three", "-four", "-five",
"-six", "-seven", "-eight", "-nine"};
printf("Enter a two-digit number: ");
scanf("%d", &n);
printf("You entered the number ");
if (n / 10 == 1)
printf("%s\n", teens[n % 10]);
else
printf("%s%s\n", tens[n / 10 - 2], ones[n % 10]);
return 0;
}
|
reinvanimschoot/c-programming-a-modern-approach-solutions
|
chapter_4/projects/02/02.c
|
#include <stdio.h>
int main(void)
{
int number, digit_1, remainder, digit_2, digit_3;
printf("Enter a three-digit number:");
scanf("%d", &number);
digit_1 = number / 100;
remainder = number % 100;
digit_2 = remainder / 10;
digit_3 = remainder % 10;
printf("The reversal is: %d%d%d", digit_3, digit_2, digit_1);
return 0;
}
|
reinvanimschoot/c-programming-a-modern-approach-solutions
|
chapter_6/projects/05/05.c
|
#include <stdio.h>
int main(void)
{
int number;
printf("Please enter a number: ");
scanf("%d", &number);
do
{
printf("%d", number % 10);
number /= 10;
} while (number > 0);
return 0;
}
|
reinvanimschoot/c-programming-a-modern-approach-solutions
|
chapter_3/projects/02/02.c
|
#include <stdio.h>
int main(void)
{
int item_number, purchase_date_month, purchase_date_day, purchase_date_year;
float unit_price;
printf("Enter item number: ");
scanf("%d", &item_number);
printf("Enter unit price: ");
scanf("%f", &unit_price);
printf("Enter purchase date (mm/dd/yyy): ");
scanf("%d /%d /%d", &purchase_date_month, &purchase_date_day, &purchase_date_year);
printf("\nItem\t\tUnit\t\tPurchase\n");
printf("\t\tPrice\t\tDate\n");
printf("%-10d\t$%7.2f\t%.2d/%.2d/%.4d", item_number, unit_price, purchase_date_month, purchase_date_day, purchase_date_year);
return 0;
}
|
reinvanimschoot/c-programming-a-modern-approach-solutions
|
chapter_6/projects/01/01.c
|
<gh_stars>0
#include <stdio.h>
int main(void)
{
float max, number;
max = 0;
while (number != 0)
{
printf("Enter a number:");
scanf("%f", &number);
if (number > max)
{
max = number;
}
}
printf("The largest number entered was %.2f", max);
return 0;
}
|
reinvanimschoot/c-programming-a-modern-approach-solutions
|
chapter_5/projects/01/01.c
|
#include <stdio.h>
int main(void)
{
int number, digit_amount;
printf("Enter a number:");
scanf("%d", &number);
if (number < 10)
digit_amount = 1;
else if (number < 100)
digit_amount = 2;
else if (number < 1000)
digit_amount = 3;
else
digit_amount = 4;
printf("The number %d has %d digit(s).", number, digit_amount);
return 0;
}
|
reinvanimschoot/c-programming-a-modern-approach-solutions
|
chapter_5/projects/02/02.c
|
<gh_stars>0
#include <stdio.h>
int main(void)
{
int hours_in_24, minutes, hours_in_12;
printf("Enter a 24-hour time: ");
scanf("%2d:%2d", &hours_in_24, &minutes);
hours_in_12 = (hours_in_24 == 12 || hours_in_24 == 0) ? 12 : hours_in_24 - 12;
printf("Equivalent 12-hour time: %2.2d:%2.2d", hours_in_12, minutes);
if (hours_in_24 >= 12)
printf(" PM\n");
else
printf(" AM\n");
return 0;
}
|
reinvanimschoot/c-programming-a-modern-approach-solutions
|
chapter_5/projects/09/09.c
|
#include <stdio.h>
int main(void)
{
int date_1_day, date_1_month, date_1_year, date_2_day, date_2_month, date_2_year;
printf("Enter first date (mm/dd/yyyy): ");
scanf("%d/%d/%d", &date_1_day, &date_1_month, &date_1_year);
printf("Enter second date (mm/dd/yyyy): ");
scanf("%d/%d/%d", &date_2_day, &date_2_month, &date_2_year);
if (date_1_year < date_2_year)
printf("%.2d/%.2d/%.2d is earlier than %.2d/%.2d/%.2d", date_1_day, date_1_month, date_1_year, date_2_day, date_2_month, date_2_year);
else if (date_2_year < date_1_year)
printf("%.2d/%.2d/%.2d is earlier than %.2d/%.2d/%.2d", date_2_day, date_2_month, date_2_year, date_1_day, date_1_month, date_1_year);
else if (date_1_month < date_2_month)
printf("%.2d/%.2d/%.2d is earlier than %.2d/%.2d/%.2d", date_1_day, date_1_month, date_1_year, date_2_day, date_2_month, date_2_year);
else if (date_1_month < date_2_month)
printf("%.2d/%.2d/%.2d is earlier than %.2d/%.2d/%.2d", date_2_day, date_2_month, date_2_year, date_1_day, date_1_month, date_1_year);
else if (date_1_day < date_2_day)
printf("%.2d/%.2d/%.2d is earlier than %.2d/%.2d/%.2d", date_1_day, date_1_month, date_1_year, date_2_day, date_2_month, date_2_year);
else if (date_2_day < date_1_day)
printf("%.2d/%.2d/%.2d is earlier than %.2d/%.2d/%.2d", date_2_day, date_2_month, date_2_year, date_1_day, date_1_month, date_1_year);
else
printf("Both dates are the same.");
return 0;
}
|
reinvanimschoot/c-programming-a-modern-approach-solutions
|
chapter_7/projects/09/09.c
|
#include <stdio.h>
#include <ctype.h>
int main(void)
{
int hours_in_12, hours_in_24, minutes;
char indicator;
printf("Enter a 12-hour time: ");
scanf("%2d:%2d %c", &hours_in_12, &minutes, &indicator);
if (tolower(indicator) == 'a')
hours_in_24 = hours_in_12;
else
hours_in_24 = hours_in_12 + 12;
printf("Equivalent in 24-time: %.2d:%.2d", hours_in_24, minutes);
return 0;
}
|
BenElhadj/get_next_line
|
get_next_line.c
|
<gh_stars>0
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bhamdi <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/09/30 16:31:53 by bhamdi #+# #+# */
/* Updated: 2018/01/24 22:33:11 by bhamdi ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
static size_t get_strlen(const char *str)
{
size_t i;
i = 0;
if (str == NULL)
return (0);
while (str[i])
i++;
return (i);
}
static char *get_strcpy(char *dest, const char *src)
{
size_t i;
i = 0;
if (src == 0)
{
dest[i] = '\0';
return (dest);
}
while (src[i])
{
dest[i] = src[i];
i++;
}
dest[i] = '\0';
return (dest);
}
static char *get_strncat(char *dest, const char *src, size_t nb)
{
size_t size;
size_t i;
size = 0;
i = 0;
while (dest[size])
size++;
while (src[i] && i < nb)
{
dest[size + i] = src[i];
i++;
}
dest[size + i] = '\0';
return (dest);
}
static int get_line(char *buf, char **line)
{
char *temp;
int i;
int k;
i = -1;
k = 0;
while (buf[++i])
if (buf[i] == '\n')
break ;
if (!(temp = (char *)malloc(sizeof(char) * (get_strlen(*line) + i + 1))))
return (0);
get_strcpy(temp, *line);
free(*line);
get_strncat(temp, buf, i);
buf[i] == '\n' ? k = 1 : 0;
if (k != 1)
buf[0] = '\0';
else
get_strcpy(buf, &(buf[i + 1]));
*line = temp;
return (k);
}
int get_next_line(const int fd, char **line)
{
static char buf[NB_FD][BUFF_SIZE + 1];
int ret;
if (fd < 0 || !line || read(fd, &ret, 0) == -1)
return (-1);
*line = NULL;
ret = 0;
if (buf[fd][0] && get_line(buf[fd], line) == 1)
return (1);
while ((ret = read(fd, buf[fd], BUFF_SIZE)) > 0)
{
buf[fd][ret] = '\0';
if (get_line(buf[fd], line) == 1)
return (1);
}
return (*line ? 1 : 0);
}
|
jvanhoefer/AMICI
|
models/model_robertson/model_robertson.h
|
#ifndef _amici_model_robertson_h
#define _amici_model_robertson_h
/* Generated by amiwrap (R2017b) 2bd39716102b9842354964196889d40d2eb2731c */
#include <cmath>
#include <memory>
#include "amici/defines.h"
#include <sunmatrix/sunmatrix_sparse.h> //SUNMatrixContent_Sparse definition
#include "amici/solver_idas.h"
#include "amici/model_dae.h"
namespace amici {
class Solver;
namespace model_model_robertson{
extern void JSparse_model_robertson(SUNMatrixContent_Sparse JSparse, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype cj, const realtype *dx, const realtype *w, const realtype *dwdx);
extern void Jy_model_robertson(double *nllh, const int iy, const realtype *p, const realtype *k, const double *y, const double *sigmay, const double *my);
extern void M_model_robertson(realtype *M, const realtype t, const realtype *x, const realtype *p, const realtype *k);
extern void dJydsigma_model_robertson(double *dJydsigma, const int iy, const realtype *p, const realtype *k, const double *y, const double *sigmay, const double *my);
extern void dJydy_model_robertson(double *dJydy, const int iy, const realtype *p, const realtype *k, const double *y, const double *sigmay, const double *my);
extern void dwdp_model_robertson(realtype *dwdp, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *tcl, const realtype *stcl);
extern void dwdx_model_robertson(realtype *dwdx, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *tcl);
extern void dxdotdp_model_robertson(realtype *dxdotdp, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip, const realtype *dx, const realtype *w, const realtype *dwdp);
extern void dydx_model_robertson(double *dydx, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *dwdx);
extern void sigmay_model_robertson(double *sigmay, const realtype t, const realtype *p, const realtype *k);
extern void w_model_robertson(realtype *w, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *tcl);
extern void x0_model_robertson(realtype *x0, const realtype t, const realtype *p, const realtype *k);
extern void xdot_model_robertson(realtype *xdot, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *dx, const realtype *w);
extern void y_model_robertson(double *y, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w);
class Model_model_robertson : public amici::Model_DAE {
public:
Model_model_robertson()
: amici::Model_DAE(
amici::ModelDimensions(
3,
3,
3,
3,
0,
3,
1,
3,
3,
0,
0,
0,
1,
1,
2,
1,
0,
0,
{},
9,
2,
2
),
amici::SimulationParameters(
std::vector<realtype>(1, 1.0),
std::vector<realtype>(3, 1.0)
),
amici::SecondOrderMode::none,
std::vector<realtype>{1, 1, 0},
std::vector<int>{})
{};
amici::Model* clone() const override { return new Model_model_robertson(*this); };
std::string getAmiciCommit() const override { return "2bd39716102b9842354964196889d40d2eb2731c"; };
void fJSparse(SUNMatrixContent_Sparse JSparse, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype cj, const realtype *dx, const realtype *w, const realtype *dwdx) override {
JSparse_model_robertson(JSparse, t, x, p, k, h, cj, dx, w, dwdx);
}
void fJrz(double *nllh, const int iz, const realtype *p, const realtype *k, const double *rz, const double *sigmaz) override {
}
void fJy(double *nllh, const int iy, const realtype *p, const realtype *k, const double *y, const double *sigmay, const double *my) override {
Jy_model_robertson(nllh, iy, p, k, y, sigmay, my);
}
void fJz(double *nllh, const int iz, const realtype *p, const realtype *k, const double *z, const double *sigmaz, const double *mz) override {
}
void fM(realtype *M, const realtype t, const realtype *x, const realtype *p, const realtype *k) override {
M_model_robertson(M, t, x, p, k);
}
void fdJrzdsigma(double *dJrzdsigma, const int iz, const realtype *p, const realtype *k, const double *rz, const double *sigmaz) override {
}
void fdJrzdz(double *dJrzdz, const int iz, const realtype *p, const realtype *k, const double *rz, const double *sigmaz) override {
}
void fdJydsigma(double *dJydsigma, const int iy, const realtype *p, const realtype *k, const double *y, const double *sigmay, const double *my) override {
dJydsigma_model_robertson(dJydsigma, iy, p, k, y, sigmay, my);
}
void fdJydy(double *dJydy, const int iy, const realtype *p, const realtype *k, const double *y, const double *sigmay, const double *my) override {
dJydy_model_robertson(dJydy, iy, p, k, y, sigmay, my);
}
void fdJzdsigma(double *dJzdsigma, const int iz, const realtype *p, const realtype *k, const double *z, const double *sigmaz, const double *mz) override {
}
void fdJzdz(double *dJzdz, const int iz, const realtype *p, const realtype *k, const double *z, const double *sigmaz, const double *mz) override {
}
void fdeltaqB(double *deltaqB, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip, const int ie, const realtype *xdot, const realtype *xdot_old, const realtype *xB) override {
}
void fdeltasx(double *deltasx, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const int ip, const int ie, const realtype *xdot, const realtype *xdot_old, const realtype *sx, const realtype *stau) override {
}
void fdeltax(double *deltax, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ie, const realtype *xdot, const realtype *xdot_old) override {
}
void fdeltaxB(double *deltaxB, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ie, const realtype *xdot, const realtype *xdot_old, const realtype *xB) override {
}
void fdrzdp(double *drzdp, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip) override {
}
void fdrzdx(double *drzdx, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h) override {
}
void fdsigmaydp(double *dsigmaydp, const realtype t, const realtype *p, const realtype *k, const int ip) override {
}
void fdsigmazdp(double *dsigmazdp, const realtype t, const realtype *p, const realtype *k, const int ip) override {
}
void fdwdp(realtype *dwdp, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *tcl, const realtype *stcl) override {
dwdp_model_robertson(dwdp, t, x, p, k, h, w, tcl, stcl);
}
void fdwdx(realtype *dwdx, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *tcl) override {
dwdx_model_robertson(dwdx, t, x, p, k, h, w, tcl);
}
void fdxdotdp(realtype *dxdotdp, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip, const realtype *dx, const realtype *w, const realtype *dwdp) override {
dxdotdp_model_robertson(dxdotdp, t, x, p, k, h, ip, dx, w, dwdp);
}
void fdydp(double *dydp, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip, const realtype *w, const realtype *dwdp) override {
}
void fdydx(double *dydx, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *dwdx) override {
dydx_model_robertson(dydx, t, x, p, k, h, w, dwdx);
}
void fdzdp(double *dzdp, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip) override {
}
void fdzdx(double *dzdx, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h) override {
}
void froot(realtype *root, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *dx) override {
}
void frz(double *rz, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h) override {
}
void fsigmay(double *sigmay, const realtype t, const realtype *p, const realtype *k) override {
sigmay_model_robertson(sigmay, t, p, k);
}
void fsigmaz(double *sigmaz, const realtype t, const realtype *p, const realtype *k) override {
}
void fsrz(double *srz, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *sx, const int ip) override {
}
void fstau(double *stau, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *sx, const int ip, const int ie) override {
}
void fsx0(realtype *sx0, const realtype t,const realtype *x0, const realtype *p, const realtype *k, const int ip) override {
}
void fsz(double *sz, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *sx, const int ip) override {
}
void fw(realtype *w, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *tcl) override {
w_model_robertson(w, t, x, p, k, h, tcl);
}
void fx0(realtype *x0, const realtype t, const realtype *p, const realtype *k) override {
x0_model_robertson(x0, t, p, k);
}
void fxdot(realtype *xdot, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *dx, const realtype *w) override {
xdot_model_robertson(xdot, t, x, p, k, h, dx, w);
}
void fy(double *y, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w) override {
y_model_robertson(y, t, x, p, k, h, w);
}
void fz(double *z, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h) override {
}
};
} // namespace model_model_robertson
} // namespace amici
#endif /* _amici_model_robertson_h */
|
jvanhoefer/AMICI
|
include/amici/simulation_parameters.h
|
<gh_stars>10-100
#ifndef AMICI_SIMULATION_PARAMETERS_H
#define AMICI_SIMULATION_PARAMETERS_H
#include "amici/defines.h"
#include <vector>
namespace amici {
/**
* @brief Container for various simulation parameters.
*/
class SimulationParameters {
public:
SimulationParameters() = default;
/**
* @brief Constructor
* @param timepoints Timepoints for which simulation results are requested
*/
explicit SimulationParameters(std::vector<realtype> timepoints)
: ts_(std::move(timepoints))
{
}
/**
* @brief Constructor
* @param fixedParameters Model constants
* @param parameters Model parameters
*/
SimulationParameters(std::vector<realtype> fixedParameters,
std::vector<realtype> parameters)
: fixedParameters(std::move(fixedParameters)),
parameters(std::move(parameters)),
pscale(std::vector<ParameterScaling>(this->parameters.size(),
ParameterScaling::none))
{
}
/**
* @brief Constructor
* @param fixedParameters Model constants
* @param parameters Model parameters
* @param plist Model parameter indices w.r.t. which sensitivities are to be
* computed
*/
SimulationParameters(std::vector<realtype> fixedParameters,
std::vector<realtype> parameters,
std::vector<int> plist
)
: fixedParameters(std::move(fixedParameters)),
parameters(std::move(parameters)),
pscale(std::vector<ParameterScaling>(this->parameters.size(),
ParameterScaling::none)),
plist(std::move(plist))
{
}
/**
* @brief Constructor
* @param timepoints Timepoints for which simulation results are requested
* @param fixedParameters Model constants
* @param parameters Model parameters
*/
SimulationParameters(std::vector<realtype> timepoints,
std::vector<realtype> fixedParameters,
std::vector<realtype> parameters)
: fixedParameters(std::move(fixedParameters)),
parameters(std::move(parameters)),
pscale(std::vector<ParameterScaling>(this->parameters.size(),
ParameterScaling::none)),
ts_(std::move(timepoints))
{
}
/**
* @brief Set reinitialization of all states based on model constants for
* presimulation (only meaningful if preequilibration is performed).
*
* Convenience function to populate
* `reinitialization_state_idxs_presim` and
* `reinitialization_state_idxs_sim`
*
* @param nx_rdata Number of states (Model::nx_rdata)
*/
void reinitializeAllFixedParameterDependentInitialStatesForPresimulation(int nx_rdata);
/**
* @brief Set reinitialization of all states based on model constants for
* the 'main' simulation (only meaningful if presimulation or
* preequilibration is performed).
*
* Convenience function to populate
* `reinitialization_state_idxs_presim` and
* `reinitialization_state_idxs_sim`
*
* @param nx_rdata Number of states (Model::nx_rdata)
*/
void reinitializeAllFixedParameterDependentInitialStatesForSimulation(int nx_rdata);
/**
* @brief Set reinitialization of all states based on model constants for
* all simulation phases.
*
* Convenience function to populate
* `reinitialization_state_idxs_presim` and
* `reinitialization_state_idxs_sim`
*
* @param nx_rdata Number of states (Model::nx_rdata)
*/
void reinitializeAllFixedParameterDependentInitialStates(int nx_rdata);
/**
* @brief Model constants
*
* Vector of size Model::nk() or empty
*/
std::vector<realtype> fixedParameters;
/**
* @brief Model constants for pre-equilibration
*
* Vector of size Model::nk() or empty. Overrides Solver::newton_preeq
*/
std::vector<realtype> fixedParametersPreequilibration;
/**
* @brief Model constants for pre-simulation
*
* Vector of size Model::nk() or empty.
*/
std::vector<realtype> fixedParametersPresimulation;
/**
* @brief Model parameters
*
* Vector of size Model::np() or empty with parameter scaled according to
* SimulationParameter::pscale.
*/
std::vector<realtype> parameters;
/**
* @brief Initial state
*
* Vector of size Model::nx() or empty
*/
std::vector<realtype> x0;
/**
* @brief Initial state sensitivities
*
* Dimensions:
* Model::nx() * Model::nplist(), Model::nx() * ExpData::plist.size(), if
* ExpData::plist is not empty, or empty
*/
std::vector<realtype> sx0;
/**
* @brief Parameter scales
*
* Vector of parameter scale of size Model::np(), indicating how/if each
* parameter is to be scaled.
*/
std::vector<ParameterScaling> pscale;
/**
* @brief Parameter indices w.r.t. which to compute sensitivities
*/
std::vector<int> plist;
/** starting time */
realtype tstart_ {0.0};
/**
* @brief Duration of pre-simulation.
*
* If this is > 0, presimulation will be performed from
* (model->t0 - t_presim) to model->t0 using the fixedParameters in
* fixedParametersPresimulation
*/
realtype t_presim {0.0};
/**
* @brief Timepoints for which model state/outputs/... are requested
*
* Vector of timepoints.
*/
std::vector<realtype> ts_;
/**
* @brief Flag indicating whether reinitialization of states depending on
* fixed parameters is activated
*/
bool reinitializeFixedParameterInitialStates {false};
/**
* @brief Indices of states to be reinitialized based on provided
* presimulation constants / fixed parameters.
*/
std::vector<int> reinitialization_state_idxs_presim;
/**
* @brief Indices of states to be reinitialized based on provided
* constants / fixed parameters.
*/
std::vector<int> reinitialization_state_idxs_sim;
};
bool operator==(const SimulationParameters &a, const SimulationParameters &b);
} // namespace amici
#endif // AMICI_SIMULATION_PARAMETERS_H
|
jvanhoefer/AMICI
|
models/model_jakstat_adjoint_o2/model_jakstat_adjoint_o2.h
|
<filename>models/model_jakstat_adjoint_o2/model_jakstat_adjoint_o2.h
#ifndef _amici_model_jakstat_adjoint_o2_h
#define _amici_model_jakstat_adjoint_o2_h
/* Generated by amiwrap (R2017b) 2bd39716102b9842354964196889d40d2eb2731c */
#include <cmath>
#include <memory>
#include "amici/defines.h"
#include <sunmatrix/sunmatrix_sparse.h> //SUNMatrixContent_Sparse definition
#include "amici/solver_cvodes.h"
#include "amici/model_ode.h"
namespace amici {
class Solver;
namespace model_model_jakstat_adjoint_o2{
extern void JSparse_model_jakstat_adjoint_o2(SUNMatrixContent_Sparse JSparse, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *dwdx);
extern void Jy_model_jakstat_adjoint_o2(double *nllh, const int iy, const realtype *p, const realtype *k, const double *y, const double *sigmay, const double *my);
extern void dJydsigma_model_jakstat_adjoint_o2(double *dJydsigma, const int iy, const realtype *p, const realtype *k, const double *y, const double *sigmay, const double *my);
extern void dJydy_model_jakstat_adjoint_o2(double *dJydy, const int iy, const realtype *p, const realtype *k, const double *y, const double *sigmay, const double *my);
extern void dsigmaydp_model_jakstat_adjoint_o2(double *dsigmaydp, const realtype t, const realtype *p, const realtype *k, const int ip);
extern void dwdp_model_jakstat_adjoint_o2(realtype *dwdp, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *tcl, const realtype *stcl);
extern void dwdx_model_jakstat_adjoint_o2(realtype *dwdx, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *tcl);
extern void dxdotdp_model_jakstat_adjoint_o2(realtype *dxdotdp, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip, const realtype *w, const realtype *dwdp);
extern void dydp_model_jakstat_adjoint_o2(double *dydp, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip, const realtype *w, const realtype *dwdp);
extern void dydx_model_jakstat_adjoint_o2(double *dydx, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *dwdx);
extern void sigmay_model_jakstat_adjoint_o2(double *sigmay, const realtype t, const realtype *p, const realtype *k);
extern void sx0_model_jakstat_adjoint_o2(realtype *sx0, const realtype t,const realtype *x0, const realtype *p, const realtype *k, const int ip);
extern void w_model_jakstat_adjoint_o2(realtype *w, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *tcl);
extern void x0_model_jakstat_adjoint_o2(realtype *x0, const realtype t, const realtype *p, const realtype *k);
extern void xdot_model_jakstat_adjoint_o2(realtype *xdot, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w);
extern void y_model_jakstat_adjoint_o2(double *y, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w);
class Model_model_jakstat_adjoint_o2 : public amici::Model_ODE {
public:
Model_model_jakstat_adjoint_o2()
: amici::Model_ODE(
amici::ModelDimensions(
162,
9,
162,
9,
0,
17,
2,
54,
3,
0,
0,
0,
18,
10,
2,
30,
0,
0,
{},
384,
8,
154
),
amici::SimulationParameters(
std::vector<realtype>(2, 1.0),
std::vector<realtype>(17, 1.0)
),
amici::SecondOrderMode::full,
std::vector<realtype>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
std::vector<int>{})
{};
amici::Model* clone() const override { return new Model_model_jakstat_adjoint_o2(*this); };
std::string getAmiciCommit() const override { return "2bd39716102b9842354964196889d40d2eb2731c"; };
void fJSparse(SUNMatrixContent_Sparse JSparse, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *dwdx) override {
JSparse_model_jakstat_adjoint_o2(JSparse, t, x, p, k, h, w, dwdx);
}
void fJrz(double *nllh, const int iz, const realtype *p, const realtype *k, const double *rz, const double *sigmaz) override {
}
void fJy(double *nllh, const int iy, const realtype *p, const realtype *k, const double *y, const double *sigmay, const double *my) override {
Jy_model_jakstat_adjoint_o2(nllh, iy, p, k, y, sigmay, my);
}
void fJz(double *nllh, const int iz, const realtype *p, const realtype *k, const double *z, const double *sigmaz, const double *mz) override {
}
void fdJrzdsigma(double *dJrzdsigma, const int iz, const realtype *p, const realtype *k, const double *rz, const double *sigmaz) override {
}
void fdJrzdz(double *dJrzdz, const int iz, const realtype *p, const realtype *k, const double *rz, const double *sigmaz) override {
}
void fdJydsigma(double *dJydsigma, const int iy, const realtype *p, const realtype *k, const double *y, const double *sigmay, const double *my) override {
dJydsigma_model_jakstat_adjoint_o2(dJydsigma, iy, p, k, y, sigmay, my);
}
void fdJydy(double *dJydy, const int iy, const realtype *p, const realtype *k, const double *y, const double *sigmay, const double *my) override {
dJydy_model_jakstat_adjoint_o2(dJydy, iy, p, k, y, sigmay, my);
}
void fdJzdsigma(double *dJzdsigma, const int iz, const realtype *p, const realtype *k, const double *z, const double *sigmaz, const double *mz) override {
}
void fdJzdz(double *dJzdz, const int iz, const realtype *p, const realtype *k, const double *z, const double *sigmaz, const double *mz) override {
}
void fdeltaqB(double *deltaqB, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip, const int ie, const realtype *xdot, const realtype *xdot_old, const realtype *xB) override {
}
void fdeltasx(double *deltasx, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const int ip, const int ie, const realtype *xdot, const realtype *xdot_old, const realtype *sx, const realtype *stau) override {
}
void fdeltax(double *deltax, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ie, const realtype *xdot, const realtype *xdot_old) override {
}
void fdeltaxB(double *deltaxB, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ie, const realtype *xdot, const realtype *xdot_old, const realtype *xB) override {
}
void fdrzdp(double *drzdp, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip) override {
}
void fdrzdx(double *drzdx, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h) override {
}
void fdsigmaydp(double *dsigmaydp, const realtype t, const realtype *p, const realtype *k, const int ip) override {
dsigmaydp_model_jakstat_adjoint_o2(dsigmaydp, t, p, k, ip);
}
void fdsigmazdp(double *dsigmazdp, const realtype t, const realtype *p, const realtype *k, const int ip) override {
}
void fdwdp(realtype *dwdp, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *tcl, const realtype *stcl) override {
dwdp_model_jakstat_adjoint_o2(dwdp, t, x, p, k, h, w, tcl, stcl);
}
void fdwdx(realtype *dwdx, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *tcl) override {
dwdx_model_jakstat_adjoint_o2(dwdx, t, x, p, k, h, w, tcl);
}
void fdxdotdp(realtype *dxdotdp, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip, const realtype *w, const realtype *dwdp) override {
dxdotdp_model_jakstat_adjoint_o2(dxdotdp, t, x, p, k, h, ip, w, dwdp);
}
void fdydp(double *dydp, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip, const realtype *w, const realtype *dwdp) override {
dydp_model_jakstat_adjoint_o2(dydp, t, x, p, k, h, ip, w, dwdp);
}
void fdydx(double *dydx, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *dwdx) override {
dydx_model_jakstat_adjoint_o2(dydx, t, x, p, k, h, w, dwdx);
}
void fdzdp(double *dzdp, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip) override {
}
void fdzdx(double *dzdx, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h) override {
}
void froot(realtype *root, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h) override {
}
void frz(double *rz, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h) override {
}
void fsigmay(double *sigmay, const realtype t, const realtype *p, const realtype *k) override {
sigmay_model_jakstat_adjoint_o2(sigmay, t, p, k);
}
void fsigmaz(double *sigmaz, const realtype t, const realtype *p, const realtype *k) override {
}
void fsrz(double *srz, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *sx, const int ip) override {
}
void fstau(double *stau, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *sx, const int ip, const int ie) override {
}
void fsx0(realtype *sx0, const realtype t,const realtype *x0, const realtype *p, const realtype *k, const int ip) override {
sx0_model_jakstat_adjoint_o2(sx0, t, x0, p, k, ip);
}
void fsz(double *sz, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *sx, const int ip) override {
}
void fw(realtype *w, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *tcl) override {
w_model_jakstat_adjoint_o2(w, t, x, p, k, h, tcl);
}
void fx0(realtype *x0, const realtype t, const realtype *p, const realtype *k) override {
x0_model_jakstat_adjoint_o2(x0, t, p, k);
}
void fxdot(realtype *xdot, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w) override {
xdot_model_jakstat_adjoint_o2(xdot, t, x, p, k, h, w);
}
void fy(double *y, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w) override {
y_model_jakstat_adjoint_o2(y, t, x, p, k, h, w);
}
void fz(double *z, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h) override {
}
};
} // namespace model_model_jakstat_adjoint_o2
} // namespace amici
#endif /* _amici_model_jakstat_adjoint_o2_h */
|
jvanhoefer/AMICI
|
tests/cpputest/testfunctions.h
|
<reponame>jvanhoefer/AMICI<filename>tests/cpputest/testfunctions.h
#ifndef TESTFUNCTIONS_H
#define TESTFUNCTIONS_H
#include <amici/amici.h>
#include <amici/hdf5.h>
#include <H5Cpp.h>
#ifndef __APPLE__
#include <iostream>
#endif
#include <sstream> // make std::ostringstream available (needs to come before TestHarness.h)
#include <string>
#include <CppUTest/TestHarness.h>
#include <CppUTestExt/MockSupport.h>
namespace amici {
class ReturnData;
class ExpData;
#if !defined(NEW_OPTION_FILE) || !defined(HDFFILE) || !defined(HDFFILEWRITE)
#error "Must define NEW_OPTION_FILE HDFFILE HDFFILEWRITE"
#endif
#define TEST_ATOL 1e-10
#define TEST_RTOL 1e-05
/**
* @brief helper function to initialize default names/ids
* @param name name of variables
* @param length number of variables
* @return default names/ids
*/
std::vector<std::string>
getVariableNames(const char* name, int length);
/**
* @brief The Model_Test class is a model-unspecific implementation
of model designed for unit testing.
*/
class Model_Test : public Model
{
public:
/** constructor with model dimensions
* @param model_dimensions ModelDimensions model_dimensions,
* @param o2mode second order sensitivity mode
* @param simulation_parameters Simulation parameters
* @param idlist indexes indicating algebraic components (DAE only)
* @param z2event mapping of event outputs to events
*/
Model_Test(ModelDimensions const& model_dimensions,
SimulationParameters simulation_parameters,
const SecondOrderMode o2mode,
const std::vector<realtype> idlist,
const std::vector<int> z2event)
: Model(model_dimensions,
simulation_parameters,
o2mode,
idlist,
z2event)
{}
/** default constructor */
Model_Test()
: Model(
ModelDimensions(),
SimulationParameters(),
SecondOrderMode::none,
std::vector<realtype>(),
std::vector<int>())
{}
Model *clone() const override { return new Model_Test(*this); }
std::unique_ptr<Solver> getSolver() override {
throw AmiException("not implemented");
}
void froot(const realtype /*t*/, const AmiVector & /*x*/,
const AmiVector & /*dx*/,
gsl::span<realtype> /*root*/) override {
throw AmiException("not implemented");
}
void fxdot(const realtype /*t*/, const AmiVector & /*x*/,
const AmiVector & /*dx*/, AmiVector & /*xdot*/) override {
throw AmiException("not implemented");
}
void fsxdot(const realtype /*t*/, const AmiVector & /*x*/,
const AmiVector & /*dx*/, const int /*ip*/,
const AmiVector & /*sx*/, const AmiVector & /*sdx*/,
AmiVector & /*sxdot*/) override {
throw AmiException("not implemented");
}
void fJ(const realtype /*t*/, const realtype /*cj*/,
const AmiVector & /*x*/, const AmiVector & /*dx*/,
const AmiVector & /*xdot*/, SUNMatrix /*J*/) override {
throw AmiException("not implemented");
}
void fJSparse(const realtype /*t*/, const realtype /*cj*/,
const AmiVector & /*x*/, const AmiVector & /*dx*/,
const AmiVector & /*xdot*/, SUNMatrix /*J*/) override {
throw AmiException("not implemented");
}
void fJB(const realtype /*t*/, realtype /*cj*/, const AmiVector & /*x*/,
const AmiVector & /*dx*/, const AmiVector & /*xB*/,
const AmiVector & /*dxB*/, const AmiVector & /*xBdot*/,
SUNMatrix /*JB*/) override {
throw AmiException("not implemented");
}
void fJSparseB(const realtype /*t*/, realtype /*cj*/,
const AmiVector & /*x*/, const AmiVector & /*dx*/,
const AmiVector & /*xB*/, const AmiVector & /*dxB*/,
const AmiVector & /*xBdot*/, SUNMatrix /*JB*/) override {
throw AmiException("not implemented");
}
void fJDiag(const realtype /*t*/, AmiVector & /*Jdiag*/,
const realtype /*cj*/, const AmiVector & /*x*/,
const AmiVector & /*dx*/) override {
throw AmiException("not implemented");
}
void fdxdotdp(const realtype /*t*/, const AmiVector & /*x*/,
const AmiVector & /*dx*/) override {
throw AmiException("not implemented");
}
void fJv(const realtype /*t*/, const AmiVector & /*x*/,
const AmiVector & /*dx*/, const AmiVector & /*xdot*/,
const AmiVector & /*v*/, AmiVector & /*nJv*/,
const realtype /*cj*/) override {
throw AmiException("not implemented");
}
void fxBdot_ss(const realtype /*t*/, const AmiVector & /*xB*/,
const AmiVector & /*dxB*/, AmiVector & /*xBdot*/
) override {
throw AmiException("not implemented");
}
void fJSparseB_ss(SUNMatrix /*JB*/) override {
throw AmiException("not implemented");
}
void writeSteadystateJB(const realtype /*t*/, realtype /*cj*/,
const AmiVector & /*x*/, const AmiVector & /*dx*/,
const AmiVector & /*xB*/, const AmiVector & /*dxB*/,
const AmiVector & /*xBdot*/) override {
throw AmiException("not implemented");
}
std::vector<std::string> getParameterNames() const override {
return getVariableNames("p", np());
}
std::vector<std::string> getStateNames() const override {
return getVariableNames("x", nx_rdata);
}
std::vector<std::string> getFixedParameterNames() const override {
return getVariableNames("k", nk());
}
std::vector<std::string> getObservableNames() const override {
return getVariableNames("y", ny);
}
std::vector<std::string> getParameterIds() const override {
return getVariableNames("p", np());
}
std::vector<std::string> getStateIds() const override {
return getVariableNames("x", nx_rdata);
}
std::vector<std::string> getFixedParameterIds() const override {
return getVariableNames("k", nk());
}
std::vector<std::string> getObservableIds() const override {
return getVariableNames("y", ny);
}
};
void simulateWithDefaultOptions();
void simulateVerifyWrite(const std::string &path);
void simulateVerifyWrite(std::string const &path, double atol, double rtol);
void simulateVerifyWrite(const std::string &hdffileOptions,
const std::string &hdffileResults,
const std::string &hdffilewrite,
const std::string &path, double atol, double rtol);
std::unique_ptr<ExpData> getTestExpData(const Model &model);
bool withinTolerance(double expected, double actual, double atol, double rtol,
int index, const char *name);
void checkEqualArray(const double *expected, const double *actual, int length,
double atol, double rtol, const char *name);
void checkEqualArray(std::vector<double> const &expected,
std::vector<double> const &actual, double atol,
double rtol, std::string const &name);
// TODO: delete after transitioning to C++-written test results
void verifyReturnDataMatlab(const std::string &hdffile,
const std::string &resultPath,
const ReturnData *rdata, const Model *model,
double atol, double rtol);
// TODO: delete after transitioning to C++-written test results
void verifyReturnDataSensitivitiesMatlab(const H5::H5File &file_id,
const std::string &resultPath,
const ReturnData *rdata,
const Model *model, double atol,
double rtol);
void verifyReturnData(const std::string &hdffile, const std::string &resultPath,
const ReturnData *rdata, const Model *model, double atol,
double rtol);
void verifyReturnDataSensitivities(const H5::H5File &file_id,
const std::string &resultPath,
const ReturnData *rdata, const Model *model,
double atol, double rtol);
void printBacktrace(int depth);
} // namespace amici
#endif
|
jvanhoefer/AMICI
|
models/model_events/model_events.h
|
<reponame>jvanhoefer/AMICI<gh_stars>10-100
#ifndef _amici_model_events_h
#define _amici_model_events_h
/* Generated by amiwrap (R2017b) 2bd39716102b9842354964196889d40d2eb2731c */
#include <cmath>
#include <memory>
#include "amici/defines.h"
#include <sunmatrix/sunmatrix_sparse.h> //SUNMatrixContent_Sparse definition
#include "amici/solver_cvodes.h"
#include "amici/model_ode.h"
namespace amici {
class Solver;
namespace model_model_events{
extern void JSparse_model_events(SUNMatrixContent_Sparse JSparse, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *dwdx);
extern void Jrz_model_events(double *nllh, const int iz, const realtype *p, const realtype *k, const double *rz, const double *sigmaz);
extern void Jy_model_events(double *nllh, const int iy, const realtype *p, const realtype *k, const double *y, const double *sigmay, const double *my);
extern void Jz_model_events(double *nllh, const int iz, const realtype *p, const realtype *k, const double *z, const double *sigmaz, const double *mz);
extern void dJrzdsigma_model_events(double *dJrzdsigma, const int iz, const realtype *p, const realtype *k, const double *rz, const double *sigmaz);
extern void dJrzdz_model_events(double *dJrzdz, const int iz, const realtype *p, const realtype *k, const double *rz, const double *sigmaz);
extern void dJydsigma_model_events(double *dJydsigma, const int iy, const realtype *p, const realtype *k, const double *y, const double *sigmay, const double *my);
extern void dJydy_model_events(double *dJydy, const int iy, const realtype *p, const realtype *k, const double *y, const double *sigmay, const double *my);
extern void dJzdsigma_model_events(double *dJzdsigma, const int iz, const realtype *p, const realtype *k, const double *z, const double *sigmaz, const double *mz);
extern void dJzdz_model_events(double *dJzdz, const int iz, const realtype *p, const realtype *k, const double *z, const double *sigmaz, const double *mz);
extern void deltasx_model_events(double *deltasx, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const int ip, const int ie, const realtype *xdot, const realtype *xdot_old, const realtype *sx, const realtype *stau);
extern void drzdx_model_events(double *drzdx, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h);
extern void dxdotdp_model_events(realtype *dxdotdp, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip, const realtype *w, const realtype *dwdp);
extern void dydp_model_events(double *dydp, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip, const realtype *w, const realtype *dwdp);
extern void dydx_model_events(double *dydx, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *dwdx);
extern void dzdx_model_events(double *dzdx, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h);
extern void root_model_events(realtype *root, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h);
extern void rz_model_events(double *rz, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h);
extern void sigmay_model_events(double *sigmay, const realtype t, const realtype *p, const realtype *k);
extern void sigmaz_model_events(double *sigmaz, const realtype t, const realtype *p, const realtype *k);
extern void srz_model_events(double *srz, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *sx, const int ip);
extern void stau_model_events(double *stau, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *sx, const int ip, const int ie);
extern void sz_model_events(double *sz, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *sx, const int ip);
extern void x0_model_events(realtype *x0, const realtype t, const realtype *p, const realtype *k);
extern void xdot_model_events(realtype *xdot, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w);
extern void y_model_events(double *y, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w);
extern void z_model_events(double *z, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h);
class Model_model_events : public amici::Model_ODE {
public:
Model_model_events()
: amici::Model_ODE(
amici::ModelDimensions(
3,
3,
3,
3,
0,
4,
4,
1,
1,
2,
2,
6,
1,
0,
0,
0,
0,
0,
{},
4,
0,
1
),
amici::SimulationParameters(
std::vector<realtype>(4, 1.0),
std::vector<realtype>(4, 1.0)
),
amici::SecondOrderMode::none,
std::vector<realtype>{0, 0, 0},
std::vector<int>{1, 2})
{};
amici::Model* clone() const override { return new Model_model_events(*this); };
std::string getAmiciCommit() const override { return "2bd39716102b9842354964196889d40d2eb2731c"; };
void fJSparse(SUNMatrixContent_Sparse JSparse, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *dwdx) override {
JSparse_model_events(JSparse, t, x, p, k, h, w, dwdx);
}
void fJrz(double *nllh, const int iz, const realtype *p, const realtype *k, const double *rz, const double *sigmaz) override {
Jrz_model_events(nllh, iz, p, k, rz, sigmaz);
}
void fJy(double *nllh, const int iy, const realtype *p, const realtype *k, const double *y, const double *sigmay, const double *my) override {
Jy_model_events(nllh, iy, p, k, y, sigmay, my);
}
void fJz(double *nllh, const int iz, const realtype *p, const realtype *k, const double *z, const double *sigmaz, const double *mz) override {
Jz_model_events(nllh, iz, p, k, z, sigmaz, mz);
}
void fdJrzdsigma(double *dJrzdsigma, const int iz, const realtype *p, const realtype *k, const double *rz, const double *sigmaz) override {
dJrzdsigma_model_events(dJrzdsigma, iz, p, k, rz, sigmaz);
}
void fdJrzdz(double *dJrzdz, const int iz, const realtype *p, const realtype *k, const double *rz, const double *sigmaz) override {
dJrzdz_model_events(dJrzdz, iz, p, k, rz, sigmaz);
}
void fdJydsigma(double *dJydsigma, const int iy, const realtype *p, const realtype *k, const double *y, const double *sigmay, const double *my) override {
dJydsigma_model_events(dJydsigma, iy, p, k, y, sigmay, my);
}
void fdJydy(double *dJydy, const int iy, const realtype *p, const realtype *k, const double *y, const double *sigmay, const double *my) override {
dJydy_model_events(dJydy, iy, p, k, y, sigmay, my);
}
void fdJzdsigma(double *dJzdsigma, const int iz, const realtype *p, const realtype *k, const double *z, const double *sigmaz, const double *mz) override {
dJzdsigma_model_events(dJzdsigma, iz, p, k, z, sigmaz, mz);
}
void fdJzdz(double *dJzdz, const int iz, const realtype *p, const realtype *k, const double *z, const double *sigmaz, const double *mz) override {
dJzdz_model_events(dJzdz, iz, p, k, z, sigmaz, mz);
}
void fdeltaqB(double *deltaqB, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip, const int ie, const realtype *xdot, const realtype *xdot_old, const realtype *xB) override {
}
void fdeltasx(double *deltasx, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const int ip, const int ie, const realtype *xdot, const realtype *xdot_old, const realtype *sx, const realtype *stau) override {
deltasx_model_events(deltasx, t, x, p, k, h, w, ip, ie, xdot, xdot_old, sx, stau);
}
void fdeltax(double *deltax, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ie, const realtype *xdot, const realtype *xdot_old) override {
}
void fdeltaxB(double *deltaxB, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ie, const realtype *xdot, const realtype *xdot_old, const realtype *xB) override {
}
void fdrzdp(double *drzdp, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip) override {
}
void fdrzdx(double *drzdx, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h) override {
drzdx_model_events(drzdx, ie, t, x, p, k, h);
}
void fdsigmaydp(double *dsigmaydp, const realtype t, const realtype *p, const realtype *k, const int ip) override {
}
void fdsigmazdp(double *dsigmazdp, const realtype t, const realtype *p, const realtype *k, const int ip) override {
}
void fdwdp(realtype *dwdp, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *tcl, const realtype *stcl) override {
}
void fdwdx(realtype *dwdx, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *tcl) override {
}
void fdxdotdp(realtype *dxdotdp, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip, const realtype *w, const realtype *dwdp) override {
dxdotdp_model_events(dxdotdp, t, x, p, k, h, ip, w, dwdp);
}
void fdydp(double *dydp, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip, const realtype *w, const realtype *dwdp) override {
dydp_model_events(dydp, t, x, p, k, h, ip, w, dwdp);
}
void fdydx(double *dydx, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *dwdx) override {
dydx_model_events(dydx, t, x, p, k, h, w, dwdx);
}
void fdzdp(double *dzdp, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip) override {
}
void fdzdx(double *dzdx, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h) override {
dzdx_model_events(dzdx, ie, t, x, p, k, h);
}
void froot(realtype *root, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h) override {
root_model_events(root, t, x, p, k, h);
}
void frz(double *rz, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h) override {
rz_model_events(rz, ie, t, x, p, k, h);
}
void fsigmay(double *sigmay, const realtype t, const realtype *p, const realtype *k) override {
sigmay_model_events(sigmay, t, p, k);
}
void fsigmaz(double *sigmaz, const realtype t, const realtype *p, const realtype *k) override {
sigmaz_model_events(sigmaz, t, p, k);
}
void fsrz(double *srz, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *sx, const int ip) override {
srz_model_events(srz, ie, t, x, p, k, h, sx, ip);
}
void fstau(double *stau, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *sx, const int ip, const int ie) override {
stau_model_events(stau, t, x, p, k, h, sx, ip, ie);
}
void fsx0(realtype *sx0, const realtype t,const realtype *x0, const realtype *p, const realtype *k, const int ip) override {
}
void fsz(double *sz, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *sx, const int ip) override {
sz_model_events(sz, ie, t, x, p, k, h, sx, ip);
}
void fw(realtype *w, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *tcl) override {
}
void fx0(realtype *x0, const realtype t, const realtype *p, const realtype *k) override {
x0_model_events(x0, t, p, k);
}
void fxdot(realtype *xdot, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w) override {
xdot_model_events(xdot, t, x, p, k, h, w);
}
void fy(double *y, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w) override {
y_model_events(y, t, x, p, k, h, w);
}
void fz(double *z, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h) override {
z_model_events(z, ie, t, x, p, k, h);
}
};
} // namespace model_model_events
} // namespace amici
#endif /* _amici_model_events_h */
|
jvanhoefer/AMICI
|
include/amici/exception.h
|
<reponame>jvanhoefer/AMICI
#ifndef amici_exception_h
#define amici_exception_h
#include "amici/defines.h" // necessary for realtype
#include <exception>
#include <array>
namespace amici {
/**
* @brief AMICI exception class
*
* Has a printf style interface to allow easy generation of error messages
*/
class AmiException : public std::exception {
public:
/**
* @brief Constructor with printf style interface
* @param fmt error message with printf format
* @param ... printf formatting variables
*/
explicit AmiException(char const* fmt, ...);
/**
* @brief Override of default error message function
* @return msg error message
*/
const char* what() const noexcept override;
/**
* @brief Returns the stored backtrace
* @return trace backtrace
*/
const char *getBacktrace() const;
/**
* @brief Stores the current backtrace
* @param nMaxFrames number of frames to go back in stacktrace
*/
void storeBacktrace(int nMaxFrames);
private:
std::array<char, 500> msg_;
std::array<char, 500> trace_;
};
/**
* @brief cvode exception handler class
*/
class CvodeException : public AmiException {
public:
/**
* @brief Constructor
* @param error_code error code returned by cvode function
* @param function cvode function name
*/
CvodeException(int error_code, const char *function);
};
/**
* @brief ida exception handler class
*/
class IDAException : public AmiException {
public:
/**
* @brief Constructor
* @param error_code error code returned by ida function
* @param function ida function name
*/
IDAException(int error_code, const char *function);
};
/**
* @brief Integration failure exception for the forward problem
*
* This exception should be thrown when an integration failure occurred
* for this exception we can assume that we can recover from the exception
* and return a solution struct to the user
*/
class IntegrationFailure : public AmiException {
public:
/**
* @brief Constructor
* @param code error code returned by cvode/ida
* @param t time of integration failure
*/
IntegrationFailure(int code, realtype t);
/** error code returned by cvodes/idas */
int error_code;
/** time of integration failure */
realtype time;
};
/**
* @brief Integration failure exception for the backward problem
*
* This exception should be thrown when an integration failure occurred
* for this exception we can assume that we can recover from the exception
* and return a solution struct to the user
*/
class IntegrationFailureB : public AmiException {
public:
/**
* @brief Constructor
* @param code error code returned by cvode/ida
* @param t time of integration failure
*/
IntegrationFailureB(int code, realtype t);
/** error code returned by cvode/ida */
int error_code;
/** time of integration failure */
realtype time;
};
/**
* @brief Setup failure exception
*
* This exception should be thrown when the solver setup failed
* for this exception we can assume that we cannot recover from the exception
* and an error will be thrown
*/
class SetupFailure : public AmiException {
public:
using AmiException::AmiException;
};
/**
* @brief Newton failure exception
*
* This exception should be thrown when the steady state computation
* failed to converge for this exception we can assume that we can
* recover from the exception and return a solution struct to the user
*/
class NewtonFailure : public AmiException {
public:
/**
* @brief Constructor, simply calls AmiException constructor
* @param function name of the function in which the error occurred
* @param code error code
*/
NewtonFailure(int code, const char *function);
/** error code returned by solver */
int error_code;
};
} // namespace amici
#endif /* amici_exception_h */
|
jvanhoefer/AMICI
|
src/model_header.ODE_template.h
|
<gh_stars>0
#ifndef _amici_TPL_MODELNAME_h
#define _amici_TPL_MODELNAME_h
#include <cmath>
#include <memory>
#include <gsl/gsl-lite.hpp>
#include "amici/model_ode.h"
#include "amici/solver_cvodes.h"
#include "sundials/sundials_types.h"
namespace amici {
class Solver;
namespace model_TPL_MODELNAME {
extern std::array<const char*, TPL_NP> parameterNames;
extern std::array<const char*, TPL_NK> fixedParameterNames;
extern std::array<const char*, TPL_NX_RDATA> stateNames;
extern std::array<const char*, TPL_NY> observableNames;
extern std::array<const char*, TPL_NW> expressionNames;
extern std::array<const char*, TPL_NP> parameterIds;
extern std::array<const char*, TPL_NK> fixedParameterIds;
extern std::array<const char*, TPL_NX_RDATA> stateIds;
extern std::array<const char*, TPL_NY> observableIds;
extern std::array<const char*, TPL_NW> expressionIds;
TPL_JY_DEF
TPL_DJYDSIGMA_DEF
TPL_DJYDY_DEF
TPL_DJYDY_COLPTRS_DEF
TPL_DJYDY_ROWVALS_DEF
TPL_ROOT_DEF
TPL_DWDP_DEF
TPL_DWDP_COLPTRS_DEF
TPL_DWDP_ROWVALS_DEF
TPL_DWDX_DEF
TPL_DWDX_COLPTRS_DEF
TPL_DWDX_ROWVALS_DEF
TPL_DWDW_DEF
TPL_DWDW_COLPTRS_DEF
TPL_DWDW_ROWVALS_DEF
TPL_DXDOTDW_DEF
TPL_DXDOTDW_COLPTRS_DEF
TPL_DXDOTDW_ROWVALS_DEF
TPL_DXDOTDP_EXPLICIT_DEF
TPL_DXDOTDP_EXPLICIT_COLPTRS_DEF
TPL_DXDOTDP_EXPLICIT_ROWVALS_DEF
TPL_DXDOTDX_EXPLICIT_DEF
TPL_DXDOTDX_EXPLICIT_COLPTRS_DEF
TPL_DXDOTDX_EXPLICIT_ROWVALS_DEF
TPL_DYDX_DEF
TPL_DYDP_DEF
TPL_SIGMAY_DEF
TPL_DSIGMAYDP_DEF
TPL_W_DEF
TPL_X0_DEF
TPL_X0_FIXEDPARAMETERS_DEF
TPL_SX0_DEF
TPL_SX0_FIXEDPARAMETERS_DEF
TPL_XDOT_DEF
TPL_Y_DEF
TPL_STAU_DEF
TPL_DELTAX_DEF
TPL_DELTASX_DEF
TPL_X_RDATA_DEF
TPL_X_SOLVER_DEF
TPL_TOTAL_CL_DEF
/**
* @brief AMICI-generated model subclass.
*/
class Model_TPL_MODELNAME : public amici::Model_ODE {
public:
/**
* @brief Default constructor.
*/
Model_TPL_MODELNAME()
: amici::Model_ODE(
amici::ModelDimensions(
TPL_NX_RDATA, // nx_rdata
TPL_NXTRUE_RDATA, // nxtrue_rdata
TPL_NX_SOLVER, // nx_solver
TPL_NXTRUE_SOLVER, // nxtrue_solver
TPL_NX_SOLVER_REINIT, // nx_solver_reinit
TPL_NP, // np
TPL_NK, // nk
TPL_NY, // ny
TPL_NYTRUE, // nytrue
TPL_NZ, // nz
TPL_NZTRUE, // nztrue
TPL_NEVENT, // nevent
TPL_NOBJECTIVE, // nobjective
TPL_NW, // nw
TPL_NDWDX, // ndwdx
TPL_NDWDP, // ndwdp
TPL_NDWDW, // ndwdw
TPL_NDXDOTDW, // ndxdotdw
TPL_NDJYDY, // ndjydy
0, // nnz
TPL_UBW, // ubw
TPL_LBW // lbw
),
amici::SimulationParameters(
std::vector<realtype>{TPL_FIXED_PARAMETERS}, // fixedParameters
std::vector<realtype>{TPL_PARAMETERS} // dynamic parameters
),
TPL_O2MODE, // o2mode
std::vector<realtype>(TPL_NX_SOLVER, 0.0), // idlist
std::vector<int>{}, // z2event
true, // pythonGenerated
TPL_NDXDOTDP_EXPLICIT, // ndxdotdp_explicit
TPL_NDXDOTDX_EXPLICIT, // ndxdotdx_explicit
TPL_W_RECURSION_DEPTH // w_recursion_depth
) {}
/**
* @brief Clone this model instance.
* @return A deep copy of this instance.
*/
virtual amici::Model *clone() const override {
return new Model_TPL_MODELNAME(*this);
}
/** model specific implementation of fJrz
* @param nllh regularization for event measurements z
* @param iz event output index
* @param p parameter vector
* @param k constant vector
* @param z model event output at timepoint
* @param sigmaz event measurement standard deviation at timepoint
**/
virtual void fJrz(realtype *nllh, const int iz, const realtype *p,
const realtype *k, const realtype *rz,
const realtype *sigmaz) override {}
TPL_JY_IMPL
/** model specific implementation of fJz
* @param nllh negative log-likelihood for event measurements z
* @param iz event output index
* @param p parameter vector
* @param k constant vector
* @param z model event output at timepoint
* @param sigmaz event measurement standard deviation at timepoint
* @param mz event measurements at timepoint
**/
virtual void fJz(realtype *nllh, const int iz, const realtype *p,
const realtype *k, const realtype *z,
const realtype *sigmaz, const realtype *mz) override {}
/** model specific implementation of fdJrzdsigma
* @param dJrzdsigma Sensitivity of event penalization Jrz w.r.t.
* standard deviation sigmaz
* @param iz event output index
* @param p parameter vector
* @param k constant vector
* @param rz model root output at timepoint
* @param sigmaz event measurement standard deviation at timepoint
**/
virtual void fdJrzdsigma(realtype *dJrzdsigma, const int iz,
const realtype *p, const realtype *k,
const realtype *rz,
const realtype *sigmaz) override {}
/** model specific implementation of fdJrzdz
* @param dJrzdz partial derivative of event penalization Jrz
* @param iz event output index
* @param p parameter vector
* @param k constant vector
* @param rz model root output at timepoint
* @param sigmaz event measurement standard deviation at timepoint
**/
virtual void fdJrzdz(realtype *dJrzdz, const int iz, const realtype *p,
const realtype *k, const realtype *rz,
const realtype *sigmaz) override {}
TPL_DJYDSIGMA_IMPL
/** model specific implementation of fdJzdsigma
* @param dJzdsigma Sensitivity of event measurement
* negative log-likelihood Jz w.r.t. standard deviation sigmaz
* @param iz event output index
* @param p parameter vector
* @param k constant vector
* @param z model event output at timepoint
* @param sigmaz event measurement standard deviation at timepoint
* @param mz event measurement at timepoint
**/
virtual void fdJzdsigma(realtype *dJzdsigma, const int iz,
const realtype *p, const realtype *k,
const realtype *z, const realtype *sigmaz,
const realtype *mz) override {}
/** model specific implementation of fdJzdz
* @param dJzdz partial derivative of event measurement negative
*log-likelihood Jz
* @param iz event output index
* @param p parameter vector
* @param k constant vector
* @param z model event output at timepoint
* @param sigmaz event measurement standard deviation at timepoint
* @param mz event measurement at timepoint
**/
virtual void fdJzdz(realtype *dJzdz, const int iz, const realtype *p,
const realtype *k, const realtype *z,
const realtype *sigmaz, const realtype *mz) override {}
/** model specific implementation of fdeltasx
* @param deltaqB sensitivity update
* @param t current time
* @param x current state
* @param p parameter vector
* @param k constant vector
* @param h heaviside vector
* @param ip sensitivity index
* @param ie event index
* @param xdot new model right hand side
* @param xdot_old previous model right hand side
* @param xB adjoint state
**/
virtual void fdeltaqB(realtype *deltaqB, const realtype t,
const realtype *x, const realtype *p,
const realtype *k, const realtype *h, const int ip,
const int ie, const realtype *xdot,
const realtype *xdot_old,
const realtype *xB) override {}
TPL_DELTASX_IMPL
TPL_DELTAX_IMPL
/** model specific implementation of fdeltaxB
* @param deltaxB adjoint state update
* @param t current time
* @param x current state
* @param p parameter vector
* @param k constant vector
* @param h heaviside vector
* @param ie event index
* @param xdot new model right hand side
* @param xdot_old previous model right hand side
* @param xB current adjoint state
**/
virtual void fdeltaxB(realtype *deltaxB, const realtype t,
const realtype *x, const realtype *p,
const realtype *k, const realtype *h, const int ie,
const realtype *xdot, const realtype *xdot_old,
const realtype *xB) override {}
/** model specific implementation of fdrzdp
* @param drzdp partial derivative of root output rz w.r.t. model parameters
*p
* @param ie event index
* @param t current time
* @param x current state
* @param p parameter vector
* @param k constant vector
* @param h heaviside vector
* @param ip parameter index w.r.t. which the derivative is requested
**/
virtual void fdrzdp(realtype *drzdp, const int ie, const realtype t,
const realtype *x, const realtype *p, const realtype *k,
const realtype *h, const int ip) override {}
/** model specific implementation of fdrzdx
* @param drzdx partial derivative of root output rz w.r.t. model states x
* @param ie event index
* @param t current time
* @param x current state
* @param p parameter vector
* @param k constant vector
* @param h heaviside vector
**/
virtual void fdrzdx(realtype *drzdx, const int ie, const realtype t,
const realtype *x, const realtype *p, const realtype *k,
const realtype *h) override {}
TPL_DSIGMAYDP_IMPL
/** model specific implementation of fsigmaz
* @param dsigmazdp partial derivative of standard deviation of event
*measurements
* @param t current time
* @param p parameter vector
* @param k constant vector
* @param ip sensitivity index
**/
virtual void fdsigmazdp(realtype *dsigmazdp, const realtype t,
const realtype *p, const realtype *k,
const int ip) override {}
TPL_DJYDY_IMPL
TPL_DJYDY_COLPTRS_IMPL
TPL_DJYDY_ROWVALS_IMPL
TPL_DWDP_IMPL
TPL_DWDP_COLPTRS_IMPL
TPL_DWDP_ROWVALS_IMPL
TPL_DWDX_IMPL
TPL_DWDX_COLPTRS_IMPL
TPL_DWDX_ROWVALS_IMPL
TPL_DWDW_IMPL
TPL_DWDW_COLPTRS_IMPL
TPL_DWDW_ROWVALS_IMPL
TPL_DXDOTDW_IMPL
TPL_DXDOTDW_COLPTRS_IMPL
TPL_DXDOTDW_ROWVALS_IMPL
TPL_DXDOTDP_EXPLICIT_IMPL
TPL_DXDOTDP_EXPLICIT_COLPTRS_IMPL
TPL_DXDOTDP_EXPLICIT_ROWVALS_IMPL
TPL_DXDOTDX_EXPLICIT_IMPL
TPL_DXDOTDX_EXPLICIT_COLPTRS_IMPL
TPL_DXDOTDX_EXPLICIT_ROWVALS_IMPL
TPL_DYDX_IMPL
TPL_DYDP_IMPL
/** model specific implementation of fdzdp
* @param dzdp partial derivative of event-resolved output z w.r.t. model
*parameters p
* @param ie event index
* @param t current time
* @param x current state
* @param p parameter vector
* @param k constant vector
* @param h heaviside vector
* @param ip parameter index w.r.t. which the derivative is requested
**/
virtual void fdzdp(realtype *dzdp, const int ie, const realtype t,
const realtype *x, const realtype *p, const realtype *k,
const realtype *h, const int ip) override {}
/** model specific implementation of fdzdx
* @param dzdx partial derivative of event-resolved output z w.r.t. model
*states x
* @param ie event index
* @param t current time
* @param x current state
* @param p parameter vector
* @param k constant vector
* @param h heaviside vector
**/
virtual void fdzdx(realtype *dzdx, const int ie, const realtype t,
const realtype *x, const realtype *p, const realtype *k,
const realtype *h) override {}
TPL_ROOT_IMPL
/** model specific implementation of frz
* @param rz value of root function at current timepoint (non-output events
*not included)
* @param ie event index
* @param t current time
* @param x current state
* @param p parameter vector
* @param k constant vector
* @param h heaviside vector
**/
virtual void frz(realtype *rz, const int ie, const realtype t,
const realtype *x, const realtype *p, const realtype *k,
const realtype *h) override {}
TPL_SIGMAY_IMPL
/** model specific implementation of fsigmaz
* @param sigmaz standard deviation of event measurements
* @param t current time
* @param p parameter vector
* @param k constant vector
**/
virtual void fsigmaz(realtype *sigmaz, const realtype t, const realtype *p,
const realtype *k) override {}
/** model specific implementation of fsrz
* @param srz Sensitivity of rz, total derivative
* @param ie event index
* @param t current time
* @param x current state
* @param p parameter vector
* @param k constant vector
* @param sx current state sensitivity
* @param h heaviside vector
* @param ip sensitivity index
**/
virtual void fsrz(realtype *srz, const int ie, const realtype t,
const realtype *x, const realtype *p, const realtype *k,
const realtype *h, const realtype *sx,
const int ip) override {}
TPL_STAU_IMPL
TPL_SX0_IMPL
TPL_SX0_FIXEDPARAMETERS_IMPL
/** model specific implementation of fsz
* @param sz Sensitivity of rz, total derivative
* @param ie event index
* @param t current time
* @param x current state
* @param p parameter vector
* @param k constant vector
* @param h heaviside vector
* @param sx current state sensitivity
* @param ip sensitivity index
**/
virtual void fsz(realtype *sz, const int ie, const realtype t,
const realtype *x, const realtype *p, const realtype *k,
const realtype *h, const realtype *sx,
const int ip) override {}
TPL_W_IMPL
TPL_X0_IMPL
TPL_X0_FIXEDPARAMETERS_IMPL
TPL_XDOT_IMPL
TPL_Y_IMPL
/** model specific implementation of fz
* @param z value of event output
* @param ie event index
* @param t current time
* @param x current state
* @param p parameter vector
* @param k constant vector
* @param h heaviside vector
**/
virtual void fz(realtype *z, const int ie, const realtype t,
const realtype *x, const realtype *p, const realtype *k,
const realtype *h) override {}
TPL_X_RDATA_IMPL
TPL_X_SOLVER_IMPL
TPL_TOTAL_CL_IMPL
std::string getName() const override {
return "TPL_MODELNAME";
}
/**
* @brief Get names of the model parameters
* @return the names
*/
virtual std::vector<std::string> getParameterNames() const override {
return std::vector<std::string>(parameterNames.begin(),
parameterNames.end());
}
/**
* @brief Get names of the model states
* @return the names
*/
virtual std::vector<std::string> getStateNames() const override {
return std::vector<std::string>(stateNames.begin(), stateNames.end());
}
/**
* @brief Get names of the fixed model parameters
* @return the names
*/
virtual std::vector<std::string> getFixedParameterNames() const override {
return std::vector<std::string>(fixedParameterNames.begin(),
fixedParameterNames.end());
}
/**
* @brief Get names of the observables
* @return the names
*/
virtual std::vector<std::string> getObservableNames() const override {
return std::vector<std::string>(observableNames.begin(),
observableNames.end());
}
/**
* @brief Get names of model expressions
* @return Expression names
*/
virtual std::vector<std::string> getExpressionNames() const override {
return std::vector<std::string>(expressionNames.begin(),
expressionNames.end());
}
/**
* @brief Get ids of the model parameters
* @return the ids
*/
virtual std::vector<std::string> getParameterIds() const override {
return std::vector<std::string>(parameterIds.begin(),
parameterIds.end());
}
/**
* @brief Get ids of the model states
* @return the ids
*/
virtual std::vector<std::string> getStateIds() const override {
return std::vector<std::string>(stateIds.begin(), stateIds.end());
}
/**
* @brief Get ids of the fixed model parameters
* @return the ids
*/
virtual std::vector<std::string> getFixedParameterIds() const override {
return std::vector<std::string>(fixedParameterIds.begin(),
fixedParameterIds.end());
}
/**
* @brief Get ids of the observables
* @return the ids
*/
virtual std::vector<std::string> getObservableIds() const override {
return std::vector<std::string>(observableIds.begin(),
observableIds.end());
}
/**
* @brief Get IDs of model expressions
* @return Expression IDs
*/
virtual std::vector<std::string> getExpressionIds() const override {
return std::vector<std::string>(expressionIds.begin(),
expressionIds.end());
}
/**
* @brief function indicating whether reinitialization of states depending on
fixed parameters is permissible
* @return flag indicating whether reinitialization of states depending on
fixed parameters is permissible
*/
virtual bool isFixedParameterStateReinitializationAllowed() const override {
return TPL_REINIT_FIXPAR_INITCOND;
}
/**
* @brief returns the AMICI version that was used to generate the model
* @return AMICI version string
*/
virtual std::string getAmiciVersion() const override {
return "TPL_AMICI_VERSION_STRING";
}
/**
* @brief returns the amici version that was used to generate the model
* @return AMICI git commit hash
*/
virtual std::string getAmiciCommit() const override {
return "TPL_AMICI_COMMIT_STRING";
}
virtual bool hasQuadraticLLH() const override {
return TPL_QUADRATIC_LLH;
}
};
} // namespace model_TPL_MODELNAME
} // namespace amici
#endif /* _amici_TPL_MODELNAME_h */
|
JA7XJ/Examen2_JosephMoscoso_P3
|
Object.h
|
#ifndef OBJECT_H
#define OBJECT_H
#include <string>
using std::string;
class Object{
public:
virtual string toString()=0;
virtual bool equals(Object*)=0;
virtual ~Object();
};
#endif
|
JA7XJ/Examen2_JosephMoscoso_P3
|
Node.h
|
<reponame>JA7XJ/Examen2_JosephMoscoso_P3
#ifndef NODE_H
#define NODE_H
#include "Usuario.h"
class Node{
private:
Usuario* data;
Node* next;
public:
Node(Usuario*);
Node();
Usuario* getData();
void setData(Usuario*);
void setNext(Node*);
Node* getNext();
~Node();
};
#endif
|
JA7XJ/Examen2_JosephMoscoso_P3
|
ListaEnlace.h
|
<reponame>JA7XJ/Examen2_JosephMoscoso_P3
#ifndef LISTAENLACE_H
#define LISTAENLACE_H
#include "Node.h"
#include "Usuario.h"
class ListaEnlace{
private:
int size;
Node* inicio;
public:
ListaEnlace();
bool push(Usuario*);
Usuario* pop();
Usuario* top();
void print();
int getSize();
~ListaEnlace();
};
#endif
|
JA7XJ/Examen2_JosephMoscoso_P3
|
Usuario.h
|
<gh_stars>0
#ifndef USUARIO_H
#define USUARIO_H
#include <vector>
using std::vector;
#include <fstream>
using std::ifstream;
using std::ofstream;
#include <string>
using std::string;
class Usuario{
private:
string nombre;
int edad;
string password;
string genero;
vector<string> intereses;
vector<Usuario*> contactos;
public:
Usuario();
Usuario(string, int, string, string);
~Usuario();
string getNombre();
void setNombre(string);
int getEdad();
void setEdad(int);
string getPassword();
void setPassword(string);
string getGenero();
void setGenero(string);
void setIntereses(vector <string>);
vector<string> getIntereses();
void addIntereses(string);
void setContactos(vector <Usuario*>);
vector<Usuario*> getContactos();
void addContactos(Usuario*);
string toString();
void write(ofstream&);
void read(ifstream&);
};
#endif
|
onlyAngelia/YAAdapterTableViewWithResponderChain
|
ARTableViewExample/ARTableViewExample/ViewController.h
|
<reponame>onlyAngelia/YAAdapterTableViewWithResponderChain<filename>ARTableViewExample/ARTableViewExample/ViewController.h
//
// ViewController.h
// ARTableViewExample
//
// Created by lanjiying on 2018/6/4.
// Copyright © 2018年 lanjiying. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
|
onlyAngelia/YAAdapterTableViewWithResponderChain
|
ARTableViewExample/Pods/Headers/Public/ARTableView/UIResponder+Rout.h
|
<reponame>onlyAngelia/YAAdapterTableViewWithResponderChain
//
// UIResponder+Rout.h
// KcalOfDriver
//
// Created by 关门滢 on 2018/5/28.
// Copyright © 2018年 liang. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIResponder (Rout)
- (void)rountEvent:(NSString *)eventName userInfo:(NSDictionary *)userInfo;
- (NSInvocation *)createInvocationWithSeletor:(SEL)seletorname;
@end
|
onlyAngelia/YAAdapterTableViewWithResponderChain
|
ARTableViewExample/ARTableViewExample/YAWebViewController.h
|
<gh_stars>10-100
//
// YAWebViewController.h
// ARTableViewExample
//
// Created by lanjiying on 2018/6/4.
// Copyright © 2018年 lanjiying. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface YAWebViewController : UIViewController
+(instancetype)showWKWebViewController:(NSString *)url;
@end
|
onlyAngelia/YAAdapterTableViewWithResponderChain
|
ARTableViewExample/ARTableViewExample/YATableViewAdapter.h
|
//
// YATableViewAdapter.h
// ARTableViewExample
//
// Created by lanjiying on 2018/6/4.
// Copyright © 2018年 lanjiying. All rights reserved.
//
#import "UITableViewAdapter.h"
@interface YATableViewAdapter : UITableViewAdapter
@end
|
onlyAngelia/YAAdapterTableViewWithResponderChain
|
ARTableViewExample/Pods/Headers/Public/ARTableView/UITableViewAdapter.h
|
//
// UITableViewAdapter.h
// KcalOfDriver
//
// Created by 关门滢 on 2018/5/28.
// Copyright © 2018年 liang. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
static NSString *kCCellSeletedEventName = @"TableViewAdapterDidSeletedCellEvent";
static NSString *kCTableViewDidSrollEventName = @"TableViewAdapterDidSrollEvent";
@interface UITableViewAdapter : NSObject<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic, strong)NSMutableArray *sourceArray;//数据源
@property(nonatomic, strong)UITableView *tableView;//所用控件
+ (instancetype)instance;
- (void)appendSourceArray:(NSArray *)array;
- (void)setView:(UITableView*)tableView;
@end
|
onlyAngelia/YAAdapterTableViewWithResponderChain
|
ARTableViewExample/Pods/Headers/Private/ARTableView/UITableView+Adater.h
|
<reponame>onlyAngelia/YAAdapterTableViewWithResponderChain<gh_stars>10-100
//
// UITableView+Adater.h
// KcalOfDriver
//
// Created by 关门滢 on 2018/5/28.
// Copyright © 2018年 liang. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "UITableViewAdapter.h"
#import "UIResponder+Rout.h"
@interface UITableView (Adater)
- (void)setAdapter:(UITableViewAdapter *)adapter;//将TableView和Adapter关联起来
@end
|
revengsmK/exploader
|
src/exploader.c
|
<reponame>revengsmK/exploader
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include "memtools.h"
/**
* Memory loader that temporarily removes Windows 10 (32-bit) 'Activate Windows' watermark by
* modifying explorer.exe process.
*
* Tested on 32-bit versions of Windows 10 20H2 and Windows 10 21H1
*
***/
// Prototypes
void cleanup(HANDLE hThread, HANDLE hProcess);
void banner(void);
/* Banner generated at manytools.org */
void banner(void){
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
COORD coordScreen = { 0, 0 };
DWORD bytesWritten = 0;
DWORD size = 0;
GetConsoleScreenBufferInfo(hConsole, &consoleInfo);
size = consoleInfo.dwSize.X * consoleInfo.dwSize.Y;
SetConsoleTextAttribute(hConsole, 7);
puts("");
puts(" dP dP ");
puts(" 88 88 ");
puts(" .d8888b. dP. .dP 88d888b. 88 .d8888b. .d8888b. .d888b88 .d8888b. 88d888b. ");
puts(" 88ooood8 `8bd8' 88' `88 88 88' `88 88' `88 88' `88 88ooood8 88' `88 ");
puts(" 88. ... .d88b. 88. .88 88 88. .88 88. .88 88. .88 88. ... 88 ");
puts(" `88888P' dP' `dP 88Y888P' dP `88888P' `88888P8 `88888P8 `88888P' dP ");
puts(" 88 ");
puts(" dP\tCoded by: Aleksandar (github.com/revengsmK) ");
puts("\n");
FillConsoleOutputAttribute(hConsole,9,size,coordScreen,&bytesWritten);
}
void cleanup(HANDLE hThread, HANDLE hProcess){
ResumeThread(hThread);
CloseHandle(hThread);
CloseHandle(hProcess);
puts("Press any key to exit....");
getch();
}
int main(void){
DWORD baseAddr = 0;
DWORD endaddr = 0;
DWORD patAddr = 0;
DWORD patAddr2 = 0;
BOOL rVal;
BOOL rVal2;
STARTUPINFO startInfo;
PROCESS_INFORMATION procInfo;
IMAGE_DOS_HEADER DosHead;
IMAGE_NT_HEADERS hPE;
unsigned char patch_bytes[] = { 0x90, 0xE9 }; // nop, jmp [address]
unsigned char patch_bytes2[] = { 0x6A, 0x00, 0x90, 0x90, 0x90 }; // push 0 , nop, nop , nop
char explorerpath[MAX_PATH];
banner();
// Kill all existing explorer processes
puts("-> Killing all existing explorer.exe processes...\n");
KillProcessByName("explorer.exe");
GetStartupInfo(&startInfo);
// Get explorer.exe full path
GetWindowsDirectory(explorerpath,MAX_PATH);
strncat(explorerpath,"\\explorer.exe",sizeof(explorerpath) - strlen(explorerpath) - 1);
// Create new suspended explorer process
if(!CreateProcess(explorerpath,NULL,NULL,NULL,FALSE,CREATE_SUSPENDED,NULL,NULL,&startInfo,&procInfo))
{
puts("[!] Failed to create process!\nAborting...\n");
getch();
return -1;
}
// Get image base address
puts("-> Getting image base address...\n");
baseAddr = GetBaseAddress(procInfo.hProcess ,procInfo.hThread);
if(baseAddr == 0)
{
puts(" [!] Failed to get image base address! Aborting...\n");
cleanup(procInfo.hThread,procInfo.hProcess);
return -1;
}
printf("-> Base address: %X\t[ OK ]\n\n", (unsigned int)baseAddr);
// Read DOS and PE header
rVal = ReadProcessMemory(procInfo.hProcess,(char*)baseAddr,&DosHead,sizeof(IMAGE_DOS_HEADER),NULL);
rVal2 = ReadProcessMemory(procInfo.hProcess,(char*)baseAddr + DosHead.e_lfanew,&hPE,sizeof(IMAGE_NT_HEADERS),NULL);
if(rVal == 0 || rVal2 == 0)
{
puts("[!] Failed to get code section size. Aborting...\n");
cleanup(procInfo.hThread,procInfo.hProcess);
return -1;
}
// Get code section size
printf("-> Code section size: %X \n",(unsigned int)hPE.OptionalHeader.SizeOfCode);
endaddr = baseAddr + hPE.OptionalHeader.SizeOfCode;
// Search for hex pattern and return address
patAddr = seekbytes(procInfo.hProcess,baseAddr,endaddr,"\x85\xC9\x0F\x84\x00\x00\x00\x00\x68\x04\x01\x00\x00","xxxx????xxxxx"); // test ecx,ecx
patAddr2 = seekbytes(procInfo.hProcess,baseAddr,endaddr,"\x68\x28\x00\x08\x08","xxxxx"); // push 0x8080028
if(patAddr == 0 || patAddr2 == 0)
{
puts("[!] Cannot find pattern. Aborting...\n");
cleanup(procInfo.hThread,procInfo.hProcess);
return -1;
}
puts("\n-> Writing to process address space...\n");
// Patch process address space...
if(!WriteProcessMemory(procInfo.hProcess,(char*)patAddr+2,patch_bytes,2,NULL))
{
puts(" [!] Failed to write to process memory address!\n");
cleanup(procInfo.hThread,procInfo.hProcess);
return -1;
}
else
printf(" [*] Writing to address 0x%X\t[ OK ]\n",(unsigned int)patAddr);
if(!WriteProcessMemory(procInfo.hProcess,(char*)patAddr2,patch_bytes2,5,NULL))
{
puts(" [!] Failed to write to process memory address!\n");
cleanup(procInfo.hThread,procInfo.hProcess);
return -1;
}
else
printf(" [*] Writing to address 0x%X\t[ OK ]\n\n",(unsigned int)patAddr2);
puts("Ok, memory loader completed operation!\n");
cleanup(procInfo.hThread,procInfo.hProcess);
return 0;
}
|
revengsmK/exploader
|
src/memtools.c
|
#include <windows.h>
#include <tlhelp32.h>
#include <stdio.h>
#include "memtools.h"
/* Returns image base address of suspended process */
DWORD GetBaseAddress(HANDLE hProc ,HANDLE hThread){
DWORD baseAddr = 0;
CONTEXT ctx;
ctx.ContextFlags = CONTEXT_INTEGER;
if(!GetThreadContext(hThread,&ctx)){
puts("Failed to get thread context!");
return 0;
}
if(!ReadProcessMemory(hProc,(void*)(ctx.Ebx + 8),&baseAddr,sizeof(void*),NULL)){
puts("Failed to get base address!\nFailed to read process memory!");
return 0;
}
return baseAddr;
}
void KillProcessByName(const char *filename){
HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
PROCESSENTRY32 pEntry;
pEntry.dwSize = sizeof(PROCESSENTRY32);
BOOL hRes = Process32First(hSnapShot, &pEntry);
while (hRes)
{
if (strcmp(pEntry.szExeFile, filename) == 0)
{
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0,
(DWORD) pEntry.th32ProcessID);
if (hProcess != NULL)
{
TerminateProcess(hProcess, 1);
CloseHandle(hProcess);
}
}
hRes = Process32Next(hSnapShot, &pEntry);
}
CloseHandle(hSnapShot);
}
/*Searches for a specified masked byte pattern in a process address range
This is a modified (to search process address range) pattern
scanning function from guidedhacking.com
*/
uintptr_t seekbytes(HANDLE hProc, uintptr_t base_addr , uintptr_t end_addr, char *pattern , char *mask){
SIZE_T bytesRead = 0;
char buffer[4096];
uintptr_t currentChunk = base_addr;
size_t patternLength;
uintptr_t i,j;
while(currentChunk <= end_addr)
{
ReadProcessMemory(hProc,(void*)currentChunk,&buffer,4096,&bytesRead);
// check ReadProcessMemory() call
if(bytesRead == 0)
return 0;
patternLength = strlen(mask);
for ( i = 0; i < bytesRead - patternLength; i++)
{
BOOL found = TRUE;
for (j = 0; j < patternLength; j++)
{
if (mask[j] != '?' && pattern[j] != *(char*)(buffer + i + j))
{
found = FALSE;
break;
}
}
if (found)
return currentChunk + i;
}
currentChunk = currentChunk + bytesRead;
}
return 0;
}
|
revengsmK/exploader
|
src/memtools.h
|
<reponame>revengsmK/exploader
#ifndef MEMTOOLS_H
#define MEMTOOLS_H
#include <stdint.h>
DWORD GetBaseAddress(HANDLE hProc , HANDLE hThread);
void KillProcessByName(const char *filename);
uintptr_t seekbytes (HANDLE hProc, uintptr_t base_addr , uintptr_t end_addr, char *pattern , char *mask);
#endif
|
discovery/slapd-ssha-totp
|
slapd-ssha-totp.c
|
/* slapd-ssha-totp.c - Password module for combined password+MFA (depends on slapd-totp) */
/* $OpenLDAP$ */
/* Authors: <NAME> <<EMAIL>>, <NAME> <<EMAIL>>
MIT License
Copyright (c) 2018 Discovery Communications
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <portable.h>
#include <stdbool.h>
#include "lutil.h"
#include "slap.h"
#include "config.h"
static LUTIL_PASSWD_CHK_FUNC chk_ssha_totp;
static const struct berval scheme_ssha_totp = BER_BVC("{SSHA+TOTP}");
#define DIGITS 6
static int chk_ssha_totp(
const struct berval *scheme,
const struct berval *passwd,
const struct berval *cred,
const char **text)
{
char *comma = NULL;
int ret = LUTIL_PASSWD_ERR;
if (cred->bv_len < DIGITS+1)
goto fail;
struct berval cred_totp;
ber_mem2bv(cred->bv_val + cred->bv_len - DIGITS, DIGITS, false, &cred_totp);
struct berval cred_ssha;
ber_mem2bv(cred->bv_val, cred->bv_len - DIGITS, false, &cred_ssha);
comma = memchr(passwd->bv_val, ',', passwd->bv_len);
if (!comma)
goto fail;
struct berval passwd_ssha;
ber_str2bv(passwd->bv_val, comma - passwd->bv_val, false, &passwd_ssha);
struct berval passwd_totp;
ber_str2bv(comma+1, passwd->bv_len - (comma + 1 - passwd->bv_val), false, &passwd_totp);
*comma = '\0'; // Hack: chk_ssha() assumes its inputs are null terminated, even though they are bervals
if ((ret=lutil_passwd(&passwd_ssha, &cred_ssha, (const char*[]){"{SSHA}", NULL}, text)))
goto fail;
if ((ret=lutil_passwd(&passwd_totp, &cred_totp, (const char*[]){"{TOTP1}", "{TOTP256}", "{TOTP512}", NULL}, text)))
goto fail;
ret = LUTIL_PASSWD_OK; // Success!
fail:
if (comma)
*comma = ',';
return ret;
}
int
ssha_totp_initialize(void)
{
return lutil_passwd_add((struct berval *) &scheme_ssha_totp, chk_ssha_totp, NULL);
}
int init_module(int argc, char *argv[]) {
return ssha_totp_initialize();
}
|
Spidfail/libft_extended
|
ft_strtrim.c
|
<reponame>Spidfail/libft_extended<gh_stars>0
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strtrim.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: guhernan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/01 17:33:22 by guhernan #+# #+# */
/* Updated: 2020/12/09 16:01:58 by guhernan ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include <stdio.h>
size_t ft_trimend(char const *s, char const *set, size_t len)
{
size_t i;
size_t k;
size_t count;
i = len - 1;
k = 0;
count = 0;
while (i != 0 && set[k])
{
if (s[i] == set[k])
{
i--;
k = 0;
count++;
}
else
k++;
}
return (count);
}
size_t ft_trimbeg(char const *s, char const *set, size_t len)
{
size_t i;
size_t k;
size_t count;
i = 0;
k = 0;
count = 0;
while (i < len && set[k])
{
if (s[i] == set[k])
{
i++;
k = 0;
count++;
}
else
k++;
}
return (count);
}
char *ft_strtrim(char const *s, char const *set)
{
char *srtn;
size_t cntend;
size_t cntbeg;
size_t size;
size = 0;
if (s == NULL || set == NULL)
return (0);
cntend = ft_trimend(s, set, ft_strlen(s));
cntbeg = ft_trimbeg(s, set, ft_strlen(s) - cntend);
if (cntbeg + cntend == ft_strlen(s))
size = 1;
else
size = (ft_strlen(s) + 1) - (cntbeg + cntend);
srtn = malloc(sizeof(char) * size);
if (srtn == NULL)
return (NULL);
ft_strlcpy(srtn, &s[cntbeg], size);
return (srtn);
}
|
Spidfail/libft_extended
|
ft_strnstr_nb.c
|
<filename>ft_strnstr_nb.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strnstr_nb.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: guhernan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/08/16 14:33:48 by guhernan #+# #+# */
/* Updated: 2021/08/16 14:33:49 by guhernan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int ft_strnstr_nb(const char *haystack, const char *ndle, size_t len)
{
const char *tmp;
size_t i;
size_t n;
i = 0;
n = 0;
tmp = 0;
if (!haystack || !ndle || len == 0 || len > INT_MAX)
return (-1);
n = ft_strlen(ndle);
tmp = ft_strnstr(haystack, ndle, len);
if (n > INT_MAX || ft_strlen(haystack) > INT_MAX || !tmp)
return (-1);
i += 1;
while (tmp)
{
len -= (tmp + n) - haystack;
if (len < n)
return (i);
i++;
tmp = ft_strnstr((tmp + 1), ndle, ft_strlen(tmp));
}
return (i);
}
|
Spidfail/libft_extended
|
ft_memjoin.c
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_memjoin.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: guhernan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/02/03 12:30:21 by guhernan #+# #+# */
/* Updated: 2021/02/03 16:51:50 by guhernan ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
void *ft_memjoin(void *m1, void *m2, size_t size1, size_t size2)
{
char *mem;
mem = NULL;
if ((m1 && size1 > 0) && (m2 && size2 > 0))
{
mem = ft_calloc((size1 + size2 + 1), sizeof(char));
if (!mem)
return (NULL);
ft_memcpy(mem, m1, (size1));
ft_memcpy(&mem[size1], m2, (size2));
}
else if ((m1 == NULL || size1 == 0) && (m2 != NULL && size2 > 0))
mem = ft_memdup(m2, size2);
else
mem = ft_memdup(m1, size1);
return (mem);
}
|
Spidfail/libft_extended
|
ft_uatoi.c
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_uatoi.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: guhernan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/18 11:45:04 by guhernan #+# #+# */
/* Updated: 2021/03/11 08:28:02 by guhernan ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
** uatoi takes a str with positive number ; so a '-' before any number
** return 0. '+' is accepted.
*/
static int ft_check_intmax(unsigned long int rtn)
{
if (rtn > UINT_MAX)
return (1);
else
return (0);
}
unsigned int ft_uatoi(const char *str)
{
size_t i;
unsigned long int rtn;
i = 0;
rtn = 0;
while (ft_isspace(str[i]))
i++;
if (str[i] == '+')
i++;
else if (str[i] == '-')
return (0);
while (str[i] >= '0' && str[i] <= '9')
{
rtn *= 10;
rtn += str[i] - '0';
if (ft_check_intmax(rtn))
return (0);
i++;
}
return (rtn);
}
|
Spidfail/libft_extended
|
ft_substr.c
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_substr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: guhernan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/01 12:07:23 by guhernan #+# #+# */
/* Updated: 2020/12/04 10:26:42 by guhernan ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_countmem(char const *s, unsigned int start, size_t len)
{
if (len > (ft_strlen(s) + 1))
return (len = (ft_strlen(s) + 1) - start);
else if (len == (ft_strlen(s) + 1))
return (len);
else
return (len + 1);
}
char *ft_substr(char const *s, unsigned int start, size_t len)
{
char *rtn;
if (s == NULL)
return (NULL);
if (start >= ft_strlen(s))
{
rtn = malloc(sizeof(char));
rtn[0] = '\0';
return (rtn);
}
else
rtn = malloc(sizeof(char) * ft_countmem(s, start, len));
if (rtn == NULL)
return (NULL);
ft_strlcpy(rtn, &s[start], len + 1);
return (rtn);
}
|
Spidfail/libft_extended
|
ft_strsvchr.c
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsvchr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: guhernan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/02/24 17:55:59 by guhernan #+# #+# */
/* Updated: 2021/02/25 15:33:30 by guhernan ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
** This function is nearly identical to strchr, but instead of searching
** one char, you can check several others. The char are listed in 'chcmp'
** parameter by the user.
*/
char *ft_strsvchr(const char *s, char *chcmp)
{
int i;
int j;
i = 0;
j = 0;
if (s == NULL)
return (NULL);
if (chcmp == NULL)
return (NULL);
while (s[i])
{
while (chcmp[j])
{
if (s[i] == chcmp[j])
return (&chcmp[j]);
j++;
}
j = 0;
i++;
}
return (NULL);
}
|
Spidfail/libft_extended
|
ft_itoa.c
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: guhernan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/04 16:10:12 by guhernan #+# #+# */
/* Updated: 2021/03/11 10:44:33 by guhernan ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
** Checked cases when n == 0;
*/
static size_t ft_nballoc(int n)
{
size_t k;
k = 0;
if (n == 0)
k = 1;
else
{
while (n != 0)
{
n /= 10;
k++;
}
}
return (k);
}
static long int ft_sign(int n)
{
long int nb;
nb = n;
if (nb < 0)
return (nb * -1);
return (n);
}
char *ft_itoa(int n)
{
size_t k;
long int nb;
char *arr;
k = ft_nballoc(n);
nb = ft_sign(n);
arr = NULL;
if (n < 0)
arr = ft_calloc((k += 1) + 1, sizeof(char));
else if (n >= 0)
arr = ft_calloc(k + 1, sizeof(char));
if (!arr)
return (NULL);
while (k-- > 0)
{
arr[k] = (nb % 10) + '0';
nb /= 10;
}
if (arr[0] == '0' && arr[1] != '\0')
arr[0] = '-';
return (arr);
}
|
Spidfail/libft_extended
|
ft_atoi.c
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_atoi.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: guhernan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/30 21:32:12 by guhernan #+# #+# */
/* Updated: 2021/03/11 08:22:31 by guhernan ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_check_max(long int nb, int sgn)
{
if (sgn > 0)
{
if (nb > INT_MAX)
return (INT_MAX);
}
else if (sgn < 0)
if ((nb * -1) < INT_MIN)
return (INT_MIN);
return (1);
}
static int ft_build_number(const char *str, size_t i, int sgn)
{
long int rtn;
rtn = 0;
while (str[i] >= '0' && str[i] <= '9')
{
rtn *= 10;
rtn += str[i] - '0';
if (ft_check_max(rtn, sgn) == INT_MIN)
return (INT_MIN);
else if (ft_check_max(rtn, sgn) == INT_MAX)
return (INT_MAX);
i++;
}
return (rtn * sgn);
}
int ft_atoi(const char *str)
{
size_t i;
int sgn;
i = 0;
sgn = 1;
if (str == NULL)
return (-1);
while (ft_isspace(str[i]))
i++;
if (str[i] == '-' || str[i] == '+')
{
if (str[i] == '-')
sgn *= -1;
i++;
}
return (ft_build_number(str, i, sgn));
}
|
Spidfail/libft_extended
|
ft_lstmap.c
|
<reponame>Spidfail/libft_extended<filename>ft_lstmap.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_lstmap.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: guhernan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/07 14:07:23 by guhernan #+# #+# */
/* Updated: 2020/12/09 14:57:37 by guhernan ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
t_list *ft_lstmap(t_list *lst, void *(*f)(void *), void (*del)(void *))
{
t_list *nlst;
t_list *simlst;
t_list *templst;
simlst = lst;
nlst = NULL;
while (simlst != NULL)
{
templst = ft_lstnew(f(simlst->content));
if (!templst)
{
ft_lstclear(&nlst, del);
return (NULL);
}
ft_lstadd_back(&nlst, templst);
simlst = simlst->next;
}
return (nlst);
}
|
Spidfail/libft_extended
|
ft_split.c
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: guhernan <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/02 19:41:43 by guhernan #+# #+# */
/* Updated: 2021/03/01 12:03:33 by guhernan ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
** Checked if s[] = '\0' ; if s[] is full of separators ;
** if there is a separator at the end or at the beginning of s[];
** if there is no separators in s[] or just one word ;
** if it's protected ; if there is any leaks ;
**
** Return value : The array of new strings resulting from the split.
** NULL if the allocation fails.
** Description : Allocates (with malloc(3)) and returns an array of strings
** obtained by splitting ’s’ using thecharacter ’c’ as a delimiter.
** The array must beended by a NULL pointer.
*/
static size_t ft_countword(char const *s, char c)
{
size_t i;
size_t count;
i = 0;
count = 0;
while (s[i])
{
if (s[i] != c && (s[i + 1] == c || s[i + 1] == '\0'))
count++;
i++;
}
return (count);
}
static void ft_init(size_t *i, size_t *k, size_t *len, size_t *start)
{
*i = 0;
*k = 0;
*len = 0;
*start = 0;
}
static char **ft_douballoc(char const *s, char c, char **arr, size_t size)
{
size_t i;
size_t len;
size_t k;
size_t start;
ft_init(&i, &k, &len, &start);
while (k < size)
{
if (s[i] != c)
{
if (len == 0)
start = i;
len++;
}
if ((s[i] == c && len != 0) || (s[i] == '\0' && len != 0))
{
arr[k] = ft_substr(s, start, len);
if (!arr[k++])
return (NULL);
len = 0;
}
i++;
}
return (arr);
}
static void *ft_dblfree(char **arr, size_t nword)
{
size_t j;
j = 0;
while (j++ <= nword)
free(arr[j]);
free(arr);
return (NULL);
}
char **ft_split(char const *s, char c)
{
size_t nword;
char **arr;
if (s == NULL)
return (0);
nword = ft_countword(s, c);
arr = malloc(sizeof(char *) * (nword + 1));
if (!arr)
return (NULL);
arr[nword] = NULL;
if (!(ft_douballoc(s, c, arr, nword)))
{
ft_dblfree(arr, nword);
return (NULL);
}
return (arr);
}
|
uberyoji/gbdk-2020
|
gbdk-support/bankpack/bankpack.c
|
// This is free and unencumbered software released into the public domain.
// For more information, please refer to <https://unlicense.org>
// bbbbbr 2020
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// #include <unistd.h>
#include <stdbool.h>
#include <stdint.h>
#include "obj_data.h"
#include "files.h"
bool g_option_verbose = false;
bool g_option_cartsize = false;
static void display_help(void);
static int handle_args(int argc, char * argv[]);
static void option_set_verbose(bool is_enabled);
static void init(void);
void cleanup(void);
static void display_help(void) {
fprintf(stdout,
"bankalloc [options] objfile1 objfile2 etc\n"
"Use: Read .o files and auto-assign areas with bank=255.\n"
" Typically called by Lcc compiler driver before linker.\n"
"\n"
"Options\n"
"-h : Show this help\n"
"-yt<mbctype> : Set MBC type per ROM byte 149 in Decimal or Hex (0xNN) (see pandocs)\n"
"-mbc=N : Similar to -yt, but sets MBC type directly to N instead\n"
" of by intepreting ROM byte 149\n"
" mbc1 will exclude banks {0x20,0x40,0x60} max=127, \n"
" mbc2 max=15, mbc3 max=127, mbc5 max=255 (not 511!) \n"
"-min=N : Min assigned ROM bank is N (default 1)\n"
"-max=N : Max assigned ROM bank is N, error if exceeded\n"
"-ext=<.ext> : Write files out with <.ext> instead of source extension\n"
"-path=<path> : Write files out to <path> (<path> *MUST* already exist)\n"
"-sym=<prefix>: Add symbols starting with <prefix> to match + update list.\n"
" Default entry is \"___bank_\" (see below)\n"
"-cartsize : Print min required cart size as \"autocartsize:<NNN>\"\n"
"-v : Verbose output, show assignments\n"
"\n"
"Example: \"bankpack -ext=.rel -path=some/newpath/ file1.o file2.o\"\n"
"Unless -ext or -path specify otherwise, input files are overwritten.\n"
"\n"
"Default MBC type is not set. It *must* be specified by -mbc= or -yt!\n"
"\n"
"The following will have FF and 255 replaced with the assigned bank:\n"
"A _CODE_255 size <size> flags <flags> addr <address>\n"
"S b_<function name> Def0000FF\n"
"S ___bank_<const name> Def0000FF\n"
" (Above can be made by: const void __at(255) __bank_<const name>;\n"
);
}
static int handle_args(int argc, char * argv[]) {
int i;
if( argc < 2 ) {
display_help();
return false;
}
// Start at first optional argument, argc is zero based
for (i = 1; i <= (argc -1); i++ ) {
if (argv[i][0] == '-') {
if (strstr(argv[i], "-h") == argv[i]) {
display_help();
return false; // Don't parse input when -h is used
} else if (strstr(argv[i], "-min=") == argv[i]) {
if (!banks_set_min(atoi(argv[i] + 5))) {
printf("BankPack: ERROR: Invalid min bank: %s\n", argv[i] + 5);
return false;
}
} else if (strstr(argv[i], "-max=") == argv[i]) {
if (!banks_set_max(atoi(argv[i] + 5))) {
printf("BankPack: ERROR: Invalid max bank: %s\n", argv[i] + 5);
return false;
}
} else if (strstr(argv[i], "-ext=") == argv[i]) {
files_set_out_ext(argv[i] + 5);
} else if (strstr(argv[i], "-path=") == argv[i]) {
files_set_out_path(argv[i] + 6);
} else if (strstr(argv[i], "-mbc=") == argv[i]) {
banks_set_mbc(atoi(argv[i] + 5));
} else if (strstr(argv[i], "-yt") == argv[i]) {
banks_set_mbc_by_rom_byte_149(strtol(argv[i] + 3, NULL, 0));
} else if (strstr(argv[i], "-v") == argv[i]) {
option_set_verbose(true);
} else if (strstr(argv[i], "-sym=") == argv[i]) {
symbol_match_add(argv[i] + 5);
} else if (strstr(argv[i], "-cartsize") == argv[i]) {
g_option_cartsize = true;
} else
printf("BankPack: Warning: Ignoring unknown option %s\n", argv[i]);
} else {
// Add to list of object files to process
files_add(argv[i]);
}
}
return true;
}
static void option_set_verbose(bool is_enabled) {
g_option_verbose = is_enabled;
}
static int matches_extension(char * filename, char * extension) {
return (strcmp(filename + (strlen(filename) - strlen(extension)), extension) == 0);
}
static void init(void) {
files_init();
obj_data_init();
}
void cleanup(void) {
files_cleanup();
obj_data_cleanup();
}
int main( int argc, char *argv[] ) {
// Exit with failure by default
int ret = EXIT_FAILURE;
// Register cleanup with exit handler
atexit(cleanup);
init();
if (handle_args(argc, argv)) {
if (banks_get_mbc_type() != MBC_TYPE_NONE) {
// Extract areas, sort and assign them to banks
// then rewrite object files as needed
files_extract();
files_rewrite();
if (g_option_verbose)
banks_show();
if (g_option_cartsize)
fprintf(stdout,"autocartsize:%d\n",banks_calc_cart_size());
cleanup();
ret = EXIT_SUCCESS;
} else
printf("BankPack: ERROR: auto-banking does not work with unbanked ROMS (no MBC)\n");
}
return ret; // Exit with failure by default
}
|
uberyoji/gbdk-2020
|
gbdk-support/lcc/gb.h
|
<filename>gbdk-support/lcc/gb.h<gh_stars>0
// gb.h
#ifndef _LCC_GB_H
#define _LCC_GB_H
#define SUFX_NOMATCH -1
#define EXT_C ".c"
#define EXT_I ".i"
#define EXT_ASM ".asm"
#define EXT_S ".s"
#define EXT_O ".o"
#define EXT_OBJ ".obj"
#define EXT_IHX ".ihx"
#define EXT_GB ".gb"
#endif // _LCC_GB_H
|
uberyoji/gbdk-2020
|
gbdk-lib/include/gb/isr.h
|
<filename>gbdk-lib/include/gb/isr.h
/** @file gb/isr.h
Allows constructing of raw ISR vectors.
*/
#ifndef _ISR_H_INCLUDE_
#define _ISR_H_INCLUDE_
#include <stdint.h>
// #define VECTOR_VBL 0x40 // you can not define raw vector for VBlank interrupt
#define VECTOR_STAT 0x48
#define VECTOR_TIMER 0x50
#define VECTOR_SERIAL 0x58
#define VECTOR_JOYPAD 0x60
typedef struct isr_vector_t {
uint8_t opcode;
void * func;
} isr_vector_t;
/** Creates the interrupt vector at the given address for the raw interrupt service routrine
@param ADDR address of the vector
@param FUNC ISR function
*/
#define ISR_VECTOR(ADDR, FUNC) \
static const isr_vector_t __at((ADDR)) __ISR_ ## ADDR = {0xc3, (void *)&(FUNC) };
#endif // _ISR_H_INCLUDE_
|
uberyoji/gbdk-2020
|
gbdk-lib/include/gb/bgb_emu.h
|
/** @file gb/bgb_emu.h
Debug window logging and profiling support for the BGB emulator.
Also see the `bgb_debug` example project included with gbdk.
See the BGB Manual for more information
("expressions, breakpoint conditions, and debug messages")
http://bgb.bircd.org/manual.html#expressions
*/
#ifndef __BGB_EMU_INCLUDE
#define __BGB_EMU_INCLUDE
/** Macro to display a message in the BGB emulator debug message window
@param message_text Quoted text string to display in the debug message window
The following special parameters can be
used when bracketed with "%" characters.
\li CPU registers: AF, BC, DE, HL, SP, PC, B, C, D,
E, H, L, A, ZERO, ZF, Z, CARRY, CY, IME, ALLREGS
\li Other state values: ROMBANK, XRAMBANK, SRAMBANK,
WRAMBANK, VRAMBANK, TOTALCLKS, LASTCLKS, CLKS2VBLANK
Example: print a message along with the currently active ROM bank.
\code{.c}
BGB_MESSAGE("Current ROM Bank is: %ROMBANK%");
\endcode
See the BGB Manual for more information
("expressions, breakpoint conditions, and debug messages")
http://bgb.bircd.org/manual.html#expressions
@see BGB_PROFILE_BEGIN(), BGB_PROFILE_END()
*/
#define BGB_MESSAGE(message_text) BGB_MESSAGE1(BGB_MACRONAME(__LINE__), message_text)
/// \cond DOXYGEN_DO_NOT_DOCUMENT
#define BGB_MACRONAME(A) BGB_MACRONAME1(A)
#define BGB_MACRONAME1(A) BGBLOG##A
#define BGB_MESSAGE1(name, message_text) \
__asm \
.MACRO name msg_t, msg_s, ?llbl\
ld d, d \
jr llbl \
.dw 0x6464 \
.dw 0x0000 \
.ascii msg_t \
llbl: \
.ENDM \
name ^/message_text/ \
__endasm
#define BGB_MESSAGE_SUFFIX(message_text, message_suffix) BGB_MESSAGE3(BGB_MACRONAME(__LINE__), message_text, message_suffix)
#define BGB_MESSAGE3(name, message_text, message_suffix) \
__asm \
.MACRO name msg_t, msg_s, ?llbl\
ld d, d \
jr llbl \
.dw 0x6464 \
.dw 0x0000 \
.ascii msg_t \
.ascii msg_s \
llbl: \
.ENDM \
name ^/message_text/, ^/message_suffix/ \
__endasm
/// \endcond DOXYGEN_DO_NOT_DOCUMENT
/** Macro to __Start__ a profiling block for the BGB emulator
@param MSG Quoted text string to display in the
debug message window along with the result
To complete the profiling block and print
the result call @ref BGB_PROFILE_END.
@see BGB_PROFILE_END(), BGB_MESSAGE()
*/
#define BGB_PROFILE_BEGIN(MSG) BGB_MESSAGE_SUFFIX(MSG, "%ZEROCLKS%");
/** Macro to __End__ a profiling block and print the results in the BGB emulator debug message window
@param MSG Quoted text string to display in the
debug message window along with the result
This should only be called after a previous call
to @ref BGB_PROFILE_BEGIN()
The results are in BGB clock units, which are
"1 nop in [CGB] doublespeed mode".
So when running in Normal Speed mode (i.e. non-CGB doublespeed)
the printed result should be __divided by 2__ to get the actual
ellapsed cycle count.
If running in CB Double Speed mode use the below call instead,
it correctly compensates for the speed difference. In this
scenario, the result does __not need to be divided by 2__ to
get the ellapsed cycle count.
\code{.c}
BGB_MESSAGE("NOP TIME: %-4+LASTCLKS%");
\endcode
@see BGB_PROFILE_BEGIN(), BGB_MESSAGE()
*/
#define BGB_PROFILE_END(MSG) BGB_MESSAGE_SUFFIX(MSG,"%-8+LASTCLKS%");
#define BGB_TEXT(MSG) BGB_MESSAGE(MSG)
/** Display preset debug information in the BGB debug messages window.
This function is equivalent to:
\code{.c}
BGB_MESSAGE("PROFILE,%(SP+$0)%,%(SP+$1)%,%A%,%TOTALCLKS%,%ROMBANK%,%WRAMBANK%");
\endcode
*/
void BGB_profiler_message();
/** Print the string and arguments given by format to the BGB emulator debug message window
@param format The format string as per printf
Does not return the number of characters printed.
Result string MUST BE LESS OR EQUAL THAN 128 BYTES LONG, INCLUDING THE TRAILIG ZERO BYTE!
Currently supported:
\li \%hx (char as hex)
\li \%hu (unsigned char)
\li \%hd (signed char)
\li \%c (character)
\li \%u (unsigned int)
\li \%d (signed int)
\li \%x (unsigned int as hex)
\li \%s (string)
Warning: to correctly pass chars for printing as chars, they *must*
be explicitly re-cast as such when calling the function.
See @ref docs_chars_varargs for more details.
*/
void BGB_printf(const char *format, ...) NONBANKED;
static void * __BGB_PROFILER_INIT = &BGB_profiler_message;
#endif
|
uberyoji/gbdk-2020
|
gbdk-lib/include/gb/gb.h
|
<filename>gbdk-lib/include/gb/gb.h<gh_stars>0
/** @file gb/gb.h
Gameboy specific functions.
*/
#ifndef _GB_H
#define _GB_H
#define __GBDK_VERSION 404
#include <types.h>
#include <stdint.h>
#include <gb/hardware.h>
/** Joypad bits.
A logical OR of these is used in the wait_pad and joypad
functions. For example, to see if the B button is pressed
try
uint8_t keys;
keys = joypad();
if (keys & J_B) {
...
}
@see joypad
*/
#define J_START 0x80U
#define J_SELECT 0x40U
#define J_B 0x20U
#define J_A 0x10U
#define J_DOWN 0x08U
#define J_UP 0x04U
#define J_LEFT 0x02U
#define J_RIGHT 0x01U
/** Screen modes.
Normally used by internal functions only.
@see mode()
*/
#define M_DRAWING 0x01U
#define M_TEXT_OUT 0x02U
#define M_TEXT_INOUT 0x03U
/** Set this in addition to the others to disable scrolling
If scrolling is disabled, the cursor returns to (0,0)
@see mode()
*/
#define M_NO_SCROLL 0x04U
/** Set this to disable interpretation
@see mode()
*/
#define M_NO_INTERP 0x08U
/** If this is set, sprite colours come from OBJ1PAL. Else
they come from OBJ0PAL
@see set_sprite_prop().
*/
#define S_PALETTE 0x10U
/** If set the sprite will be flipped horizontally.
@see set_sprite_prop()
*/
#define S_FLIPX 0x20U
/** If set the sprite will be flipped vertically.
@see set_sprite_prop()
*/
#define S_FLIPY 0x40U
/** If this bit is clear, then the sprite will be displayed
on top of the background and window.
@see set_sprite_prop()
*/
#define S_PRIORITY 0x80U
/* Interrupt flags */
/** Disable calling of interrupt service routines
*/
#define EMPTY_IFLAG 0x00U
/** VBlank Interrupt occurs at the start of the vertical blank.
During this period the video ram may be freely accessed.
@see set_interrupts(), @see add_VBL
*/
#define VBL_IFLAG 0x01U
/** LCD Interrupt when triggered by the STAT register.
@see set_interrupts(), @see add_LCD
*/
#define LCD_IFLAG 0x02U
/** Timer Interrupt when the timer @ref TIMA_REG overflows.
@see set_interrupts(), @see add_TIM
*/
#define TIM_IFLAG 0x04U
/** Serial Link Interrupt occurs when the serial transfer has completed.
@see set_interrupts(), @see add_SIO
*/
#define SIO_IFLAG 0x08U
/** Joypad Interrupt occurs on a transition of the keypad.
@see set_interrupts(), @see add_JOY
*/
#define JOY_IFLAG 0x10U
/* DMG Palettes */
#define DMG_BLACK 0x03
#define DMG_DARK_GRAY 0x02
#define DMG_LITE_GRAY 0x01
#define DMG_WHITE 0x00
/** DMG palette helper macro.
*/
#define DMG_PALETTE(C0, C1, C2, C3) ((UBYTE)((((C3) & 0x03) << 6) | (((C2) & 0x03) << 4) | (((C1) & 0x03) << 2) | ((C0) & 0x03)))
/* Limits */
/** Width of the visible screen in pixels.
*/
#define SCREENWIDTH 0xA0U
/** Height of the visible screen in pixels.
*/
#define SCREENHEIGHT 0x90U
/** The Minimum X position of the Window Layer (Left edge of screen) @see move_win()
*/
#define MINWNDPOSX 0x07U
/** The Minimum Y position of the Window Layer (Top edge of screen) @see move_win()
*/
#define MINWNDPOSY 0x00U
/** The Maximum X position of the Window Layer (Right edge of screen) @see move_win()
*/
#define MAXWNDPOSX 0xA6U
/** The Maximum Y position of the Window Layer (Bottom edge of screen) @see move_win()
*/
#define MAXWNDPOSY 0x8FU
/** Interrupt handlers
*/
typedef void (*int_handler)(void) NONBANKED;
/** The remove functions will remove any interrupt handler.
A handler of NULL will cause bad things
to happen if the given interrupt is enabled.
Removes the VBL interrupt handler. @see add_VBL()
*/
void remove_VBL(int_handler h) NONBANKED;
/** Removes the LCD interrupt handler.
@see add_LCD(), remove_VBL()
*/
void remove_LCD(int_handler h) NONBANKED;
/** Removes the TIM interrupt handler.
@see add_TIM(), remove_VBL()
*/
void remove_TIM(int_handler h) NONBANKED;
/** Removes the Serial Link / SIO interrupt handler.
@see add_SIO(), @see remove_VBL()
The default SIO ISR gets installed automatically if
any of the standard SIO calls are used. These calls
include @ref add_SIO(), @ref remove_SIO(),
@ref send_byte(), @ref receive_byte().
The default SIO ISR cannot be removed once installed.
Only secondary chained SIO ISRs (added with @ref add_SIO() )
can be removed.
*/
void remove_SIO(int_handler h) NONBANKED;
/** Removes the JOY interrupt handler.
@see add_JOY(), remove_VBL()
*/
void remove_JOY(int_handler h) NONBANKED;
/** Adds a V-blank interrupt handler.
@param h The handler to be called whenever a V-blank
interrupt occurs.
Up to 4 handlers may be added, with the last added being
called last. If the @ref remove_VBL function is to be called,
only three may be added.
Do not use '__critical' and '__interrupt' attributes for a
function added via add_VBL() (or LCD, etc). The attributes
are only required when constructing a bare jump from the
interrupt vector itself.
Note: The default VBL is installed automatically.
*/
void add_VBL(int_handler h) NONBANKED;
/** Adds a LCD interrupt handler.
Called when the LCD interrupt occurs, which is normally
when @ref LY_REG == @ref LYC_REG.
From pan/k0Pa:
There are various reasons for this interrupt to occur
as described by the @ref STAT_REG register ($FF41). One very
popular reason is to indicate to the user when the
video hardware is about to redraw a given LCD line.
This can be useful for dynamically controlling the
@ref SCX_REG / @ref SCY_REG registers ($FF43/$FF42) to perform
special video effects.
@see add_VBL
*/
void add_LCD(int_handler h) NONBANKED;
/** Adds a timer interrupt handler.
From pan/k0Pa:
This interrupt occurs when the @ref TIMA_REG
register ($FF05) changes from $FF to $00.
@see add_VBL
@see set_interrupts() with TIM_IFLAG
*/
void add_TIM(int_handler h) NONBANKED;
/** Adds a Serial Link transmit complete interrupt handler.
From pan/k0Pa:
This interrupt occurs when a serial transfer has
completed on the game link port.
@see send_byte, receive_byte(), add_VBL()
@see set_interrupts() with SIO_IFLAG
*/
void add_SIO(int_handler h) NONBANKED;
/** Adds a joypad button change interrupt handler.
From pan/k0Pa:
This interrupt occurs on a transition of any of the
keypad input lines from high to low. Due to the fact
that keypad "bounce" is virtually always present,
software should expect this interrupt to occur one
or more times for every button press and one or more
times for every button release.
@see joypad(), add_VBL()
*/
void add_JOY(int_handler h) NONBANKED;
/** Interrupt handler chain terminator that does __not__ wait for .STAT
You must add this handler last in every interrupt handler
chain if you want to change the default interrupt handler
behaviour that waits for LCD controller mode to become 1 or 0
before return from the interrupt.
Example:
\code{.c}
__critical {
add_SIO(nowait_int_handler); // Disable wait on VRAM state before returning from SIO interrupt
}
\endcode
@see wait_int_handler()
*/
void nowait_int_handler(void) NONBANKED;
/** Default Interrupt handler chain terminator that waits for
@see STAT_REG and __only__ returns at the BEGINNING of
either Mode 0 or Mode 1.
Used by default at the end of interrupt chains to help
prevent graphical glitches. The glitches are caused when an
ISR interrupts a graphics operation in one mode but returns
in a different mode for which that graphics operation is not
allowed.
@see nowait_int_handler()
*/
void wait_int_handler(void) NONBANKED;
/** Set the current screen mode - one of M_* modes
Normally used by internal functions only.
@see M_DRAWING, M_TEXT_OUT, M_TEXT_INOUT, M_NO_SCROLL, M_NO_INTERP
*/
void mode(uint8_t m) NONBANKED;
/** Returns the current mode
@see M_DRAWING, M_TEXT_OUT, M_TEXT_INOUT, M_NO_SCROLL, M_NO_INTERP
*/
uint8_t get_mode(void) NONBANKED __preserves_regs(b, c);
/** GB CPU type
@see DMG_TYPE, MGB_TYPE, CGB_TYPE, cpu_fast(), cpu_slow()
*/
extern uint8_t _cpu;
/** Hardware Model: Original GB or Super GB. @see _cpu
*/
#define DMG_TYPE 0x01
/** Hardware Model: Pocket GB or Super GB 2. @see _cpu
*/
#define MGB_TYPE 0xFF
/** Hardware Model: Color GB. @see _cpu
*/
#define CGB_TYPE 0x11
/** Global Time Counter in VBL periods (60Hz)
Increments once per Frame
Will wrap around every ~18 minutes (unsigned 16 bits = 65535 / 60 / 60 = 18.2)
*/
extern volatile uint16_t sys_time;
/** Serial Link: Send the byte in @ref _io_out out through the serial port
Make sure to enable interrupts for the
Serial Link before trying to transfer data.
@see add_SIO(), remove_SIO()
@see set_interrupts() with @ref SIO_IFLAG
*/
void send_byte(void);
/** Serial Link: Receive a byte from the serial port into @ref _io_in
Make sure to enable interrupts for the
Serial Link before trying to transfer data.
@see add_SIO(), remove_SIO()
@see set_interrupts() with @ref SIO_IFLAG
*/
void receive_byte(void);
/** Serial Link: Current IO Status. An OR of IO_* */
extern volatile uint8_t _io_status;
/** Serial Link: Byte just read after calling @ref receive_byte()
*/
extern volatile uint8_t _io_in;
/** Serial Link: Write byte to send here before calling @ref send_byte()
*/
extern volatile uint8_t _io_out;
/* Status codes */
/** Serial Link IO is completed */
#define IO_IDLE 0x00U
/** Serial Link Sending data */
#define IO_SENDING 0x01U
/** Serial Link Receiving data */
#define IO_RECEIVING 0x02U
/** Serial Link Error */
#define IO_ERROR 0x04U
/** Tracks current active ROM bank @see SWITCH_ROM_MBC1(), SWITCH_ROM_MBC5()
This variable is updated automatically when you call SWITCH_ROM_MBC1 or
SWITCH_ROM_MBC5, or call a BANKED function.
*/
__REG _current_bank;
#define CURRENT_BANK _current_bank
/** Obtains the __bank number__ of VARNAME
@param VARNAME Name of the variable which has a __bank_VARNAME companion symbol which is adjusted by bankpack
*/
#ifndef BANK
#define BANK(VARNAME) ( (uint8_t) & __bank_ ## VARNAME )
#endif
/** Creates the reference for retriving the bank number of the object
@param VARNAME Variable name to use, may be existiing identifier
@see BANK() for obtaining the bank number of the included data.
Use @ref BANKREF_EXTERN() within another source file
to make the variable and it's data accesible there.
*/
#define BANKREF(VARNAME) void __func_ ## VARNAME() __banked __naked { \
__asm \
.local b___func_ ## VARNAME \
___bank_ ## VARNAME = b___func_ ## VARNAME \
.globl ___bank_ ## VARNAME \
__endasm; \
}
/** Creates extern references for accessing a BANKREF() generated variable.
@param VARNAME Name of the variable used with BANKREF
@ref BANKREF(), BANK()
*/
#define BANKREF_EXTERN(VARNAME) extern const void __bank_ ## VARNAME;
/** Makes MBC1 and other compatible MBCs switch the active ROM bank
@param b ROM bank to switch to
*/
#define SWITCH_ROM_MBC1(b) \
_current_bank = (b), *(uint8_t *)0x2000 = (b)
#define SWITCH_ROM SWITCH_ROM_MBC1
/** Switches SRAM bank on MBC1 and other compaticle MBCs
@param b SRAM bank to switch to
*/
#define SWITCH_RAM_MBC1(b) \
*(uint8_t *)0x4000 = (b)
#define SWITCH_RAM SWITCH_RAM_MBC1
/** Enables SRAM on MBC1
*/
#define ENABLE_RAM_MBC1 \
*(uint8_t *)0x0000 = 0x0A
#define ENABLE_RAM ENABLE_RAM_MBC1
/** Disables SRAM on MBC1
*/
#define DISABLE_RAM_MBC1 \
*(uint8_t *)0x0000 = 0x00
#define DISABLE_RAM DISABLE_RAM_MBC1
#define SWITCH_16_8_MODE_MBC1 \
*(uint8_t *)0x6000 = 0x00
#define SWITCH_4_32_MODE_MBC1 \
*(uint8_t *)0x6000 = 0x01
/** Makes MBC5 switch to the active ROM bank; only 4M roms are supported, @see SWITCH_ROM_MBC5_8M()
@param b ROM bank to switch to
Note the order used here. Writing the other way around on a MBC1 always selects bank 1
*/
#define SWITCH_ROM_MBC5(b) \
_current_bank = (b), \
*(uint8_t *)0x3000 = 0, \
*(uint8_t *)0x2000 = (b)
/** Makes MBC5 to switch the active ROM bank; active bank number is not tracked by _current_bank if you use this macro
@see _current_bank
@param b ROM bank to switch to
Note the order used here. Writing the other way around on a MBC1 always selects bank 1
*/
#define SWITCH_ROM_MBC5_8M(b) \
*(uint8_t *)0x3000 = ((uint16_t)(b) >> 8), \
*(uint8_t *)0x2000 = (b)
/** Switches SRAM bank on MBC5
@param b SRAM bank to switch to
*/
#define SWITCH_RAM_MBC5(b) \
*(uint8_t *)0x4000 = (b)
/** Enables SRAM on MBC5
*/
#define ENABLE_RAM_MBC5 \
*(uint8_t *)0x0000 = 0x0A
/** Disables SRAM on MBC5
*/
#define DISABLE_RAM_MBC5 \
*(uint8_t *)0x0000 = 0x00
/** Delays the given number of milliseconds.
Uses no timers or interrupts, and can be called with
interrupts disabled (why nobody knows :)
*/
void delay(uint16_t d) NONBANKED;
/** Reads and returns the current state of the joypad.
Follows Nintendo's guidelines for reading the pad.
Return value is an OR of J_*
When testing for multiple different buttons, it's
best to read the joypad state *once* into a variable
and then test using that variable.
@see J_START, J_SELECT, J_A, J_B, J_UP, J_DOWN, J_LEFT, J_RIGHT
*/
uint8_t joypad(void) NONBANKED __preserves_regs(b, c, h, l);
/** Waits until at least one of the buttons given in mask are pressed.
@param mask Bitmask indicating which buttons to wait for
Normally only used for checking one key, but it will
support many, even J_LEFT at the same time as J_RIGHT. :)
Note: Checks in a loop that doesn't HALT at all, so the CPU
will be maxed out until this call returns.
@see joypad
@see J_START, J_SELECT, J_A, J_B, J_UP, J_DOWN, J_LEFT, J_RIGHT
*/
uint8_t waitpad(uint8_t mask) NONBANKED __preserves_regs(b, c);
/** Waits for the directional pad and all buttons to be released.
Note: Checks in a loop that doesn't HALT at all, so the CPU
will be maxed out until this call returns.
*/
void waitpadup(void) NONBANKED __preserves_regs(a, b, c, d, e, h, l);
/** Multiplayer joypad structure.
Must be initialized with @ref joypad_init() first then it
may be used to poll all avaliable joypads with @ref joypad_ex()
*/
typedef struct {
uint8_t npads;
union {
struct {
uint8_t joy0, joy1, joy2, joy3;
};
uint8_t joypads[4];
};
} joypads_t;
/** Initializes joypads_t structure for polling multiple joypads
(for the GB and ones connected via SGB)
@param npads number of joypads requested (1, 2 or 4)
@param joypads pointer to joypads_t structure to be initialized
Only required for @ref joypad_ex, not required for calls to regular @ref joypad()
@returns number of joypads avaliable
@see joypad_ex(), joypads_t
*/
uint8_t joypad_init(uint8_t npads, joypads_t * joypads);
/** Polls all avaliable joypads (for the GB and ones connected via SGB)
@param joypads pointer to joypads_t structure to be filled with joypad statuses,
must be previously initialized with joypad_init()
@see joypad_init(), joypads_t
*/
void joypad_ex(joypads_t * joypads) __preserves_regs(b, c);
/** Enables unmasked interrupts
@see disable_interrupts, set_interrupts
*/
inline void enable_interrupts(void) __preserves_regs(a, b, c, d, e, h, l) {
__asm__("ei");
}
/** Disables interrupts.
This function may be called as many times as you like;
however the first call to enable_interrupts will re-enable
them.
@see enable_interrupts, set_interrupts
*/
inline void disable_interrupts(void) __preserves_regs(a, b, c, d, e, h, l) {
__asm__("di");
}
/** Clears any pending interrupts and sets the interrupt mask
register IO to flags.
@param flags A logical OR of *_IFLAGS
@see enable_interrupts(), disable_interrupts()
@see VBL_IFLAG, LCD_IFLAG, TIM_IFLAG, SIO_IFLAG, JOY_IFLAG
*/
void set_interrupts(uint8_t flags) NONBANKED __preserves_regs(b, c, d, e);
/** Performs a warm reset by reloading the CPU value
then jumping to the start of crt0 (0x0150)
*/
void reset(void) NONBANKED;
/** HALTs the CPU and waits for the vertical blank interrupt (VBL) to finish.
This is often used in main loops to idle the CPU at low power
until it's time to start the next frame. It's also useful for
syncing animation with the screen re-draw.
Warning: If the VBL interrupt is disabled, this function will
never return. If the screen is off this function returns
immediately.
*/
void wait_vbl_done(void) NONBANKED __preserves_regs(b, c, d, e, h, l);
/** Turns the display off.
Waits until the VBL interrupt before turning the display off.
@see DISPLAY_ON
*/
void display_off(void) NONBANKED __preserves_regs(b, c, d, e, h, l);
/** Copies data from somewhere in the lower address space to part of hi-ram.
@param dst Offset in high ram (0xFF00 and above) to copy to.
@param src Area to copy from
@param n Number of bytes to copy.
*/
void hiramcpy(uint8_t dst,
const void *src,
uint8_t n) NONBANKED __preserves_regs(b, c);
/** Turns the display back on.
@see display_off, DISPLAY_OFF
*/
#define DISPLAY_ON \
LCDC_REG|=LCDCF_ON
/** Turns the display off immediately.
@see display_off, DISPLAY_ON
*/
#define DISPLAY_OFF \
display_off();
/** Turns on the background layer.
Sets bit 0 of the LCDC register to 1.
*/
#define SHOW_BKG \
LCDC_REG|=LCDCF_BGON
/** Turns off the background layer.
Sets bit 0 of the LCDC register to 0.
*/
#define HIDE_BKG \
LCDC_REG&=~LCDCF_BGON
/** Turns on the window layer
Sets bit 5 of the LCDC register to 1.
*/
#define SHOW_WIN \
LCDC_REG|=LCDCF_WINON
/** Turns off the window layer.
Clears bit 5 of the LCDC register to 0.
*/
#define HIDE_WIN \
LCDC_REG&=~LCDCF_WINON
/** Turns on the sprites layer.
Sets bit 1 of the LCDC register to 1.
*/
#define SHOW_SPRITES \
LCDC_REG|=LCDCF_OBJON
/** Turns off the sprites layer.
Clears bit 1 of the LCDC register to 0.
*/
#define HIDE_SPRITES \
LCDC_REG&=~LCDCF_OBJON
/** Sets sprite size to 8x16 pixels, two tiles one above the other.
Sets bit 2 of the LCDC register to 1.
*/
#define SPRITES_8x16 \
LCDC_REG|=LCDCF_OBJ16
/** Sets sprite size to 8x8 pixels, one tile.
Clears bit 2 of the LCDC register to 0.
*/
#define SPRITES_8x8 \
LCDC_REG&=~LCDCF_OBJ16
/**
* Set byte in vram at given memory location
*
* @param addr address to write to
* @param v value
*/
void set_vram_byte(uint8_t * addr, uint8_t v) __preserves_regs(b, c);
/**
* Get byte from vram at given memory location
*
* @param addr address to read from
* @return read value
*/
uint8_t get_vram_byte(uint8_t * addr) __preserves_regs(b, c);
/**
* Get address of X,Y tile of background map
*/
uint8_t * get_bkg_xy_addr(uint8_t x, uint8_t y) __preserves_regs(b, c);
/** Sets VRAM Tile Pattern data for the Background / Window
@param first_tile Index of the first tile to write
@param nb_tiles Number of tiles to write
@param data Pointer to (2 bpp) source tile data
Writes __nb_tiles__ tiles to VRAM starting at __first_tile__, tile data
is sourced from __data__. Each Tile is 16 bytes in size (8x8 pixels, 2 bits-per-pixel).
Note: Sprite Tiles 128-255 share the same memory region as Background Tiles 128-255.
GBC only: @ref VBK_REG determines which bank of Background tile patterns are written to.
\li VBK_REG=0 indicates the first bank
\li VBK_REG=1 indicates the second
*/
void set_bkg_data(uint8_t first_tile,
uint8_t nb_tiles,
const uint8_t *data) NONBANKED __preserves_regs(b, c);
/** Sets VRAM Tile Pattern data for the Background / Window using 1bpp source data
@param first_tile Index of the first Tile to write
@param nb_tiles Number of Tiles to write
@param data Pointer to (1bpp) source Tile Pattern data
@param color Color
Similar to @ref set_bkg_data, except source data is 1 bit-per-pixel
which gets expanded into 2 bits-per-pixel.
For a given bit that represent a pixel:
\li 0 will be expanded into color 0
\li 1 will be expanded into color 1, 2 or 3 depending on color argument
@see SHOW_BKG, HIDE_BKG, set_bkg_tiles
*/
void set_bkg_1bit_data(uint8_t first_tile,
uint8_t nb_tiles,
const uint8_t *data,
uint8_t color) NONBANKED __preserves_regs(b, c);
/** Copies from Background / Window VRAM Tile Pattern data into a buffer
@param first_tile Index of the first Tile to read from
@param nb_tiles Number of Tiles to read
@param data Pointer to destination buffer for Tile Pattern data
Copies __nb_tiles__ tiles from VRAM starting at __first_tile__, Tile data
is copied into __data__.
Each Tile is 16 bytes, so the buffer pointed to by __data__
should be at least __nb_tiles__ x 16 bytes in size.
@see get_win_data
*/
void get_bkg_data(uint8_t first_tile,
uint8_t nb_tiles,
uint8_t *data) NONBANKED __preserves_regs(b, c);
/** Sets a rectangular region of Background Tile Map.
@param x X Start position in Background Map tile coordinates. Range 0 - 31
@param y Y Start position in Background Map tile coordinates. Range 0 - 31
@param w Width of area to set in tiles. Range 1 - 32
@param h Height of area to set in tiles. Range 1 - 32
@param tiles Pointer to source tile map data
Entries are copied from map at __tiles__ to the Background Tile Map starting at
__x__, __y__ writing across for __w__ tiles and down for __h__ tiles.
Use @ref set_bkg_submap() instead when:
\li Source map is wider than 32 tiles.
\li Writing a width that does not match the source map width __and__ more
than one row high at a time.
One byte per source tile map entry.
Writes that exceed coordinate 31 on the x or y axis will wrap around to
the Left and Top edges.
Note: Patterns 128-255 overlap with patterns 128-255 of the sprite Tile Pattern table.
GBC only: @ref VBK_REG determines whether Tile Numbers or Tile Attributes get set.
\li VBK_REG=0 Tile Numbers are written
\li VBK_REG=1 Tile Attributes are written
GBC Tile Attributes are defined as:
\li Bit 7 - Priority flag. When this is set, it puts the tile above the sprites
with colour 0 being transparent.
\n 0: Below sprites
\n 1: Above sprites
\n Note: @ref SHOW_BKG needs to be set for these priorities to take place.
\li Bit 6 - Vertical flip. Dictates which way up the tile is drawn vertically.
\n 0: Normal
\n 1: Flipped Vertically
\li Bit 5 - Horizontal flip. Dictates which way up the tile is drawn horizontally.
\n 0: Normal
\n 1: Flipped Horizontally
\li Bit 4 - Not used
\li Bit 3 - Character Bank specification. Dictates from which bank of
Background Tile Patterns the tile is taken.
\n 0: Bank 0
\n 1: Bank 1
\li Bit 2 - See bit 0.
\li Bit 1 - See bit 0.
\li Bit 0 - Bits 0-2 indicate which of the 7 BKG colour palettes the tile is
assigned.
@see SHOW_BKG
@see set_bkg_data, set_bkg_submap
*/
void set_bkg_tiles(uint8_t x,
uint8_t y,
uint8_t w,
uint8_t h,
const uint8_t *tiles) NONBANKED __preserves_regs(b, c);
/** Sets a rectangular area of the Background Tile Map using a sub-region
from a source tile map. Useful for scrolling implementations of maps
larger than 32 x 32 tiles.
@param x X Start position in Background Map tile coordinates. Range 0 - 31
@param y Y Start position in Background Map tile coordinates. Range 0 - 31
@param w Width of area to set in tiles. Range 1 - 255
@param h Height of area to set in tiles. Range 1 - 255
@param map Pointer to source tile map data
@param map_w Width of source tile map in tiles. Range 1 - 255
Entries are copied from __map__ to the Background Tile Map starting at
__x__, __y__ writing across for __w__ tiles and down for __h__ tiles,
using __map_w__ as the rowstride for the source tile map.
Use this instead of @ref set_bkg_tiles when the source map is wider than
32 tiles or when writing a width that does not match the source map width.
One byte per source tile map entry.
Writes that exceed coordinate 31 on the x or y axis will wrap around to
the Left and Top edges.
See @ref set_bkg_tiles for setting CGB attribute maps with @ref VBK_REG.
@see SHOW_BKG
@see set_bkg_data, set_bkg_tiles, set_win_submap
*/
void set_bkg_submap(uint8_t x, uint8_t y, uint8_t w, uint8_t h, const uint8_t *map, uint8_t map_w);
/** Copies a rectangular region of Background Tile Map entries into a buffer.
@param x X Start position in Background Map tile coordinates. Range 0 - 31
@param y Y Start position in Background Map tile coordinates. Range 0 - 31
@param w Width of area to copy in tiles. Range 0 - 31
@param h Height of area to copy in tiles. Range 0 - 31
@param tiles Pointer to destination buffer for Tile Map data
Entries are copied into __tiles__ from the Background Tile Map starting at
__x__, __y__ reading across for __w__ tiles and down for __h__ tiles.
One byte per tile.
The buffer pointed to by __tiles__ should be at least __x__ x __y__ bytes in size.
*/
void get_bkg_tiles(uint8_t x,
uint8_t y,
uint8_t w,
uint8_t h,
uint8_t *tiles) NONBANKED __preserves_regs(b, c);
/**
* Set single tile t on background layer at x,y
* @param x X-coordinate
* @param y Y-coordinate
* @param t tile index
* @return returns the address of tile, so you may use faster set_vram_byte() later
*/
uint8_t * set_bkg_tile_xy(uint8_t x, uint8_t y, uint8_t t) __preserves_regs(b, c);
/**
* Get single tile t on background layer at x,y
* @param x X-coordinate
* @param y Y-coordinate
* @return returns tile index
*/
uint8_t get_bkg_tile_xy(uint8_t x, uint8_t y) __preserves_regs(b, c);
/** Moves the Background Layer to the position specified in __x__ and __y__ in pixels.
@param x X axis screen coordinate for Left edge of the Background
@param y Y axis screen coordinate for Top edge of the Background
0,0 is the top left corner of the GB screen. The Background Layer wraps around the screen,
so when part of it goes off the screen it appears on the opposite side (factoring in the
larger size of the Background Layer versus the screen size).
The background layer is always under the Window Layer.
@see SHOW_BKG, HIDE_BKG
*/
inline void move_bkg(uint8_t x, uint8_t y) {
SCX_REG=x, SCY_REG=y;
}
/** Moves the Background relative to it's current position.
@param x Number of pixels to move the Background on the __X axis__
\n Range: -128 - 127
@param y Number of pixels to move the Background on the __Y axis__
\n Range: -128 - 127
@see move_bkg
*/
inline void scroll_bkg(int8_t x, int8_t y) {
SCX_REG+=x, SCY_REG+=y;
}
/**
* Get address of X,Y tile of window map
*/
uint8_t * get_win_xy_addr(uint8_t x, uint8_t y) __preserves_regs(b, c);
/** Sets VRAM Tile Pattern data for the Window / Background
@param first_tile Index of the first tile to write
@param nb_tiles Number of tiles to write
@param data Pointer to (2 bpp) source Tile Pattern data.
This is the same as @ref set_bkg_data, since the Window Layer and
Background Layer share the same Tile pattern data.
@see set_bkg_data
@see set_win_tiles
@see SHOW_WIN, HIDE_WIN
*/
void set_win_data(uint8_t first_tile,
uint8_t nb_tiles,
const uint8_t *data) NONBANKED __preserves_regs(b, c);
/** Sets VRAM Tile Pattern data for the Window / Background using 1bpp source data
@param first_tile Index of the first tile to write
@param nb_tiles Number of tiles to write
@param data Pointer to (1bpp) source Tile Pattern data
This is the same as @ref set_bkg_1bit_data, since the Window Layer and
Background Layer share the same Tile pattern data.
@see set_bkg_data, set_bkg_1bit_data, set_win_data
*/
void set_win_1bit_data(uint8_t first_tile,
uint8_t nb_tiles,
const uint8_t *data) NONBANKED __preserves_regs(b, c);
/** Copies from Window / Background VRAM Tile Pattern data into a buffer
@param first_tile Index of the first Tile to read from
@param nb_tiles Number of Tiles to read
@param data Pointer to destination buffer for Tile Pattern Data
This is the same as @ref get_bkg_data, since the Window Layer and
Background Layer share the same Tile pattern data.
@see get_bkg_data
*/
void get_win_data(uint8_t first_tile,
uint8_t nb_tiles,
uint8_t *data) NONBANKED __preserves_regs(b, c);
/** Sets a rectangular region of the Window Tile Map.
@param x X Start position in Window Map tile coordinates. Range 0 - 31
@param y Y Start position in Window Map tile coordinates. Range 0 - 31
@param w Width of area to set in tiles. Range 1 - 32
@param h Height of area to set in tiles. Range 1 - 32
@param tiles Pointer to source tile map data
Entries are copied from map at __tiles__ to the Window Tile Map starting at
__x__, __y__ writing across for __w__ tiles and down for __h__ tiles.
Use @ref set_win_submap() instead when:
\li Source map is wider than 32 tiles.
\li Writing a width that does not match the source map width __and__ more
than one row high at a time.
One byte per source tile map entry.
Writes that exceed coordinate 31 on the x or y axis will wrap around to
the Left and Top edges.
Note: Patterns 128-255 overlap with patterns 128-255 of the sprite Tile Pattern table.
GBC only: @ref VBK_REG determines whether Tile Numbers or Tile Attributes get set.
\li VBK_REG=0 Tile Numbers are written
\li VBK_REG=1 Tile Attributes are written
For more details about GBC Tile Attributes see @ref set_bkg_tiles.
@see SHOW_WIN, HIDE_WIN, set_win_submap, set_bkg_tiles, set_bkg_data
*/
void set_win_tiles(uint8_t x,
uint8_t y,
uint8_t w,
uint8_t h,
const uint8_t *tiles) NONBANKED __preserves_regs(b, c);
/** Sets a rectangular area of the Window Tile Map using a sub-region
from a source tile map.
@param x X Start position in Window Map tile coordinates. Range 0 - 31
@param y Y Start position in Wimdpw Map tile coordinates. Range 0 - 31
@param w Width of area to set in tiles. Range 1 - 255
@param h Height of area to set in tiles. Range 1 - 255
@param map Pointer to source tile map data
@param map_w Width of source tile map in tiles. Range 1 - 255
Entries are copied from __map__ to the Window Tile Map starting at
__x__, __y__ writing across for __w__ tiles and down for __h__ tiles,
using __map_w__ as the rowstride for the source tile map.
Use this instead of @ref set_win_tiles when the source map is wider than
32 tiles or when writing a width that does not match the source map width.
One byte per source tile map entry.
Writes that exceed coordinate 31 on the x or y axis will wrap around to
the Left and Top edges.
GBC only: @ref VBK_REG determines whether Tile Numbers or Tile Attributes get set.
\li VBK_REG=0 Tile Numbers are written
\li VBK_REG=1 Tile Attributes are written
See @ref set_bkg_tiles for details about CGB attribute maps with @ref VBK_REG.
@see SHOW_WIN, HIDE_WIN, set_win_tiles, set_bkg_submap, set_bkg_tiles, set_bkg_data
**/
void set_win_submap(uint8_t x, uint8_t y, uint8_t w, uint8_t h, const uint8_t *map, uint8_t map_w);
/** Copies a rectangular region of Window Tile Map entries into a buffer.
@param x X Start position in Window Map tile coordinates. Range 0 - 31
@param y Y Start position in Window Map tile coordinates. Range 0 - 31
@param w Width of area to copy in tiles. Range 0 - 31
@param h Height of area to copy in tiles. Range 0 - 31
@param tiles Pointer to destination buffer for Tile Map data
Entries are copied into __tiles__ from the Window Tile Map starting at
__x__, __y__ reading across for __w__ tiles and down for __h__ tiles.
One byte per tile.
The buffer pointed to by __tiles__ should be at least __x__ x __y__ bytes in size.
*/
void get_win_tiles(uint8_t x,
uint8_t y,
uint8_t w,
uint8_t h,
uint8_t *tiles) NONBANKED __preserves_regs(b, c);
/**
* Set single tile t on window layer at x,y
* @param x X-coordinate
* @param y Y-coordinate
* @param t tile index
* @return returns the address of tile, so you may use faster set_vram_byte() later
*/
uint8_t * set_win_tile_xy(uint8_t x, uint8_t y, uint8_t t) __preserves_regs(b, c);
/**
* Get single tile t on window layer at x,y
* @param x X-coordinate
* @param y Y-coordinate
* @return returns the tile index
*/
uint8_t get_win_tile_xy(uint8_t x, uint8_t y) __preserves_regs(b, c);
/** Moves the Window to the __x__, __y__ position on the screen.
@param x X coordinate for Left edge of the Window (actual displayed location will be X - 7)
@param y Y coordinate for Top edge of the Window
7,0 is the top left corner of the screen in Window coordinates. The Window is locked to the bottom right corner.
The Window is always over the Background layer.
@see SHOW_WIN, HIDE_WIN
*/
inline void move_win(uint8_t x, uint8_t y) {
WX_REG=x, WY_REG=y;
}
/** Move the Window relative to its current position.
@param x Number of pixels to move the window on the __X axis__
\n Range: -128 - 127
@param y Number of pixels to move the window on the __Y axis__
\n Range: -128 - 127
@see move_win
*/
inline void scroll_win(int8_t x, int8_t y) {
WX_REG+=x, WY_REG+=y;
}
/** Sets VRAM Tile Pattern data for Sprites
@param first_tile Index of the first tile to write
@param nb_tiles Number of tiles to write
@param data Pointer to (2 bpp) source Tile Pattern data
Writes __nb_tiles__ tiles to VRAM starting at __first_tile__, tile data
is sourced from __data__. Each Tile is 16 bytes in size (8x8 pixels, 2 bits-per-pixel).
Note: Sprite Tiles 128-255 share the same memory region as Background Tiles 128-255.
GBC only: @ref VBK_REG determines which bank of Background tile patterns are written to.
\li VBK_REG=0 indicates the first bank
\li VBK_REG=1 indicates the second
*/
void set_sprite_data(uint8_t first_tile,
uint8_t nb_tiles,
const uint8_t *data) NONBANKED __preserves_regs(b, c);
/** Sets VRAM Tile Pattern data for Sprites using 1bpp source data
@param first_tile Index of the first tile to write
@param nb_tiles Number of tiles to write
@param data Pointer to (1bpp) source Tile Pattern data
Similar to @ref set_sprite_data, except source data is 1 bit-per-pixel
which gets expanded into 2 bits-per-pixel.
For a given bit that represent a pixel:
\li 0 will be expanded into color 0
\li 1 will be expanded into color 3
@see SHOW_SPRITES, HIDE_SPRITES, set_sprite_tile
*/
void set_sprite_1bit_data(uint8_t first_tile,
uint8_t nb_tiles,
const uint8_t *data) NONBANKED __preserves_regs(b, c);
/** Copies from Sprite VRAM Tile Pattern data into a buffer
@param first_tile Index of the first tile to read from
@param nb_tiles Number of tiles to read
@param data Pointer to destination buffer for Tile Pattern data
Copies __nb_tiles__ tiles from VRAM starting at __first_tile__, tile data
is copied into __data__.
Each Tile is 16 bytes, so the buffer pointed to by __data__
should be at least __nb_tiles__ x 16 bytes in size.
*/
void get_sprite_data(uint8_t first_tile,
uint8_t nb_tiles,
uint8_t *data) NONBANKED __preserves_regs(b, c);
/** Sprite Attributes structure
@param x X Coordinate of the sprite on screen
@param y Y Coordinate of the sprite on screen
@param tile Sprite tile number (see @ref set_sprite_tile)
@param prop OAM Property Flags (see @ref set_sprite_prop)
*/
typedef struct OAM_item_t {
uint8_t y, x; //< X, Y Coordinates of the sprite on screen
uint8_t tile; //< Sprite tile number
uint8_t prop; //< OAM Property Flags
} OAM_item_t;
/** Shadow OAM array in WRAM, that is DMA-transferred into the real OAM each VBlank
*/
extern volatile struct OAM_item_t shadow_OAM[];
/** MSB of shadow_OAM address is used by OAM DMA copying routine
*/
__REG _shadow_OAM_base;
/** Disable OAM DMA copy each VBlank
*/
#define DISABLE_OAM_DMA \
_shadow_OAM_base = 0
/** Enable OAM DMA copy each VBlank and set it to transfer default shadow_OAM array
*/
#define ENABLE_OAM_DMA \
_shadow_OAM_base = (uint8_t)((uint16_t)&shadow_OAM >> 8)
/** Enable OAM DMA copy each VBlank and set it to transfer any 256-byte aligned array
*/
inline void SET_SHADOW_OAM_ADDRESS(void * address) {
_shadow_OAM_base = (uint8_t)((uint16_t)address >> 8);
}
/** Sets sprite number __nb__in the OAM to display tile number __tile__.
@param nb Sprite number, range 0 - 39
@param tile Selects a tile (0 - 255) from memory at 8000h - 8FFFh
\n In CGB Mode this could be either in VRAM Bank
\n 0 or 1, depending on Bit 3 of the OAM Attribute Flag
\n (see @ref set_sprite_prop)
In 8x16 mode:
\li The sprite will also display the next tile (__tile__ + 1)
directly below (y + 8) the first tile.
\li The lower bit of the tile number is ignored:
the upper 8x8 tile is (__tile__ & 0xFE), and
the lower 8x8 tile is (__tile__ | 0x01).
\li See: @ref SPRITES_8x16
*/
inline void set_sprite_tile(uint8_t nb, uint8_t tile) {
shadow_OAM[nb].tile=tile;
}
/** Returns the tile number of sprite number __nb__ in the OAM.
@param nb Sprite number, range 0 - 39
@see set_sprite_tile for more details
*/
inline uint8_t get_sprite_tile(uint8_t nb) {
return shadow_OAM[nb].tile;
}
/** Sets the OAM Property Flags of sprite number __nb__ to those defined in __prop__.
@param nb Sprite number, range 0 - 39
@param prop Property setting (see bitfield description)
The bits in __prop__ represent:
\li Bit 7 - Priority flag. When this is set the sprites appear behind the
background and window layer.
\n 0: infront
\n 1: behind
\li Bit 6 - Vertical flip. Dictates which way up the sprite is drawn
vertically.
\n 0: normal
\n 1:upside down
\li Bit 5 - Horizontal flip. Dictates which way up the sprite is
drawn horizontally.
\n 0: normal
\n 1:back to front
\li Bit 4 - DMG/Non-CGB Mode Only. Assigns either one of the two b/w palettes to the sprite.
\n 0: OBJ palette 0
\n 1: OBJ palette 1
\li Bit 3 - GBC only. Dictates from which bank of Sprite Tile Patterns the tile
is taken.
\n 0: Bank 0
\n 1: Bank 1
\li Bit 2 - See bit 0.
\li Bit 1 - See bit 0.
\li Bit 0 - GBC only. Bits 0-2 indicate which of the 7 OBJ colour palettes the
sprite is assigned.
*/
inline void set_sprite_prop(uint8_t nb, uint8_t prop){
shadow_OAM[nb].prop=prop;
}
/** Returns the OAM Property Flags of sprite number __nb__.
@param nb Sprite number, range 0 - 39
@see set_sprite_prop for property bitfield settings
*/
inline uint8_t get_sprite_prop(uint8_t nb){
return shadow_OAM[nb].prop;
}
/** Moves sprite number __nb__ to the __x__, __y__ position on the screen.
@param nb Sprite number, range 0 - 39
@param x X Position. Specifies the sprites horizontal position on the screen (minus 8).
\n An offscreen value (X=0 or X>=168) hides the sprite, but the sprite
still affects the priority ordering - a better way to hide a sprite is to set
its Y-coordinate offscreen.
@param y Y Position. Specifies the sprites vertical position on the screen (minus 16).
\n An offscreen value (for example, Y=0 or Y>=160) hides the sprite.
Moving the sprite to 0,0 (or similar off-screen location) will hide it.
*/
inline void move_sprite(uint8_t nb, uint8_t x, uint8_t y) {
OAM_item_t * itm = &shadow_OAM[nb];
itm->y=y, itm->x=x;
}
/** Moves sprite number __nb__ relative to its current position.
@param nb Sprite number, range 0 - 39
@param x Number of pixels to move the sprite on the __X axis__
\n Range: -128 - 127
@param y Number of pixels to move the sprite on the __Y axis__
\n Range: -128 - 127
@see move_sprite for more details about the X and Y position
*/
inline void scroll_sprite(uint8_t nb, int8_t x, int8_t y) {
OAM_item_t * itm = &shadow_OAM[nb];
itm->y+=y, itm->x+=x;
}
/** Hides sprite number __nb__ by moving it to zero position by Y.
@param nb Sprite number, range 0 - 39
*/
inline void hide_sprite(uint8_t nb) {
shadow_OAM[nb].y = 0;
}
/** Copies Tile Pattern data to an address in VRAM
@param vram_addr Pointer to destination VRAM Address
@param data Pointer to source buffer
@param len Number of bytes to copy
Copies __len__ bytes from a buffer at __data__ to VRAM starting at __vram_addr__.
GBC only: @ref VBK_REG determines which bank of Background tile patterns are written to.
\li VBK_REG=0 indicates the first bank
\li VBK_REG=1 indicates the second
*/
void set_data(uint8_t *vram_addr,
const uint8_t *data,
uint16_t len) NONBANKED __preserves_regs(b, c);
/** Copies Tile Pattern data from an address in VRAM into a buffer
@param vram_addr Pointer to source VRAM Address
@param data Pointer to destination buffer
@param len Number of bytes to copy
Copies __len__ bytes from VRAM starting at __vram_addr__ into a buffer at __data__.
GBC only: @ref VBK_REG determines which bank of Background tile patterns are written to.
\li VBK_REG=0 indicates the first bank
\li VBK_REG=1 indicates the second
*/
void get_data(uint8_t *data,
uint8_t *vram_addr,
uint16_t len) NONBANKED __preserves_regs(b, c);
/** Sets a rectangular region of Tile Map entries at a given VRAM Address.
@param x X Start position in Map tile coordinates. Range 0 - 31
@param y Y Start position in Map tile coordinates. Range 0 - 31
@param w Width of area to set in tiles. Range 1 - 32
@param h Height of area to set in tiles. Range 1 - 32
@param vram_addr Pointer to destination VRAM Address
@param tiles Pointer to source Tile Map data
Entries are copied from __tiles__ to Tile Map at address vram_addr starting at
__x__, __y__ writing across for __w__ tiles and down for __h__ tiles.
One byte per source tile map entry.
There are two 32x32 Tile Maps in VRAM at addresses 9800h-9BFFh and 9C00h-9FFFh.
GBC only: @ref VBK_REG determines whether Tile Numbers or Tile Attributes get set.
\li VBK_REG=0 Tile Numbers are written
\li VBK_REG=1 Tile Attributes are written
*/
void set_tiles(uint8_t x,
uint8_t y,
uint8_t w,
uint8_t h,
uint8_t *vram_addr,
const uint8_t *tiles) NONBANKED __preserves_regs(b, c);
/** Sets VRAM Tile Pattern data starting from given base address
without taking into account the state of LCDC bit 4.
@param first_tile Index of the first tile to write
@param nb_tiles Number of tiles to write
@param data Pointer to (2 bpp) source Tile Pattern data.
@param base MSB of the destination address in VRAM (usually 0x80 or 0x90 which gives 0x8000 or 0x9000)
set_tile_data() allows to load tile data not taking into account LCDC bit 4 state
*/
void set_tile_data(uint8_t first_tile,
uint8_t nb_tiles,
const uint8_t *data,
uint8_t base) NONBANKED __preserves_regs(b, c);
/** Copies a rectangular region of Tile Map entries from a given VRAM Address into a buffer.
@param x X Start position in Background Map tile coordinates. Range 0 - 31
@param y Y Start position in Background Map tile coordinates. Range 0 - 31
@param w Width of area to copy in tiles. Range 0 - 31
@param h Height of area to copy in tiles. Range 0 - 31
@param vram_addr Pointer to source VRAM Address
@param tiles Pointer to destination buffer for Tile Map data
Entries are copied into __tiles__ from the Background Tile Map starting at
__x__, __y__ reading across for __w__ tiles and down for __h__ tiles.
One byte per tile.
There are two 32x32 Tile Maps in VRAM at addresses 9800h - 9BFFh and 9C00h - 9FFFh.
The buffer pointed to by __tiles__ should be at least __x__ x __y__ bytes in size.
*/
void get_tiles(uint8_t x,
uint8_t y,
uint8_t w,
uint8_t h,
uint8_t *vram_addr,
uint8_t *tiles) NONBANKED __preserves_regs(b, c);
/** Initializes the entire Window Tile Map with Tile Number __c__
@param c Tile number to fill with
Note: This function avoids writes during modes 2 & 3
*/
void init_win(uint8_t c) NONBANKED __preserves_regs(b, c);
/** Initializes the entire Background Tile Map with Tile Number __c__
@param c Tile number to fill with
Note: This function avoids writes during modes 2 & 3
*/
void init_bkg(uint8_t c) NONBANKED __preserves_regs(b, c);
/** Fills the VRAM memory region __s__ of size __n__ with Tile Number __c__
@param s Start address in VRAM
@param c Tile number to fill with
@param n Size of memory region (in bytes) to fill
Note: This function avoids writes during modes 2 & 3
*/
void vmemset (void *s, uint8_t c, size_t n) NONBANKED __preserves_regs(b, c);
/** Fills a rectangular region of Tile Map entries for the Background layer with tile.
@param x X Start position in Background Map tile coordinates. Range 0 - 31
@param y Y Start position in Background Map tile coordinates. Range 0 - 31
@param w Width of area to set in tiles. Range 0 - 31
@param h Height of area to set in tiles. Range 0 - 31
@param tile Fill value
*/
void fill_bkg_rect(uint8_t x, uint8_t y, uint8_t w, uint8_t h, uint8_t tile) NONBANKED __preserves_regs(b, c);
/** Fills a rectangular region of Tile Map entries for the Window layer with tile.
@param x X Start position in Window Map tile coordinates. Range 0 - 31
@param y Y Start position in Window Map tile coordinates. Range 0 - 31
@param w Width of area to set in tiles. Range 0 - 31
@param h Height of area to set in tiles. Range 0 - 31
@param tile Fill value
*/
void fill_win_rect(uint8_t x, uint8_t y, uint8_t w, uint8_t h, uint8_t tile) NONBANKED __preserves_regs(b, c);
#endif /* _GB_H */
|
RegenHo/XHNewsFrameworkExample
|
Project/XHNewsFrameworkExample/Views/HUAJIEBannerView.h
|
<filename>Project/XHNewsFrameworkExample/Views/HUAJIEBannerView.h
//
// HUAJIEBannerView.h
// HUAJIENewsiPhoneSDK
//
// Created by <NAME> on 14-3-16.
// Copyright (c) 2014年 曾宪华 QQ群: (142557668) QQ:543413507 Gmail:<EMAIL>. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface HUAJIEBannerView : UIView
@property (nonatomic, strong) UIImageView *focusImageView;
@end
|
44henry/matlab
|
matrix_computations/lchol_grad_sparse.c
|
<reponame>44henry/matlab
#include "mex.h"
#include "string.h"
#include "math.h"
/* TODO: THIS IMPLEMENTATION IS QUICK AND DIRTY, NOT OPTIMIZED NOR MADE EASY TO USE. */
int compare
(
const void * a,
const void * b
)
{
return (int)*(double*)a - (int)*(double*)b;
}
/*
* Cholesky decomposition and its derivative for a sparse matrix K.
* Decomposes the symmetric positive definite sparse matrix into a
* lower triangular matrix L and its derivatives dL.
*
* ind: The indices of the symbolic structure of L and dL. First index
* is zero.
*
* k: The values of matrix K for the indices.
*
* dk: The values of the derivative of K for the indices. This may
* contain several derivatives.
*
* length: The number of indices.
*
* d: The number of derivative vectors in dk.
*
* n: The dimensionality of the matrix K.
*/
int cholesky
(
double *array,
double *cols,
int length,
int D,
int N
)
{
int i, j, ind, jnd, ind_pivot, d, n;
double *item, key;
double *p, *k, *dk;
p = array;
k = array + length;
dk = array + 2*length;
ind = 0;
for (n=1; n<=N; n++) {
/* Check positive definiteness */
if (k[ind] <= 0.0)
return -2;
/* Define pivot */
k[ind] = sqrt(k[ind]);
for (d=0; d<D; d++) {
dk[ind+d*length] = 0.5 * dk[ind+d*length] / k[ind];
}
ind_pivot = ind;
/* Adjust lead column */
for (ind = ind_pivot+1; ind < length && p[ind] <= n*N; ind++) {
k[ind] = k[ind] / k[ind_pivot];
for (d=0; d<D; d++) {
dk[ind+d*length] = (dk[ind+d*length] - k[ind]*dk[ind_pivot+d*length]) / k[ind_pivot];
}
}
/* Row operations */
item = p+ind;
for (ind = ind_pivot+1; ind < length && p[ind] <= n*N; ind++) {
/* current row to column index */
i = ((int)(p[ind]-1) % N) + 1;
for (jnd = ind; jnd < length && p[jnd] <= n*N; jnd++) {
/* current row to row index */
j = ((int)(p[jnd]-1) % N) + 1;
/* find (j,i) from p using binary search */
key = (i-1)*N+j;
/*item = (double*)bsearch(&key, item+1, length-(item-p)-1, sizeof(double), compare);*/
item = (double*)bsearch(&key, p+(int)cols[i-1], cols[i]-cols[i-1], sizeof(double), compare);
/* item = (double*)bsearch(&key, p+jnd+1, length-jnd-1, sizeof(double), compare);*/
if (item==NULL)
return -1;
/*item = p+length-1;*/
*(item+length) = *(item+length) - k[ind]*k[jnd];
for (d=0; d<D; d++) {
*(item+(d+2)*length) = *(item+(d+2)*length) - dk[ind+d*length]*k[jnd] - dk[jnd+d*length]*k[ind];
}
}
}
}
return 0;
/*
for (i=0; i<length; i++) {
*(k+i) = *(k+i) + 1;
for (j=0; j<d; j++) {
*(dk+i+j*length) = *(dk+i+j*length) * (j+2);
}
}
*/
}
void mexFunction
(
int nout,
mxArray *pout[],
int nin,
const mxArray *pin[]
)
{
mwSize mrows, ncols;
double *x, *y, *cols;
int *p;
int N;
if (nin != 3)
mexErrMsgTxt("Three inputs required.");
if (nout != 1)
mexErrMsgTxt("One output required.");
mrows = mxGetM(pin[0]);
ncols = mxGetN(pin[0]);
/*pout[0] = pin[0];*/
pout[0] = mxCreateDoubleMatrix(mrows, ncols, mxREAL);
y = mxGetPr(pout[0]);
x = mxGetPr(pin[0]);
cols = mxGetPr(pin[1]);
memcpy(y, x, mrows*ncols*sizeof(double));
/*
p = malloc(mrows*sizeof(int));
for (int m=0; m<mrows; m++) {
p[m] = (int)x[m] - 1;
}
*/
N = (int)mxGetScalar(pin[2]);
int retval = cholesky(y, cols, mrows, ncols-2, N);
/*
int retval = cholesky(y, y+mrows, y+(2*mrows), mrows, ncols-2, N);
*/
/*free(p);*/
if (retval == -1)
mexErrMsgTxt("Symbolic structure not consistent.");
if (retval == -2)
mexErrMsgTxt("Matrix not positive definite.");
return;
}
|
ZJNixiang/HookZz
|
src/memory_manager.c
|
#include "memory_manager.h"
#include "core.h"
#include "std_kit/std_list.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* shared instance */
memory_manager_t *g_memory_manager = NULL;
memory_manager_t *memory_manager_cclass(shared_instance)() {
if (g_memory_manager == NULL) {
g_memory_manager = SAFE_MALLOC_TYPE(memory_manager_t);
g_memory_manager->code_caves = list_new();
g_memory_manager->free_memory_blocks = list_new();
g_memory_manager->process_memory_layout = list_new();
XCHECK(g_memory_manager != NULL);
}
return g_memory_manager;
}
CodeSlice *memory_manager_cclass(allocate_code_slice)(memory_manager_t *self, int size) {
CodeSlice *cs = NULL;
list_iterator_t *it = list_iterator_new(self->free_memory_blocks, LIST_HEAD);
for (int i = 0; i < self->free_memory_blocks->len; i++) {
FreeMemoryBlock *fmb = (FreeMemoryBlock *)(list_at(self->free_memory_blocks, i)->val);
if ((fmb->total_size - fmb->used_size) > size) {
cs = SAFE_MALLOC_TYPE(CodeSlice);
cs->data = (void *)(fmb->address + fmb->used_size);
cs->size = size;
fmb->used_size += size;
return cs;
}
}
// allocate a new page
if (cs == NULL) {
void *page_ptr = memory_manager_cclass(allocate_page)(self, PROT_R_X, 1);
FreeMemoryBlock *fmb = SAFE_MALLOC_TYPE(FreeMemoryBlock);
fmb->used_size = 0;
fmb->total_size = memory_manager_cclass(get_page_size)();
fmb->prot = PROT_R_X;
fmb->address = page_ptr;
list_rpush(self->free_memory_blocks, list_node_new(fmb));
cs = SAFE_MALLOC_TYPE(CodeSlice);
cs->data = (void *)(fmb->address + fmb->used_size);
cs->size = size;
fmb->used_size += size;
return cs;
}
return NULL;
}
void *search_dummy_code_cave(zz_addr_t search_start, zz_addr_t search_end, int size) {
assert(search_start);
assert(search_start < search_end);
zz_addr_t cur_addr = search_start;
unsigned char dummy_0[1024] = {0};
while (cur_addr < search_end) {
if (!memcmp((void *)cur_addr, dummy_0, size)) {
return (void *)cur_addr;
}
cur_addr += size;
}
return NULL;
}
CodeCave *memory_manager_cclass(search_code_cave)(memory_manager_t *self, void *address, int range, int size) {
CodeCave *cc = NULL;
zz_addr_t limit_start, limit_end;
zz_addr_t search_start, search_end;
limit_start = (zz_addr_t)address - range;
limit_end = (zz_addr_t)address + range - size;
list_iterator_t *it = list_iterator_new(self->free_memory_blocks, LIST_HEAD);
if (!self->process_memory_layout->len) {
memory_manager_cclass(get_process_memory_layout)(self);
}
for (int i = 0; i < self->process_memory_layout->len; i++) {
MemoryBlock *mb = (MemoryBlock *)(list_at(self->process_memory_layout, i)->val);
// fix top/bottom limit
search_start = (zz_addr_t)mb->address > limit_start ? (zz_addr_t)mb->address : limit_start;
search_end = ((zz_addr_t)mb->address + mb->size) < limit_end ? ((zz_addr_t)mb->address + mb->size) : limit_end;
// check `fixed`
if(search_start > search_end) {
continue;
}
void *p = search_dummy_code_cave(search_start, search_end, size);
if (p) {
cc = SAFE_MALLOC_TYPE(CodeCave);
cc->size = size;
cc->address = p;
return cc;
}
}
return NULL;
}
|
ZJNixiang/HookZz
|
srcxx/Platforms/arch-arm64/ARM64Writer.h
|
<reponame>ZJNixiang/HookZz
//
// Created by jmpews on 2018/6/14.
//
#ifndef HOOKZZ_ARM64WRITER_H
#define HOOKZZ_ARM64WRITER_H
#include "ARM64Register.h"
#include "Instruction.h"
#include <vector>
class ARM64Relocator;
class ARM64AssemblerWriter {
public:
void *start_pc;
void *start_address;
std::vector<ARM64InstructionCTX *> instCTXs;
std::vector<char> instBytes;
public:
ARM64AssemblerWriter(void *pc);
void reset(void *pc);
void PatchTo(void *target_address);
void putBytes(void *data, int dataSize);
void put_ldr_reg_imm(ARM64Reg reg, uint32_t offset) {
ARM64RegInfo ri;
DescribeARM64Reigster(reg, &ri);
uint32_t imm19, Rt;
imm19 = offset >> 2;
Rt = ri.index;
uint32_t inst = 0x58000000 | imm19 << 5 | Rt;
putBytes((void *)&inst, 4);
}
void put_str_reg_reg_offset(ARM64Reg src_reg, ARM64Reg dst_reg, uint64_t offset) {
ARM64RegInfo rs, rd;
DescribeARM64Reigster(src_reg, &rs);
DescribeARM64Reigster(dst_reg, &rd);
uint32_t size, v = 0, opc = 0, Rn_ndx, Rt_ndx;
Rn_ndx = rd.index;
Rt_ndx = rs.index;
if (rs.isInteger) {
size = (rs.width == 64) ? 0b11 : 0b10;
}
uint32_t imm12 = offset >> size;
uint32_t inst = 0x39000000 | size << 30 | opc << 22 | imm12 << 10 | Rn_ndx << 5 | Rt_ndx;
putBytes((void *)&inst, 4);
}
void put_ldr_reg_reg_offset(ARM64Reg dst_reg, ARM64Reg src_reg, uint64_t offset) {
ARM64RegInfo rs, rd;
DescribeARM64Reigster(src_reg, &rs);
DescribeARM64Reigster(dst_reg, &rd);
uint32_t size, v = 0, opc = 0b01, Rn_ndx, Rt_ndx;
Rn_ndx = rs.index;
Rt_ndx = rd.index;
if (rs.isInteger) {
size = (rs.width == 64) ? 0b11 : 0b10;
}
uint32_t imm12 = offset >> size;
uint32_t inst = 0x39000000 | size << 30 | opc << 22 | imm12 << 10 | Rn_ndx << 5 | Rt_ndx;
putBytes((void *)&inst, 4);
}
void put_br_reg(ARM64Reg reg) {
ARM64RegInfo ri;
DescribeARM64Reigster(reg, &ri);
uint32_t op = 0, Rn_ndx;
Rn_ndx = ri.index;
uint32_t inst = 0xd61f0000 | op << 21 | Rn_ndx << 5;
putBytes((void *)&inst, 4);
}
void put_blr_reg(ARM64Reg reg) {
ARM64RegInfo ri;
DescribeARM64Reigster(reg, &ri);
uint32_t op = 0b01, Rn_ndx;
Rn_ndx = ri.index;
uint32_t inst = 0xd63f0000 | op << 21 | Rn_ndx << 5;
putBytes((void *)&inst, 4);
}
void put_b_imm(uint64_t offset) {
uint32_t op = 0b0, imm26;
imm26 = (offset >> 2) & 0x03ffffff;
uint32_t inst = 0x14000000 | op << 31 | imm26;
putBytes((void *)&inst, 4);
}
};
#endif //HOOKZZ_ARM64WRITER_H
|
ZJNixiang/HookZz
|
src/logging.h
|
#ifndef logging_h
#define logging_h
#define COMMON_LOG(fmt, ...) \
do { \
fprintf(stdout, fmt "\n", __VA_ARGS__); \
} while (0)
#define COMMON_LOG_STR(MSG) COMMON_LOG("%s", MSG)
#if defined(X_LOG) && X_LOG
#if defined(__ANDROID__)
#include <android/log.h>
#define Logging(fmt, ...) \
do { \
__android_log_print(ANDROID_LOG_INFO, "HookZz", fmt, __VA_ARGS__); \
} while (0);
#else
#define Logging(fmt, ...) \
do { \
COMMON_LOG(fmt, __VA_ARGS__); \
} while (0);
#endif
#else
#define Logging(fmt, ...)
#endif
#endif
|
ZJNixiang/HookZz
|
src/platforms/backend-posix/memory-helper-posix.h
|
#ifndef platforms_backend_darwin_memory_helper_linux_h
#define platforms_backend_darwin_memory_helper_linux_h
#include "core.h"
#include <sys/mman.h>
#include <unistd.h>
#define posix_memory_helper_cclass(member) cclass(posix_memory_helper, member)
int posix_memory_helper_cclass(get_page_size)();
void *posix_memory_helper_cclass(allocate_page)(int prot, int n);
void posix_memory_helper_cclass(patch_code)(void *dest, void *src, int count);
void posix_memory_helper_cclass(set_page_permission)(void *page_address, int prot, int n);
#endif
|
ZJNixiang/HookZz
|
src/std_kit/std_map.h
|
/**
* Copyright (c) 2014 rxi
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MIT license. See LICENSE for details.
*/
#ifndef MAP_H
#define MAP_H
#include <string.h>
#define MAP_VERSION "0.1.0"
typedef union {
int _int;
float _float;
double _double;
void *_pointer;
} map_value_t;
typedef struct _map_node_t {
unsigned hash;
map_value_t value;
struct _map_node_t *next;
} map_node_t;
typedef struct {
map_node_t **buckets;
unsigned nbuckets;
unsigned nnodes;
} map_base_t, map_t;
typedef struct {
unsigned bucket_index;
map_node_t *node_next;
} map_iter_t;
map_base_t *map_new();
void map_destory(map_base_t *m);
map_value_t map_get_value(map_base_t *m, const char *key);
int map_set_value(map_base_t *m, const char *key, map_value_t value);
void map_remove_value(map_base_t *m, const char *key);
map_iter_t map_iter_new(void);
map_node_t *map_iter_next(map_base_t *m, map_iter_t *iter);
#endif
|
ZJNixiang/HookZz
|
srcxx/Platforms/arch-arm64/Instruction.h
|
//
// Created by jmpews on 2018/6/14.
//
#ifndef HOOKZZ_INSTRUCTION_H
#define HOOKZZ_INSTRUCTION_H
#include "hookzz.h"
typedef struct _ARM64InstructionCTX {
zz_addr_t pc;
zz_addr_t address;
uint8_t size;
uint32_t bytes;
} ARM64InstructionCTX;
#endif //HOOKZZ_INSTRUCTION_H
|
ZJNixiang/HookZz
|
src/std_kit/std_kit.c
|
#include "std_kit.h"
void *safe_malloc(size_t size) {
if (size <= 0) {
ERROR_LOG("[!] malloc with size %ld", size);
return NULL;
}
void *data = (void *)malloc(size);
if (!data) {
ERROR_LOG_STR("[!] malloc return NULL !!!");
return data;
}
memset(data, 0, size);
return data;
}
|
ZJNixiang/HookZz
|
src/platforms/backend-arm/closure-bridge-arm.h
|
<gh_stars>1-10
/**
* Copyright 2017 jmpews
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef platforms_backend_arm_bridge_arm
#define platforms_backend_arm_bridge_arm
#include <stdint.h>
#define PRIAVE
#ifndef REGISTER_STATE_STRUCT
#define REGISTER_STATE_STRUCT
#if defined(__arm64__) || defined(__aarch64__)
typedef union _FPReg {
__int128_t q;
struct {
double d1;
double d2;
} d;
struct {
float f1;
float f2;
float f3;
float f4;
} f;
} FPReg;
typedef struct _RegState {
uint64_t dmmpy_0;
union {
uint64_t x[29];
struct {
uint64_t x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21,
x22, x23, x24, x25, x26, x27, x28;
} regs;
} general;
uint64_t fp;
uint64_t lr;
union {
FPReg q[8];
struct {
FPReg q0, q1, q2, q3, q4, q5, q6, q7;
} regs;
} floating;
} RegState;
#elif defined(__arm__)
typedef struct _RegState {
uint32_t dummy_0;
uint32_t dummy_1;
union {
uint32_t r[13];
struct {
uint32_t r0, r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12;
} regs;
} general;
uint32_t lr;
} RegState;
#elif defined(__i386__)
typedef struct _RegState {
} RegState;
#elif defined(__x86_64__)
typedef struct _RegState {
} RegState;
#endif
#endif
typedef struct _ClosureBridgeData {
void *user_code;
void *user_data;
void *redirect_trampoline;
} ClosureBridgeInfo;
typedef struct _ClosureBridgeTrampolineTable {
void *entry;
void *trampoline_page;
uint16_t used_count;
uint16_t free_count;
struct _ClosureBridgeTrampolineTable *prev;
struct _ClosureBridgeTrampolineTable *next;
} ClosureBridgeTrampolineTable;
typedef void (*USER_CODE_CALL)(RegState *rs, ClosureBridgeInfo *cb_info);
ClosureBridgeInfo *ClosureBridgeAllocate(void *user_data, void *user_code);
void closure_bridge_trampoline_template();
void closure_bridge_template();
#endif
|
ZJNixiang/HookZz
|
src/interceptor.c
|
<reponame>ZJNixiang/HookZz
#include <stdlib.h>
#include <string.h>
#include "core.h"
#include "interceptor.h"
#include "memory_manager.h"
#include "std_kit/std_list.h"
interceptor_t *g_interceptor = NULL;
interceptor_t *interceptor_cclass(shared_instance)(void) {
if (g_interceptor == NULL) {
g_interceptor = SAFE_MALLOC_TYPE(interceptor_t);
g_interceptor->hook_entries = list_new();
g_interceptor->memory_manager = memory_manager_cclass(shared_instance)();
}
return g_interceptor;
}
hook_entry_t *interceptor_cclass(find_hook_entry)(interceptor_t *self, void *target_address) {
if (!self)
self = interceptor_cclass(shared_instance)();
list_iterator_t *it = list_iterator_new(self->hook_entries, LIST_HEAD);
for (int i = 0; i < self->hook_entries->len; i++) {
hook_entry_t *entry = (hook_entry_t *)(list_at(self->hook_entries, i)->val);
if (entry->target_address == target_address) {
return entry;
}
}
return NULL;
}
void interceptor_cclass(add_hook_entry)(interceptor_t *self, hook_entry_t *entry) {
list_rpush(self->hook_entries, list_node_new(entry));
return;
}
|
ZJNixiang/HookZz
|
srcxx/Platforms/arch-arm64/custom-bridge-handler-arm64.h
|
<gh_stars>1-10
//
// Created by z on 2018/4/7.
//
#ifndef CUSTOM_BRIDGE_HANDLER_H
#define CUSTOM_BRIDGE_HANDLER_H
#include "ClosureBridge.h"
#include "hookzz.h"
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
void dynamic_common_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcbInfo);
void common_bridge_handler(RegState *rs, ClosureBridgeInfo *cbInfo);
void dynamic_context_begin_invocation_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcbInfo);
void dynamic_context_end_invocation_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcbInfo);
void context_end_invocation_bridge_handler(RegState *rs, ClosureBridgeInfo *cbInfo);
void context_begin_invocation_bridge_handler(RegState *rs, ClosureBridgeInfo *cbInfo);
void dynamic_binary_instrumentationn_bridge_handler(RegState *rs, ClosureBridgeInfo *cbInfo);
#ifdef __cplusplus
}
#endif //__cplusplus
#endif //CUSTOM_BRIDGE_HANDLER_H
|
ZJNixiang/HookZz
|
src/platforms/backend-x86/closure-bridge-x86.c
|
#include "closure-bridge-x86.h"
#include "backend-x86-helper.h"
#include <string.h>
#include <CommonKit/log/log_kit.h>
#include <sys/mman.h>
#include <unistd.h>
#define closure_bridge_trampoline_template_length (7 * 4)
static ClosureBridgeTrampolineTable *gClosureBridageTrampolineTable = NULL;
void common_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info) {}
static ClosureBridgeTrampolineTable *ClosureBridgeTrampolineTableAllocate(void) { return NULL; }
static void ClosureBridgeTrampolineTableFree(ClosureBridgeTrampolineTable *table) { return; }
ClosureBridgeInfo *ClosureBridgeAllocate(void *user_data, void *user_code) { return NULL; }
static void ClosureBridgeFree(ClosureBridgeInfo *bridgeData) { return; }
|
ZJNixiang/HookZz
|
src/platforms/backend-darwin/memory-manager-darwin.c
|
<reponame>ZJNixiang/HookZz<gh_stars>1-10
#include <errno.h>
#include <mach-o/dyld.h>
#include <mach/mach.h>
#include <mach/vm_map.h>
#include <sys/mman.h>
#include "core.h"
#include "mach_vm.h"
#include "memory-helper-darwin.h"
#include "memory_manager.h"
extern void __clear_cache(void *beg, void *end);
PLATFORM_API bool memory_manager_cclass(is_support_allocate_rx_memory)(memory_manager_t *self) { return true; }
PLATFORM_API void memory_manager_cclass(get_process_memory_layout)(memory_manager_t *self) {
mach_msg_type_number_t count;
struct vm_region_submap_info_64 info;
vm_size_t nesting_depth;
kern_return_t kr = KERN_SUCCESS;
vm_address_t tmp_addr = 0;
vm_size_t tmp_size = 0;
while (1) {
count = VM_REGION_SUBMAP_INFO_COUNT_64;
kr = vm_region_recurse_64(mach_task_self(), &tmp_addr, &tmp_size, (natural_t *)&nesting_depth,
(vm_region_info_64_t)&info, &count);
if (kr == KERN_INVALID_ADDRESS) {
break;
} else if (kr) {
mach_error("vm_region:", kr);
break; /* last region done */
}
if (info.is_submap) {
nesting_depth++;
} else {
MemoryBlock *mb = SAFE_MALLOC_TYPE(MemoryBlock);
list_rpush(self->process_memory_layout, list_node_new(mb));
tmp_addr += tmp_size;
mb->address = (void *)((zz_addr_t)tmp_addr - tmp_size);
mb->size = tmp_size;
mb->prot = info.protection;
}
}
}
#if !USE_POSIX_IN_DARWIN
PLATFORM_API int memory_manager_cclass(get_page_size)() {
int page_size = darwin_memory_helper_cclass(get_page_size)();
return page_size;
}
#endif
#if !USE_POSIX_IN_DARWIN
PLATFORM_API void memory_manager_cclass(set_page_permission)(void *page_address, int prot, int n) {
darwin_memory_helper_cclass(set_page_permission)(page_address, prot, n);
return;
}
#endif
#if !USE_POSIX_IN_DARWIN
PLATFORM_API void *memory_manager_cclass(allocate_page)(memory_manager_t *self, int prot, int n) {
vm_address_t page_address;
kern_return_t kr;
vm_size_t page_size;
page_size = darwin_memory_helper_cclass(get_page_size)();
/* use vm_allocate not mmap */
kr = mach_vm_allocate(mach_task_self(), (mach_vm_address_t *)&page_address, page_size * n, VM_FLAGS_ANYWHERE);
/* set page permission */
darwin_memory_helper_cclass(set_page_permission)((void *)page_address, prot, n);
return (void *)page_address;
}
#endif
#if !USE_POSIX_IN_DARWIN
/*
REF:
substitute/lib/darwin/execmem.c:execmem_foreign_write_with_pc_patch
frida-gum-master/gum/gummemory.c:gum_memory_patch_code
frida-gum-master/gum/backend-darwin/gummemory-darwin.c:gum_alloc_n_pages
mach mmap use __vm_allocate and __vm_map
https://github.com/bminor/glibc/blob/master/sysdeps/mach/hurd/mmap.c
https://github.com/bminor/glibc/blob/master/sysdeps/mach/munmap.c
http://shakthimaan.com/downloads/hurd/A.Programmers.Guide.to.the.Mach.System.Calls.pdf
*/
PLATFORM_API void memory_manager_cclass(patch_code)(memory_manager_t *self, void *dest, void *src, int count) {
vm_address_t dest_page;
vm_size_t offset;
int page_size = memory_manager_cclass(get_page_size)();
// https://www.gnu.org/software/hurd/gnumach-doc/Memory-Attributes.html
dest_page = (zz_addr_t)dest & ~(page_size - 1);
offset = (zz_addr_t)dest - dest_page;
vm_prot_t prot;
vm_inherit_t inherit;
kern_return_t kr;
mach_port_t task_self = mach_task_self();
darwin_memory_helper_cclass(get_memory_info)((void *)dest_page, &prot, &inherit);
// For another method, pelease read `REF`;
// zz_ptr_t code_mmap = mmap(NULL, range_size, PROT_READ | PROT_WRITE,
// MAP_ANON | MAP_SHARED, -1, 0);
// if (code_mmap == MAP_FAILED) {
// return;
// }
void *copy_page = memory_manager_cclass(allocate_page)(self, PROT_RW_, 1);
kr = vm_copy(task_self, (vm_address_t)dest_page, page_size, (vm_address_t)copy_page);
if (kr != KERN_SUCCESS) {
ERROR_LOG_STR("[[memory_manager_cclass(patch_code)]]");
return;
}
memcpy((void *)((zz_addr_t)copy_page + offset), src, count);
// SAME: mprotect(code_mmap, range_size, prot);
darwin_memory_helper_cclass(set_page_permission)(copy_page, PROT_R_X, 1);
// TODO: need check `memory region` again.
// // if only with this, `memory region` is `r-x`
// vm_protect((vm_map_t)mach_task_self(), 0x00000001816b2030, 16, FALSE, 0x13);
// // and with this, `memory region` is `rwx`
// *(char *)0x00000001816b01a8 = 'a';
mach_vm_address_t target_address = (vm_address_t)dest_page;
vm_prot_t cur_protection, max_protection;
kr = mach_vm_remap(task_self, &target_address, page_size, 0, VM_FLAGS_OVERWRITE, task_self,
(mach_vm_address_t)copy_page,
/*copy*/ TRUE, &cur_protection, &max_protection, inherit);
__clear_cache((void *)dest, (void *)((uintptr_t)dest + count));
if (kr != KERN_SUCCESS) {
ERROR_LOG_STR("[[memory_manager_cclass(patch_code)]]");
// LOG-NEED
}
// read `REF`
// munmap(code_mmap, range_size);
kr = mach_vm_deallocate(task_self, (mach_vm_address_t)copy_page, page_size);
if (kr != KERN_SUCCESS) {
ERROR_LOG_STR("[[memory_manager_cclass(patch_code)]]");
}
}
#endif
|
ZJNixiang/HookZz
|
src/interceptor_routing.h
|
<filename>src/interceptor_routing.h
#ifndef interceptor_routing_h
#define interceptor_routing_h
#include "closure_bridge.h"
#include "core.h"
#include "hookzz.h"
#include "interceptor.h"
ARCH_API void *get_ret_addr_PTR(RegState *rs);
ARCH_API void *get_next_hop_addr_PTR(RegState *rs);
ARCH_API void *get_current_fp_reg();
void interceptor_routing_begin(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR, void *ret_addr_PTR);
void interceptor_routing_end(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR);
void interceptor_routing_dynamic_binary_instrumentation(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR);
void interceptor_routing_begin_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info);
void interceptor_routing_end_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info);
void interceptor_routing_dynamic_binary_instrumentation_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info);
void interceptor_routing_common_bridge_handler(RegState *rs, ClosureBridgeInfo *cb_info);
#if DYNAMIC_CLOSURE_BRIDGE
void interceptor_routing_begin_dynamic_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcb_info);
void interceptor_routing_end_dynamic_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcb_info);
void interceptor_routing_dynamic_common_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcb_info);
#endif
#endif
|
ZJNixiang/HookZz
|
src/interceptor.h
|
<reponame>ZJNixiang/HookZz
#ifndef interceptor_h
#define interceptor_h
#include "core.h"
#include "hookzz.h"
#include "memory_manager.h"
typedef struct _FunctionBackup {
void *address;
int size;
char data[32];
} FunctionBackup;
struct _interceptor_t;
struct _hook_entry_backend_t;
typedef struct _hook_entry_t {
void *target_address;
HookType type;
uintptr_t id;
bool is_enable;
bool is_try_near_jump;
bool is_near_jump;
PRECALL pre_call;
POSTCALL post_call;
DBICALL dbi_call;
void *replace_call;
void *on_enter_transfer_trampoline;
void *on_enter_trampoline;
void *on_invoke_trampoline;
void *on_leave_trampoline;
void *on_dynamic_binary_instrumentation_trampoline;
FunctionBackup origin_prologue;
struct _hook_entry_backend_t *backend;
struct _interceptor_t *interceptor;
} hook_entry_t;
struct _interceptor_backend_t;
typedef struct _interceptor_t {
bool is_support_rx_memory;
list_t *hook_entries;
struct _interceptor_backend_t *interceptor_backend;
memory_manager_t *memory_manager;
} interceptor_t;
#define interceptor_cclass(member) cclass(interceptor, member)
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
interceptor_t *interceptor_cclass(shared_instance)(void);
hook_entry_t *interceptor_cclass(find_hook_entry)(interceptor_t *self, void *target_address);
void interceptor_cclass(add_hook_entry)(interceptor_t *self, hook_entry_t *entry);
void interceptor_cclass(initialize_interceptor_backend)();
#ifdef __cplusplus
}
#endif //__cplusplus
#endif
|
ZJNixiang/HookZz
|
src/platforms/backend-arm/interceptor-arm.h
|
#ifndef platforms_backend_arm_intercetor_arm
#define platforms_backend_arm_intercetor_arm
#include "hookzz.h"
#include "zkit.h"
#include "interceptor.h"
#include "memory.h"
#include "platforms/arch-arm/relocator-arm.h"
#include "platforms/arch-arm/relocator-thumb.h"
#include "platforms/arch-arm/writer-arm.h"
#include "platforms/arch-arm/writer-thumb.h"
// (next_hop_addr_PTR + general_regs + sp)
#define CTX_SAVE_STACK_OFFSET (4 * 14)
typedef struct _InterceptorBackend {
ExecuteMemoryManager *emm;
ARMRelocator arm_relocator;
ThumbRelocator thumb_relocator;
ARMAssemblerWriter arm_writer;
ThumbAssemblerWriter thumb_writer;
ARMReader arm_reader;
ARMReader thumb_reader;
zz_ptr_t enter_bridge;
zz_ptr_t leave_bridge;
zz_ptr_t dynamic_binary_instrumentation_bridge;
} InterceptorBackend;
typedef struct _ARMHookFuntionEntryBackend {
bool is_thumb;
zz_size_t redirect_code_size;
} ARMHookEntryBackend;
#endif
|
ZJNixiang/HookZz
|
srcxx/Trampoline.h
|
//
// Created by z on 2018/6/14.
//
#ifndef HOOKZZ_TRAMPOLINE_H
#define HOOKZZ_TRAMPOLINE_H
class Trampoline {};
#endif //HOOKZZ_TRAMPOLINE_H
|
ZJNixiang/HookZz
|
src/memory_manager.h
|
#ifndef memory_allocator_h
#define memory_allocator_h
#include "core.h"
#include "hookzz.h"
#include "std_kit/std_list.h"
#include <stdint.h>
// memory permission prot
#define PROT_RW_ (1 | 2)
#define PROT_R_X (1 | 4)
typedef struct _CodeSlice {
void *data;
int size;
} CodeSlice;
typedef struct _CodeCave {
int size;
void *backup;
void *address;
} CodeCave;
typedef struct _MemoryBlock {
int prot; // memory permission
int size;
void *address;
} MemoryBlock;
typedef struct _FreeMemoryBlock {
int prot; // memory permission
int total_size;
int used_size;
void *address;
} FreeMemoryBlock;
typedef struct _memory_manager_t {
bool is_support_rx_memory;
list_t *code_caves;
list_t *process_memory_layout;
list_t *free_memory_blocks;
} memory_manager_t;
#define memory_manager_cclass(member) cclass(memory_manager, member)
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
memory_manager_t *memory_manager_cclass(shared_instance)();
PLATFORM_API int memory_manager_cclass(get_page_size)();
PLATFORM_API void memory_manager_cclass(set_page_permission)(void *page_address, int prot, int n);
PLATFORM_API bool memory_manager_cclass(is_support_allocate_rx_memory)(memory_manager_t *self);
PLATFORM_API void *memory_manager_cclass(allocate_page)(memory_manager_t *self, int prot, int n);
PLATFORM_API void memory_manager_cclass(patch_code)(memory_manager_t *self, void *dest, void *src, int count);
PLATFORM_API void memory_manager_cclass(get_process_memory_layout)(memory_manager_t *self);
CodeCave *memory_manager_cclass(search_code_cave)(memory_manager_t *self, void *address, int range, int size);
CodeSlice *memory_manager_cclass(allocate_code_slice)(memory_manager_t *self, int size);
#ifdef __cplusplus
}
#endif //__cplusplus
#endif
|
ZJNixiang/HookZz
|
srcxx/Platforms/arch-arm64/ARM64Reader.h
|
//
// Created by jmpews on 2018/6/14.
//
#ifndef HOOKZZ_READERARM64_H
#define HOOKZZ_READERARM64_H
#include "ARM64AssemblyCore.h"
#include "Instruction.h"
#include "hookzz.h"
#include <istream>
#include <streambuf>
#include <vector>
class ARM64AssemblyReader {
public:
void *start_pc;
void *start_address;
std::vector<ARM64InstructionCTX *> instCTXs;
std::vector<char> instBytes;
public:
ARM64AssemblyReader(void *address, void *pc);
void reset(void *address, void *pc);
ARM64InstructionCTX *readInstruction();
};
#endif //HOOKZZ_READERARM64_H
|
ZJNixiang/HookZz
|
src/platforms/arch-arm64/relocator-arm64.c
|
#include "relocator-arm64.h"
#include "ARM64AssemblyCore.h"
#include "std_kit/std_kit.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>
ARM64Relocator *arm64_assembly_relocator_cclass(new)(ARM64AssemblyReader *input, ARM64AssemblyWriter *output) {
ARM64Relocator *relocator = SAFE_MALLOC_TYPE(ARM64Relocator);
relocator->input = input;
relocator->output = output;
relocator->io_indexs = list_new();
relocator->literal_instCTXs = list_new();
return relocator;
}
void arm64_assembly_relocator_cclass(reset)(ARM64Relocator *self, ARM64AssemblyReader *input, ARM64AssemblyWriter *output) {
arm64_assembly_reader_reset(self->input, 0, 0);
arm64_assembly_writer_reset(self->output, 0);
list_destroy(self->literal_instCTXs);
self->literal_instCTXs = list_new();
list_destroy(self->io_indexs);
self->io_indexs = list_new();
}
void arm64_assembly_relocator_cclass(try_relocate)(void *address, int bytes_min, int *bytes_max) {
int tmp_size = 0;
bool early_end = false;
ARM64InstructionCTX *instCTX = NULL;
ARM64AssemblyReader *reader = arm64_assembly_reader_cclass(new)(address, address);
do {
instCTX = arm64_assembly_reader_cclass(read_inst)(reader);
switch (getInstType(instCTX->bytes)) {
case BImm:
early_end = true;
break;
default:;
}
tmp_size += instCTX->size;
} while (tmp_size < bytes_min);
if (early_end) {
*bytes_max = bytes_min;
}
// TODO: free ARM64AssemblyReader
SAFE_FREE(reader);
}
void arm64_assembly_relocator_cclass(relocate_to)(ARM64Relocator *self, void *target_address) {
list_iterator_t *it = list_iterator_new(self->literal_instCTXs, LIST_HEAD);
for (int i; i < self->literal_instCTXs->len; i++) {
ARM64InstructionCTX *instCTX = (ARM64InstructionCTX *)(list_at(self->literal_instCTXs, i)->val);
zz_addr_t literal_target_address;
literal_target_address = *(zz_addr_t *)instCTX->address;
if (literal_target_address > (zz_addr_t)self->input->start_pc &&
literal_target_address < ((zz_addr_t)self->input->start_pc + self->input->inst_bytes->size)) {
list_iterator_t *it_a = list_iterator_new(self->io_indexs, LIST_HEAD);
for (int j; j < self->io_indexs->len; j++) {
io_index_t *io_index = (io_index_t *)(list_at(self->io_indexs, j)->val);
int i_index = io_index->input_index;
int o_index = io_index->output_index;
ARM64InstructionCTX *inputInstCTX =
(ARM64InstructionCTX *)(list_at(self->input->instCTXs, i_index)->val);
ARM64InstructionCTX *outputInstCTX =
(ARM64InstructionCTX *)(list_at(self->output->instCTXs, o_index)->val);
if (inputInstCTX->address == literal_target_address) {
*(zz_addr_t *)instCTX->address =
((ARM64InstructionCTX *)(list_at(self->output->instCTXs, o_index)->val))->pc -
(zz_addr_t)self->output->start_pc + (zz_addr_t)target_address;
break;
}
}
}
}
}
void arm64_assembly_relocator_cclass(double_write)(ARM64Relocator *self, void *target_address) {
assert((zz_addr_t)target_address % 4 == 0);
int origin_inst_buffer_size = self->output->inst_bytes->size;
// temporary store inst buffer
void *tmp_inst_buffer = (void *)malloc(self->output->inst_bytes->size);
memcpy(tmp_inst_buffer, self->output->inst_bytes->data, self->output->inst_bytes->size);
arm64_assembly_writer_cclass(reset)(self->output, target_address);
arm64_assembly_relocator_cclass(reset)(self, self->input, self->output);
arm64_assembly_relocator_cclass(relocate_write_all)(self);
void *no_need_relocate_inst_buffer =
(void *)((zz_addr_t)tmp_inst_buffer + self->output->inst_bytes->size);
arm64_assembly_writer_cclass(put_bytes)(self->output, no_need_relocate_inst_buffer,
origin_inst_buffer_size - self->output->inst_bytes->size);
}
void arm64_assembly_relocator_cclass(register_literal_instCTX)(ARM64Relocator *self, ARM64InstructionCTX *instCTX) {
list_rpush(self->literal_instCTXs, list_node_new(instCTX));
}
void arm64_assembly_relocator_cclass(relocate_write_all)(ARM64Relocator *self) {
do {
arm64_assembly_relocator_cclass(relocate_write)(self);
} while (self->io_indexs->len < self->input->instCTXs->len);
}
void arm64_assembly_relocator_cclass(relocate_write)(ARM64Relocator *self) {
ARM64InstructionCTX *instCTX = NULL;
bool rewritten = true;
int done_relocated_input_count;
done_relocated_input_count = self->io_indexs->len;
if (self->input->instCTXs->len > self->io_indexs->len) {
instCTX = (ARM64InstructionCTX *)(list_at(self->input->instCTXs, done_relocated_input_count)->val);
} else
return;
// push relocate input <-> output index
io_index_t *io_index = SAFE_MALLOC_TYPE(io_index_t);
io_index->input_index = done_relocated_input_count;
io_index->output_index = self->output->instCTXs->len;
list_rpush(self->io_indexs, list_node_new(io_index));
switch (getInstType(instCTX->bytes)) {
case LoadLiteral:
arm64_assembly_relocator_cclass(rewrite_LoadLiteral)(self, instCTX);
break;
case BaseCmpBranch:
arm64_assembly_relocator_cclass(rewrite_BaseCmpBranch)(self, instCTX);
break;
case BranchCond:
arm64_assembly_relocator_cclass(rewrite_BranchCond)(self, instCTX);
break;
case B:
arm64_assembly_relocator_cclass(rewrite_B)(self, instCTX);
break;
case BL:
arm64_assembly_relocator_cclass(rewrite_BL)(self, instCTX);
break;
default:
rewritten = false;
break;
}
if (!rewritten) {
arm64_assembly_writer_cclass(put_bytes)(self->output, (void *)&instCTX->bytes, instCTX->size);
}
}
void arm64_assembly_relocator_cclass(rewrite_LoadLiteral)(ARM64Relocator *self, ARM64InstructionCTX *instCTX) {
uint32_t Rt, label;
int index;
zz_addr_t target_address;
Rt = get_insn_sub(instCTX->bytes, 0, 5);
label = get_insn_sub(instCTX->bytes, 5, 19);
target_address = (label << 2) + instCTX->pc;
ARM64Reg regRt = arm64_register_disdescribe(Rt, 0);
arm64_assembly_writer_cclass(put_ldr_reg_imm)(self->output, regRt, 0x8);
arm64_assembly_writer_cclass(put_b_imm)(self->output, 0xc);
arm64_assembly_writer_cclass(put_bytes)(self->output, (zz_ptr_t)&target_address, sizeof(target_address));
arm64_assembly_relocator_cclass(register_literal_instCTX)(
self, (ARM64InstructionCTX *)(list_at(self->output->instCTXs, self->output->instCTXs->len - 1))->val);
arm64_assembly_writer_cclass(put_ldr_reg_reg_offset)(self->output, regRt, regRt, 0);
}
void arm64_assembly_relocator_cclass(rewrite_BaseCmpBranch)(ARM64Relocator *self, ARM64InstructionCTX *instCTX) {
uint32_t target;
uint32_t inst32;
zz_addr_t target_address;
inst32 = instCTX->bytes;
target = get_insn_sub(inst32, 5, 19);
target_address = (target << 2) + instCTX->pc;
target = 0x8 >> 2;
BIT32SET(&inst32, 5, 19, target);
arm64_assembly_writer_cclass(put_bytes)(self->output, &inst32, instCTX->size);
arm64_assembly_writer_cclass(put_b_imm)(self->output, 0x14);
arm64_assembly_writer_cclass(put_ldr_reg_imm)(self->output, ARM64_REG_X17, 0x8);
arm64_assembly_writer_cclass(put_br_reg)(self->output, ARM64_REG_X17);
arm64_assembly_writer_cclass(put_bytes)(self->output, (zz_ptr_t)&target_address, sizeof(zz_ptr_t));
arm64_assembly_relocator_cclass(register_literal_instCTX)(
self, (ARM64InstructionCTX *)(list_at(self->output->instCTXs, self->output->instCTXs->len - 1))->val);
}
void arm64_assembly_relocator_cclass(rewrite_BranchCond)(ARM64Relocator *self, ARM64InstructionCTX *instCTX) {
uint32_t target;
uint32_t inst32;
zz_addr_t target_address;
inst32 = instCTX->bytes;
target = get_insn_sub(inst32, 5, 19);
target_address = (target << 2) + instCTX->pc;
target = 0x8 >> 2;
BIT32SET(&inst32, 5, 19, target);
arm64_assembly_writer_cclass(put_bytes)(self->output, &inst32, instCTX->size);
arm64_assembly_writer_cclass(put_b_imm)(self->output, 0x14);
arm64_assembly_writer_cclass(put_ldr_reg_imm)(self->output, ARM64_REG_X17, 0x8);
arm64_assembly_writer_cclass(put_br_reg)(self->output, ARM64_REG_X17);
arm64_assembly_writer_cclass(put_bytes)(self->output, (zz_ptr_t)&target_address, sizeof(zz_ptr_t));
arm64_assembly_relocator_cclass(register_literal_instCTX)(
self, (ARM64InstructionCTX *)(list_at(self->output->instCTXs, self->output->instCTXs->len - 1))->val);
}
void arm64_assembly_relocator_cclass(rewrite_B)(ARM64Relocator *self, ARM64InstructionCTX *instCTX) {
uint32_t addr;
zz_addr_t target_address;
addr = get_insn_sub(instCTX->bytes, 0, 26);
target_address = (addr << 2) + instCTX->pc;
arm64_assembly_writer_cclass(put_ldr_reg_imm)(self->output, ARM64_REG_X17, 0x8);
arm64_assembly_writer_cclass(put_br_reg)(self->output, ARM64_REG_X17);
arm64_assembly_writer_cclass(put_bytes)(self->output, (zz_ptr_t)&target_address, sizeof(zz_ptr_t));
arm64_assembly_relocator_cclass(register_literal_instCTX)(
self, (ARM64InstructionCTX *)(list_at(self->output->instCTXs, self->output->instCTXs->len - 1))->val);
}
void arm64_assembly_relocator_cclass(rewrite_BL)(ARM64Relocator *self, ARM64InstructionCTX *instCTX) {
uint32_t op, addr;
zz_addr_t target_address, next_pc_address;
addr = get_insn_sub(instCTX->bytes, 0, 26);
target_address = (addr << 2) + instCTX->pc;
next_pc_address = instCTX->pc + 4;
arm64_assembly_writer_cclass(put_ldr_reg_imm)(self->output, ARM64_REG_X17, 0xc);
arm64_assembly_writer_cclass(put_blr_reg)(self->output, ARM64_REG_X17);
arm64_assembly_writer_cclass(put_b_imm)(self->output, 0xc);
arm64_assembly_writer_cclass(put_bytes)(self->output, (zz_ptr_t)&target_address, sizeof(zz_ptr_t));
arm64_assembly_relocator_cclass(register_literal_instCTX)(
self, (ARM64InstructionCTX *)(list_at(self->output->instCTXs, self->output->instCTXs->len - 1))->val);
}
|
ZJNixiang/HookZz
|
srcxx/ThreadManager.h
|
//
// Created by jmpews on 2018/6/14.
//
#ifndef HOOKZZ_THREADMANAGER_H
#define HOOKZZ_THREADMANAGER_H
#include "CommonClass/DesignPattern/Singleton.h"
#include <iostream>
#include <vector>
typedef struct _ThreadLocalKey {
pthread_key_t key;
} ThreadLocalKey;
class ThreadManager : public Singleton<ThreadManager> {
public:
std::vector<ThreadLocalKey *> thread_local_keys;
public:
ThreadLocalKey *allocateThreadLocalKey();
void setThreadLocalData(ThreadLocalKey *thread_local_key, void *);
void *getThreadLocalData(ThreadLocalKey *thread_local_key);
};
#endif //HOOKZZ_THREADMANAGER_H
|
ZJNixiang/HookZz
|
srcxx/InterceptorRoutingTrampoline.h
|
//
// Created by jmpews on 2018/6/15.
//
#ifndef HOOKZZ_INTERCEPTORBACKEND_H
#define HOOKZZ_INTERCEPTORBACKEND_H
#include "Interceptor.h"
class InterceptorRoutingTrampoline {
public:
virtual void Prepare(HookEntry *entry){};
virtual void BuildForEnterTransfer(HookEntry *entry){};
virtual void BuildForEnter(HookEntry *entry){};
virtual void BuildForDynamicBinaryInstrumentation(HookEntry *entry){};
virtual void BuildForLeave(HookEntry *entry){};
virtual void BuildForInvoke(HookEntry *entry){};
virtual void Active(HookEntry *entry){};
void BuildAll(HookEntry *entry);
};
#endif //HOOKZZ_INTERCEPTORBACKEND_H
|
ZJNixiang/HookZz
|
srcxx/CommonClass/DesignPattern/Singleton.h
|
<gh_stars>1-10
//
// Created by jmpews on 2018/6/14.
//
#ifndef HOOKZZ_SINGLETON_H
#define HOOKZZ_SINGLETON_H
#include <pthread.h>
template <typename T> class Singleton {
private:
static T *_instance;
public:
static T *GetInstance();
};
template <typename T> T *Singleton<T>::_instance = NULL;
template <typename T> T *Singleton<T>::GetInstance() {
if (_instance == NULL) {
_instance = new T();
}
return _instance;
}
#endif //HOOKZZ_SINGLETON_H
|
ZJNixiang/HookZz
|
src/platforms/backend-posix/memory-helper-posix.c
|
<gh_stars>1-10
#include "memory-helper-posix.h"
#include "core.h"
#include "hookzz.h"
#include "memory_manager.h"
#include <sys/mman.h>
extern void __clear_cache(void *beg, void *end);
void posix_memory_helper_cclass(set_page_permission)(void *page_address, int prot, int n) {
int page_size = posix_memory_helper_cclass(get_page_size)();
int r;
r = mprotect((zz_ptr_t)page_address, page_size * n, prot);
if (r == -1) {
ERROR_LOG("r = %d, at (%p) error!", r, (zz_ptr_t)page_address);
return;
}
return;
}
int posix_memory_helper_cclass(get_page_size)() {
int page_size = sysconf(_SC_PAGESIZE);
return page_size;
}
void *posix_memory_helper_cclass(allocate_page)(int prot, int n) {
int page_size = posix_memory_helper_cclass(get_page_size)();
void *mmap_page = mmap(0, 1, PROT_WRITE | PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
mprotect(mmap_page, (size_t)page_size, prot);
return mmap_page;
}
/*
ref:
substitute/lib/darwin/execmem.c:execmem_foreign_write_with_pc_patch
frida-gum-master/gum/gummemory.c:gum_memory_patch_code
frida-gum-master/gum/backend-darwin/gummemory-darwin.c:gum_alloc_n_pages
mach mmap use __vm_allocate and __vm_map
https://github.com/bminor/glibc/blob/master/sysdeps/mach/hurd/mmap.c
https://github.com/bminor/glibc/blob/master/sysdeps/mach/munmap.c
http://shakthimaan.com/downloads/hurd/A.Programmers.Guide.to.the.Mach.System.Calls.pdf
*/
void posix_memory_helper_cclass(patch_code)(void *dest, void *src, int count) {
void *dest_page = NULL;
int offset = 0;
int page_size = posix_memory_helper_cclass(get_page_size)();
// https://www.gnu.org/software/hurd/gnumach-doc/Memory-Attributes.html
dest_page = (void *)((zz_addr_t)dest & ~(page_size - 1));
offset = (zz_addr_t)dest - (zz_addr_t)dest_page;
// another method, pelease read `REF`;
// zz_ptr_t code_mmap = mmap(NULL, range_size, PROT_READ | PROT_WRITE,
// MAP_ANON | MAP_SHARED, -1, 0);
// if (code_mmap == MAP_FAILED) {
// return;
// }
void *copy_page = posix_memory_helper_cclass(allocate_page)(PROT_RW_, 1);
memcpy(copy_page, (void *)dest_page, page_size);
memcpy((void *)((zz_addr_t)copy_page + offset), src, count);
/* SAME: mprotect(code_mmap, range_size, prot); */
posix_memory_helper_cclass(set_page_permission)(dest_page, PROT_WRITE | PROT_READ | PROT_EXEC, 1);
memcpy(dest_page, copy_page, page_size);
posix_memory_helper_cclass(set_page_permission)(dest_page, PROT_EXEC | PROT_READ, 1);
#if 0
// why not working ???
// posix_memory_helper_cclass(set_page_permission)(copy_page, PROT_EXEC | PROT_READ, 1);
// void *remap_page = mremap(copy_page, page_size, page_size, MREMAP_MAYMOVE|MREMAP_FIXED, dest_page);
// if(remap_page == MAP_FAILED) {
// ERROR_LOG("r = %d, at (%p) error!", 0, (zz_ptr_t)remap_page);
// return;
// }
#endif
__clear_cache((void *)dest, (void *)((uintptr_t)dest + count));
// TODO
munmap(copy_page, page_size);
return;
}
|
ZJNixiang/HookZz
|
src/platforms/arch-arm64/register-arm64.c
|
<reponame>ZJNixiang/HookZz<filename>src/platforms/arch-arm64/register-arm64.c
#include "register-arm64.h"
#include "std_kit/std_kit.h"
#include <string.h>
void arm64_register_describe(ARM64Reg reg, ARM64RegInfo *ri) {
if (reg >= ARM64_REG_X0 && reg <= ARM64_REG_X28) {
ri->is_integer = true;
ri->width = 64;
ri->meta = ARM64_REG_X0 + (reg - ARM64_REG_X0);
} else if (reg == ARM64_REG_X29 || reg == ARM64_REG_FP) {
ri->is_integer = true;
ri->width = 64;
ri->meta = ARM64_REG_X29;
} else if (reg == ARM64_REG_X30 || reg == ARM64_REG_LR) {
ri->is_integer = true;
ri->width = 64;
ri->meta = ARM64_REG_X30;
} else if (reg == ARM64_REG_SP) {
ri->is_integer = true;
ri->width = 64;
ri->meta = ARM64_REG_X31;
} else {
ri->index = 0;
ERROR_LOG_STR("arm64_register_describe error.");
}
ri->index = ri->meta - ARM64_REG_X0;
}
ARM64Reg arm64_register_disdescribe(int index, int width) {
if (width == 0)
width = 64;
return (ARM64Reg)(index - (int)ARM64_REG_X0);
}
|
ZJNixiang/HookZz
|
srcxx/Macros.h
|
<gh_stars>1-10
//
// Created by jmpews on 2018/6/15.
//
#ifndef HOOKZZ_MACROS_H
#define HOOKZZ_MACROS_H
#include <stdint.h>
#define INT5_MASK 0x0000001f
#define INT8_MASK 0x000000ff
#define INT10_MASK 0x000003ff
#define INT11_MASK 0x000007ff
#define INT12_MASK 0x00000fff
#define INT14_MASK 0x00003fff
#define INT16_MASK 0x0000ffff
#define INT18_MASK 0x0003ffff
#define INT19_MASK 0x0007ffff
#define INT24_MASK 0x00ffffff
#define INT26_MASK 0x03ffffff
#define INT28_MASK 0x0fffffff
#define THUMB_FUNCTION_ADDRESS(address) ((uintptr_t)address & ~(uintptr_t)1)
#define INSTRUCTION_IS_THUMB(insn_addr) (((uintptr_t)insn_addr & 0x1) == 0x1)
#define ALIGN_FLOOR(address, range) ((uintptr_t)address & ~((uintptr_t)range - 1))
#define ALIGN_CEIL(address, range) (((uintptr_t)address + (uintptr_t)range - 1) & ~((uintptr_t)range - 1))
#endif //HOOKZZ_MACROS_H
|
ZJNixiang/HookZz
|
src/platforms/arch-arm64/writer-arm64.c
|
<filename>src/platforms/arch-arm64/writer-arm64.c
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include "memory_manager.h"
#include "writer-arm64.h"
inline void ReadBytes(void *data, void *address, int length) { memcpy(data, address, length); }
ARM64AssemblyWriter *arm64_assembly_writer_cclass(new)(void *pc) {
ARM64AssemblyWriter *writer = SAFE_MALLOC_TYPE(ARM64AssemblyWriter);
writer->start_pc = pc;
writer->instCTXs = list_new();
writer->inst_bytes = buffer_array_create(64);
return writer;
}
void arm64_assembly_writer_cclass(destory)(ARM64AssemblyWriter *self) {}
void arm64_assembly_writer_cclass(reset)(ARM64AssemblyWriter *self, void *pc) {
self->start_pc = pc;
list_destroy(self->instCTXs);
self->instCTXs = list_new();
buffer_array_clear(self->inst_bytes);
return;
}
void arm64_assembly_writer_cclass(patch_to)(ARM64AssemblyWriter *self, void *target_address) {
self->start_address = target_address;
memory_manager_t *memory_manager;
memory_manager = memory_manager_cclass(shared_instance)();
memory_manager_cclass(patch_code)(memory_manager, target_address, self->inst_bytes->data, self->inst_bytes->size);
return;
}
size_t arm64_assembly_writer_cclass(bxxx_range)() { return ((1 << 23) << 2); }
#define ARM64_INST_SIZE 4
void arm64_assembly_writer_cclass(put_bytes)(ARM64AssemblyWriter *self, void *data, int length) {
assert(length % 4 == 0);
for (int i = 0; i < (length / ARM64_INST_SIZE); i++) {
ARM64InstructionCTX *instCTX = SAFE_MALLOC_TYPE(ARM64InstructionCTX);
instCTX->pc = (zz_addr_t)self->start_pc + self->inst_bytes->size;
instCTX->address = (zz_addr_t)self->inst_bytes->data + self->inst_bytes->size;
instCTX->size = ARM64_INST_SIZE;
ReadBytes(&instCTX->bytes, (void *)((zz_addr_t)data + ARM64_INST_SIZE * i), ARM64_INST_SIZE);
buffer_array_put(self->inst_bytes, (void *)((zz_addr_t)data + ARM64_INST_SIZE * i), ARM64_INST_SIZE);
list_rpush(self->instCTXs, list_node_new(instCTX));
}
}
void arm64_assembly_writer_cclass(put_ldr_reg_imm)(ARM64AssemblyWriter *self, ARM64Reg reg, uint32_t offset) {
ARM64RegInfo ri;
arm64_register_describe(reg, &ri);
uint32_t imm19, Rt;
imm19 = offset >> 2;
Rt = ri.index;
uint32_t inst = 0x58000000 | imm19 << 5 | Rt;
arm64_assembly_writer_cclass(put_bytes)(self, (void *)&inst, 4);
}
void arm64_assembly_writer_cclass(put_str_reg_reg_offset)(ARM64AssemblyWriter *self, ARM64Reg src_reg,
ARM64Reg dest_reg, uint64_t offset) {
ARM64RegInfo rs, rd;
arm64_register_describe(src_reg, &rs);
arm64_register_describe(dest_reg, &rd);
uint32_t size, v = 0, opc = 0, Rn_ndx, Rt_ndx;
Rn_ndx = rd.index;
Rt_ndx = rs.index;
if (rs.is_integer) {
size = (rs.width == 64) ? 0b11 : 0b10;
}
uint32_t imm12 = offset >> size;
uint32_t inst = 0x39000000 | size << 30 | opc << 22 | imm12 << 10 | Rn_ndx << 5 | Rt_ndx;
arm64_assembly_writer_cclass(put_bytes)(self, (void *)&inst, 4);
}
void arm64_assembly_writer_cclass(put_ldr_reg_reg_offset)(ARM64AssemblyWriter *self, ARM64Reg dest_reg,
ARM64Reg src_reg, uint64_t offset) {
ARM64RegInfo rs, rd;
arm64_register_describe(src_reg, &rs);
arm64_register_describe(dest_reg, &rd);
uint32_t size, v = 0, opc = 0b01, Rn_ndx, Rt_ndx;
Rn_ndx = rs.index;
Rt_ndx = rd.index;
if (rs.is_integer) {
size = (rs.width == 64) ? 0b11 : 0b10;
}
uint32_t imm12 = offset >> size;
uint32_t inst = 0x39000000 | size << 30 | opc << 22 | imm12 << 10 | Rn_ndx << 5 | Rt_ndx;
arm64_assembly_writer_cclass(put_bytes)(self, (void *)&inst, 4);
}
void arm64_assembly_writer_cclass(put_br_reg)(ARM64AssemblyWriter *self, ARM64Reg reg) {
ARM64RegInfo ri;
arm64_register_describe(reg, &ri);
uint32_t op = 0, Rn_ndx;
Rn_ndx = ri.index;
uint32_t inst = 0xd61f0000 | op << 21 | Rn_ndx << 5;
arm64_assembly_writer_cclass(put_bytes)(self, (void *)&inst, 4);
}
void arm64_assembly_writer_cclass(put_blr_reg)(ARM64AssemblyWriter *self, ARM64Reg reg) {
ARM64RegInfo ri;
arm64_register_describe(reg, &ri);
uint32_t op = 0b01, Rn_ndx;
Rn_ndx = ri.index;
uint32_t inst = 0xd63f0000 | op << 21 | Rn_ndx << 5;
arm64_assembly_writer_cclass(put_bytes)(self, (void *)&inst, 4);
}
void arm64_assembly_writer_cclass(put_b_imm)(ARM64AssemblyWriter *self, uint64_t offset) {
uint32_t op = 0b0, imm26;
imm26 = (offset >> 2) & 0x03ffffff;
uint32_t inst = 0x14000000 | op << 31 | imm26;
arm64_assembly_writer_cclass(put_bytes)(self, (void *)&inst, 4);
}
|
ZJNixiang/HookZz
|
src/platforms/arch-arm64/reader-arm64.c
|
<gh_stars>1-10
#include "reader-arm64.h"
#include "std_kit/std_kit.h"
#include <string.h>
inline void ReadBytes(void *data, void *address, int length);
void ReadBytes(void *data, void *address, int length) { memcpy(data, address, length); }
ARM64AssemblyReader *arm64_assembly_reader_cclass(new)(void *address, void *pc) {
ARM64AssemblyReader *reader = SAFE_MALLOC_TYPE(ARM64AssemblyReader);
reader->start_address = address;
reader->start_pc = pc;
reader->instCTXs = list_new();
reader->inst_bytes = buffer_array_create(64);
return reader;
}
void arm64_assembly_reader_cclass(reset)(ARM64AssemblyReader *self, void *address, void *pc) {
self->start_address = address;
self->start_pc = pc;
list_destroy(self->instCTXs);
self->instCTXs = list_new();
buffer_array_clear(self->inst_bytes);
return;
}
ARM64InstructionCTX *arm64_assembly_reader_cclass(read_inst)(ARM64AssemblyReader *self) {
ARM64InstructionCTX *instCTX = SAFE_MALLOC_TYPE(ARM64InstructionCTX);
instCTX->pc = (zz_addr_t)self->start_pc + self->inst_bytes->size;
instCTX->address = (zz_addr_t)self->start_address + self->inst_bytes->size;
instCTX->size = 4;
ReadBytes((void *)&instCTX->bytes, (void *)instCTX->address, 4);
buffer_array_put(self->inst_bytes, (void *)instCTX->address, 4);
list_rpush(self->instCTXs, list_node_new(instCTX));
return instCTX;
}
|
ZJNixiang/HookZz
|
src/platforms/arch-arm64/closure-bridge-arm64.c
|
#include "closure_bridge.h"
#include "core.h"
#include "memory_manager.h"
#define closure_bridge_trampoline_template_length (7 * 4)
void ClosureBridgeCClass(InitializeTablePage)(ClosureBridgeTrampolineTable *table, void *page_address) {
memory_manager_t *memory_manager = memory_manager_cclass(shared_instance)();
memory_manager_cclass(set_page_permission)(page_address, PROT_RW_, 1);
int page_size = memory_manager_cclass(get_page_size)();
int t = page_size / closure_bridge_trampoline_template_length;
void *copy_address = page_address;
for (int i = 0; i < t; ++i) {
copy_address = (void *)((intptr_t)page_address + i * closure_bridge_trampoline_template_length);
memcpy(copy_address, (void *)closure_bridge_trampoline_template, closure_bridge_trampoline_template_length);
}
memory_manager_cclass(set_page_permission)(page_address, PROT_R_X, 1);
table->entry = page_address;
table->trampoline_page = page_address;
table->used_count = 0;
table->free_count = (uint16_t)t;
}
void ClosureBridgeCClass(InitializeClosureBridgeInfo)(ClosureBridgeTrampolineTable *table, ClosureBridgeInfo *cb_info,
void *user_data, void *user_code) {
assert(cb_info);
assert(table);
uint16_t trampoline_used_count = table->used_count;
void *redirect_trampoline =
(void *)((intptr_t)table->trampoline_page + closure_bridge_trampoline_template_length * trampoline_used_count);
cb_info->user_code = user_code;
cb_info->user_data = user_data;
cb_info->redirect_trampoline = redirect_trampoline;
table->used_count++;
table->free_count--;
memory_manager_cclass(set_page_permission)(table->trampoline_page, PROT_RW_, 1);
// bind data to trampline
void *tmp = (void *)((intptr_t)cb_info->redirect_trampoline + 4 * 3);
memcpy(tmp, &cb_info, sizeof(ClosureBridgeInfo *));
// set trampoline to bridge
void *tmpX = (void *)closure_bridge_template;
tmp = (void *)((intptr_t)cb_info->redirect_trampoline + 4 * 5);
memcpy(tmp, &tmpX, sizeof(void *));
memory_manager_cclass(set_page_permission)(table->trampoline_page, PROT_R_X, 1);
}
|
ZJNixiang/HookZz
|
srcxx/Platforms/backend-darwin/DarwinDynamicClosureBridge.h
|
<reponame>ZJNixiang/HookZz<filename>srcxx/Platforms/backend-darwin/DarwinDynamicClosureBridge.h
//
// Created by jmpews on 2018/6/15.
//
#ifndef HOOKZZ_DARWINDYNAMICCLOSUREBRIDGE_H
#define HOOKZZ_DARWINDYNAMICCLOSUREBRIDGE_H
#endif //HOOKZZ_DARWINDYNAMICCLOSUREBRIDGE_H
|
ZJNixiang/HookZz
|
src/platforms/arch-arm64/arch-arm64.c
|
#include "hookzz.h"
#include "arch-arm64.h"
void *get_next_hop_addr_PTR(RegState *rs) {
void *next_hop_addr_PTR = (void *)&rs->general.regs.x15;
return next_hop_addr_PTR;
}
void *get_ret_addr_PTR(RegState *rs) {
void *ret_addr_PTR = (void *)&rs->lr;
return ret_addr_PTR;
}
void *get_current_fp_reg() {
void *fp_reg;
xASM("mov %[fp_reg], fp" : [fp_reg] "=r"(fp_reg) :);
return fp_reg;
}
|
ZJNixiang/HookZz
|
srcxx/Platforms/backend-darwin/DarwinMemoryManager.h
|
//
// Created by jmpews on 2018/6/14.
//
#ifndef HOOKZZ_DARWINMEMORYMANAGER_H
#define HOOKZZ_DARWINMEMORYMANAGER_H
#include "MemoryManager.h"
#endif //HOOKZZ_DARWINMEMORYMANAGER_H
|
ZJNixiang/HookZz
|
srcxx/Platforms/arch-arm64/ARM64Relocator.h
|
//
// Created by jmpews on 2018/6/14.
//
#ifndef HOOKZZ_ARM64RELOCATOR_H
#define HOOKZZ_ARM64RELOCATOR_H
#include "ARM64Reader.h"
#include "ARM64Writer.h"
#include "Instruction.h"
#include <iostream>
#include <map>
#include <vector>
class ARM64Relocator {
public:
int limitRelocateInstSize;
int relocatedInstSize;
int needRelocateInputCount;
int doneRelocateInputCount;
ARM64AssemblerWriter *output;
ARM64AssemblyReader *input;
// memory patch can't confirm the code slice length, so last setp of memory patch need repair the literal instruction.
std::vector<ARM64InstructionCTX *> literalInstCTXs;
std::map<int, int> indexRelocatedInputOutput;
public:
ARM64Relocator(ARM64AssemblyReader *input, ARM64AssemblerWriter *output);
void reset();
void tryRelocate(void *address, int bytes_min, int *bytes_max);
void relocateTo(void *target_address);
void doubleWrite(void *target_address);
void registerLiteralInstCTX(ARM64InstructionCTX *instCTX);
void relocateWrite();
void relocateWriteAll();
void rewrite_LoadLiteral(ARM64InstructionCTX *instCTX);
void rewrite_BaseCmpBranch(ARM64InstructionCTX *instCTX);
void rewrite_BranchCond(ARM64InstructionCTX *instCTX);
void rewrite_B(ARM64InstructionCTX *instCTX);
void rewrite_BL(ARM64InstructionCTX *instCTX);
};
#endif //HOOKZZ_ARM64RELOCATOR_H
|
ZJNixiang/HookZz
|
src/platforms/arch-arm64/instruction.c
|
<reponame>ZJNixiang/HookZz
#include "instruction.h"
#include <stdint.h>
#include <string.h>
uint32_t get_insn_sub(uint32_t insn, int start, int length) { return (insn >> start) & ((1 << length) - 1); }
|
ZJNixiang/HookZz
|
src/platforms/backend-posix/thread-local-storage-posix.c
|
<reponame>ZJNixiang/HookZz<gh_stars>1-10
#include "thread_local_storage.h"
#ifndef thread_local
#include <pthread.h>
static pthread_key_t _thread_variable_key = 0;
void *get_thread_variable_value() {
if (!_thread_variable_key)
return NULL;
void *value = pthread_getspecific(_thread_variable_key);
return value;
}
void set_thread_variable_value(void *value) {
if (!_thread_variable_key) {
int err = pthread_key_create(&_thread_variable_key, NULL);
assert(err == 0);
}
int err = pthread_setspecific(flagKey, value);
assert(err == 0);
}
#endif
|
ZJNixiang/HookZz
|
srcxx/Platforms/backend-posix/PosixClosureBridge.h
|
<filename>srcxx/Platforms/backend-posix/PosixClosureBridge.h
//
// Created by jmpews on 2018/6/14.
//
#ifndef HOOKZZ_POSIXCLOSUREBRIDGE_H
#define HOOKZZ_POSIXCLOSUREBRIDGE_H
#include "ClosureBridge.h"
#include "PosixClosureBridge.h"
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#endif //HOOKZZ_POSIXCLOSUREBRIDGE_H
|
ZJNixiang/HookZz
|
srcxx/MemoryManager.h
|
//
// Created by z on 2018/6/14.
//
#ifndef HOOKZZ_MEMORYMANAGER_H
#define HOOKZZ_MEMORYMANAGER_H
#include <iostream>
#include <stdint.h>
#include <vector>
#include "CommonClass/DesignPattern/Singleton.h"
#include "hookzz.h"
typedef enum _MemoryAttribute { MEM_RX } MemoryAttribute;
typedef struct _CodeSlice {
void *data;
int size;
} CodeSlice;
typedef struct _CodeCave {
int size;
void *backup;
zz_addr_t address;
} CodeCave;
typedef struct _MemoryBlock {
int prot; // memory permission
int size;
zz_addr_t address;
} MemoryBlock;
typedef struct _FreeMemoryBlock {
int prot; // memory permission
int total_size;
int used_size;
zz_addr_t address;
} FreeMemoryBlock;
class MemoryManager {
public:
bool is_support_rx_memory;
std::vector<CodeCave *> code_caves;
std::vector<MemoryBlock *> process_memory_layout;
std::vector<FreeMemoryBlock *> free_memory_blocks;
public:
static bool IsSupportRXMemory();
static int GetPageSize();
void patchCode(void *dest, void *src, int count);
void *allocateMemoryPage(MemoryAttribute prot, int n);
void getProcessMemoryLayout();
CodeSlice *allocateCodeSlice(int size);
CodeCave *searchCodeCave(void *address, int range, int need_size);
};
#endif //HOOKZZ_MEMORYMANAGER_H
|
ZJNixiang/HookZz
|
srcxx/Platforms/arch-arm64/ARM64InterceptorRoutingTrampoline.h
|
<filename>srcxx/Platforms/arch-arm64/ARM64InterceptorRoutingTrampoline.h
//
// Created by jmpews on 2018/6/14.
//
#ifndef HOOKZZ_ARM64INTERCEPTOR_H
#define HOOKZZ_ARM64INTERCEPTOR_H
#include "ARM64Reader.h"
#include "ARM64Relocator.h"
#include "ARM64Writer.h"
#include "Interceptor.h"
#include "InterceptorRoutingTrampoline.h"
#include "MemoryManager.h"
class ARM64InterceptorRoutingTrampoline : public InterceptorRoutingTrampoline {
public:
MemoryManager *memory_manager;
ARM64Relocator *relocatorARM64;
ARM64AssemblerWriter *writerARM64;
ARM64AssemblyReader *readerARM64;
public:
void Prepare(HookEntry *entry);
void BuildForEnterTransfer(HookEntry *entry);
void BuildForEnter(HookEntry *entry);
void BuildForDynamicBinaryInstrumentation(HookEntry *entry);
void BuildForLeave(HookEntry *entry);
void BuildForInvoke(HookEntry *entry);
void ActiveTrampoline(HookEntry *entry);
};
typedef struct _ARM64HookFuntionEntryBackend {
int limit_relocate_inst_size;
} ARM64HookEntryBackend;
#endif //HOOKZZ_INTERCEPTORARM64_H
|
ZJNixiang/HookZz
|
src/logging.c
|
<reponame>ZJNixiang/HookZz<gh_stars>1-10
#include "logging.h"
|
ZJNixiang/HookZz
|
src/platforms/arch-arm64/arch-arm64.h
|
<reponame>ZJNixiang/HookZz
#define xASM(x) __asm(x)
#if 0
#undef get_current_fp_reg
#define get_current_fp_reg(fp_reg) xASM("mov %[fp_reg], fp" : [fp_reg] "=r"(fp_reg) :);
#endif
|
ZJNixiang/HookZz
|
srcxx/StackManager.h
|
//
// Created by jmpews on 2018/6/14.
//
#ifndef HOOKZZ_STACKMANAGER_H
#define HOOKZZ_STACKMANAGER_H
#include <map>
#include "hookzz.h"
#include "ThreadManager.h"
typedef struct _CallStackEntry {
char *key;
void *value;
} CallStackEntry;
class ThreadStackManager;
class CallStackManager {
public:
int id;
class ThreadStackManager *thread_stack;
zz_ptr_t retAddr;
std::map<char *, void *> kv_map;
public:
void setCallStackValue(char *key, void *value);
void *getCallStackValue(char *key);
};
class ThreadStackManager {
public:
int id;
ThreadLocalKey *thread_local_key;
std::vector<CallStackManager *> call_stacks;
public:
ThreadStackManager(ThreadLocalKey *key);
static ThreadStackManager *initializeFromThreadLocalKey(ThreadLocalKey *key);
void pushCallStack(CallStackManager *call_stack);
CallStackManager *popCallStack();
};
#endif //HOOKZZ_STACKMANAGER_H
|
ZJNixiang/HookZz
|
src/std_kit/std_map.c
|
<filename>src/std_kit/std_map.c
/**
* Copyright (c) 2014 rxi
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MIT license. See LICENSE for details.
*/
#include "std_map.h"
#include <stdlib.h>
#include <string.h>
static unsigned map_hash(const char *str) {
unsigned hash = 5381;
while (*str) {
hash = ((hash << 5) + hash) ^ *str++;
}
return hash;
}
static map_node_t *map_node_new(const char *key, map_value_t value) {
map_node_t *node;
int key_str_len = strlen(key) + 1;
node = (map_node_t *)malloc(sizeof(map_node_t) + key_str_len);
node->hash = map_hash(key);
node->value = value;
// copy key string append the map_node_t
memcpy(node + 1, key, key_str_len);
return node;
}
static int map_bucket_index(map_base_t *m, unsigned hash) {
/* If the implementation is changed to allow a non-power-of-2 bucket count,
* the line below should be changed to use mod instead of AND */
return hash & (m->nbuckets - 1);
}
static void map_add_node(map_base_t *m, map_node_t *node) {
int n = map_bucket_index(m, node->hash);
node->next = m->buckets[n];
m->buckets[n] = node;
}
static int map_resize(map_base_t *m, int nbuckets) {
map_node_t *nodes, *node, *next;
map_node_t **buckets;
int i;
/* Chain all nodes together */
nodes = NULL;
i = m->nbuckets;
while (i--) {
node = (m->buckets)[i];
while (node) {
next = node->next;
node->next = nodes;
nodes = node;
node = next;
}
}
/* Reset buckets */
buckets = realloc(m->buckets, sizeof(*m->buckets) * nbuckets);
if (buckets != NULL) {
m->buckets = buckets;
m->nbuckets = nbuckets;
}
if (m->buckets) {
memset(m->buckets, 0, sizeof(*m->buckets) * m->nbuckets);
/* Re-add nodes to buckets */
node = nodes;
while (node) {
next = node->next;
map_add_node(m, node);
node = next;
}
}
/* Return error code if realloc() failed */
return (buckets == NULL) ? -1 : 0;
}
static map_node_t *map_get_node(map_base_t *m, const char *key) {
unsigned hash = map_hash(key);
map_node_t **next;
if (m->nbuckets > 0) {
next = &m->buckets[map_bucket_index(m, hash)];
while (*next) {
if ((*next)->hash == hash && !strcmp((char *)(*next + 1), key)) {
return *next;
}
next = &(*next)->next;
}
}
return NULL;
}
map_value_t map_get_value(map_base_t *m, const char *key) {
map_node_t *node;
node = map_get_node(m, key);
if (node)
return node->value;
return (map_value_t){0};
}
map_base_t *map_new() {
map_base_t *map = (map_base_t *)malloc(sizeof(map_base_t));
memset(map, 0, sizeof(map_base_t));
return map;
}
void map_destory(map_base_t *m) {
map_node_t *next, *node;
int i;
i = m->nbuckets;
while (i--) {
node = m->buckets[i];
while (node) {
next = node->next;
free(node);
node = next;
}
}
free(m->buckets);
}
int map_set_value(map_base_t *m, const char *key, map_value_t value) {
int n, err;
map_node_t *node;
map_value_t tmp_value;
/* Find & replace existing node */
node = map_get_node(m, key);
if (node) {
node->value = value;
return 0;
}
/* Add new node */
node = map_node_new(key, value);
if (node == NULL)
goto fail;
if (m->nnodes >= m->nbuckets) {
n = (m->nbuckets > 0) ? (m->nbuckets << 1) : 1;
err = map_resize(m, n);
if (err)
goto fail;
}
map_add_node(m, node);
m->nnodes++;
return 0;
fail:
if (node)
free(node);
return -1;
}
void map_remove_value(map_base_t *m, const char *key) {
unsigned hash = map_hash(key);
map_node_t **next;
map_node_t *node;
if (m->nbuckets > 0) {
next = &m->buckets[map_bucket_index(m, hash)];
while (*next) {
if ((*next)->hash == hash && !strcmp((char *)(*next + 1), key)) {
node = *next;
*next = (*next)->next;
free(node);
m->nnodes--;
}
next = &(*next)->next;
}
}
}
map_iter_t map_iter_new(void) {
map_iter_t iter;
iter.bucket_index = -1;
iter.node_next = NULL;
return iter;
}
map_node_t *map_iter_next(map_base_t *m, map_iter_t *iter) {
map_node_t *iter_node;
for (int i = iter->bucket_index; i < m->nbuckets; i++) {
if (iter->node_next)
iter_node = iter->node_next;
else
iter_node = m->buckets[i];
while (iter_node->next) {
iter->node_next = iter_node->next;
iter->bucket_index = i;
return iter->node_next;
}
}
return NULL;
}
|
ZJNixiang/HookZz
|
src/platforms/backend-posix/memory-manager-posix.c
|
<reponame>ZJNixiang/HookZz
#include "memory-helper-posix.h"
#include "memory_manager.h"
#if !defined(__APPLE__) || USE_POSIX_IN_DARWIN
PLATFORM_API int memory_manager_cclass(get_page_size)() {
int page_size;
page_size = posix_memory_helper_cclass(get_page_size)();
return page_size;
}
PLATFORM_API void memory_manager_cclass(patch_code)(memory_manager_t *self, void *dest, void *src, int count) {
posix_memory_helper_cclass(patch_code)(dest, src, count);
return;
}
PLATFORM_API void *memory_manager_cclass(allocate_page)(memory_manager_t *self, int prot, int n) {
return posix_memory_helper_cclass(allocate_page)(prot, n);
}
PLATFORM_API void memory_manager_cclass(set_page_permission)(void *page_address, int prot, int n) {
posix_memory_helper_cclass(set_page_permission)(page_address, prot, n);
}
#endif
|
ZJNixiang/HookZz
|
srcxx/ClosureBridge.h
|
<reponame>ZJNixiang/HookZz<gh_stars>1-10
//
// Created by jmpews on 2018/6/14.
//
#ifndef HOOKZZ_CLOSUREBRIDGE_H
#define HOOKZZ_CLOSUREBRIDGE_H
#include <stdint.h>
#include <vector>
#define PRIAVE
#include "CommonClass/DesignPattern/Singleton.h"
#include "Core.h"
#include "hookzz.h"
typedef struct _ClosureBridgeInfo {
void *user_code;
void *user_data;
void *redirect_trampoline;
} ClosureBridgeInfo;
typedef struct _ClosureBridgeTrampolineTable {
void *entry;
void *trampoline_page;
uint16_t used_count;
uint16_t free_count;
} ClosureBridgeTrampolineTable;
class ClosureBridge {
public:
std::vector<ClosureBridgeInfo *> bridge_infos;
std::vector<ClosureBridgeTrampolineTable *> trampoline_tables;
public:
ClosureBridgeInfo *allocateClosureBridge(void *user_data, void *user_code);
ClosureBridgeTrampolineTable *allocateClosureBridgeTrampolineTable();
};
typedef struct _DynamicClosureBridgeInfo {
void *trampolineTo PRIAVE;
void *user_code;
void *user_data;
void *redirect_trampoline;
} DynamicClosureBridgeInfo;
typedef struct _DynamicClosureTrampolineTable {
void *entry;
void *trampoline_page;
void *data_page;
uint16_t used_count;
uint16_t free_count;
} DynamicClosureBridgeTrampolineTable;
class DynamicClosureBridge {
public:
std::vector<DynamicClosureBridgeInfo *> bridge_infos;
std::vector<DynamicClosureBridgeTrampolineTable *> trampoline_tables;
public:
DynamicClosureBridgeInfo *allocateDynamicClosureBridge(void *user_data, void *user_code);
DynamicClosureBridgeTrampolineTable *addDynamicClosurceBridgeTrampolineTable();
};
typedef void (*USER_CODE_CALL)(RegState *rs, ClosureBridgeInfo *cbInfo);
typedef void (*DYNAMIC_USER_CODE_CALL)(RegState *rs, DynamicClosureBridgeInfo *dcbInfo);
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
void closure_bridge_trampoline_template();
void closure_bridge_template();
void dynamic_closure_bridge_template();
void dynamic_closure_trampoline_table_page();
#ifdef __cplusplus
}
#endif //__cplusplus
#endif //HOOKZZ_CLOSUREBRIDGE_H
|
ZJNixiang/HookZz
|
src/platforms/arch-arm64/register-arm64.h
|
#ifndef platforms_arch_arm64_register_arm64_h
#define platforms_arch_arm64_register_arm64_h
#include "instruction.h"
typedef enum _ARM64Reg {
ARM64_REG_X0 = 0,
ARM64_REG_X1,
ARM64_REG_X2,
ARM64_REG_X3,
ARM64_REG_X4,
ARM64_REG_X5,
ARM64_REG_X6,
ARM64_REG_X7,
ARM64_REG_X8,
ARM64_REG_X9,
ARM64_REG_X10,
ARM64_REG_X11,
ARM64_REG_X12,
ARM64_REG_X13,
ARM64_REG_X14,
ARM64_REG_X15,
ARM64_REG_X16,
ARM64_REG_X17,
ARM64_REG_X18,
ARM64_REG_X19,
ARM64_REG_X20,
ARM64_REG_X21,
ARM64_REG_X22,
ARM64_REG_X23,
ARM64_REG_X24,
ARM64_REG_X25,
ARM64_REG_X26,
ARM64_REG_X27,
ARM64_REG_X28,
ARM64_REG_X29,
ARM64_REG_X30,
ARM64_REG_X31,
ARM64_REG_FP = ARM64_REG_X29,
ARM64_REG_LR = ARM64_REG_X30,
ARM64_REG_SP = ARM64_REG_X31
} ARM64Reg;
typedef struct _ARM64RegInfo {
int index;
int meta;
int width;
bool is_integer;
} ARM64RegInfo;
void arm64_register_describe(ARM64Reg reg, ARM64RegInfo *ri);
ARM64Reg arm64_register_disdescribe(int index, int width);
#endif
|
ZJNixiang/HookZz
|
src/platforms/arch-arm64/reader-arm64.h
|
#ifndef platforms_arch_arm64_reader_arm64_h
#define platforms_arch_arm64_reader_arm64_h
#include "ARM64AssemblyCore.h"
#include "core.h"
#include "instruction.h"
#include "std_kit/std_buffer_array.h"
#include "std_kit/std_kit.h"
#include "std_kit/std_list.h"
typedef struct _ARM64AssemblyReader {
void *start_pc;
void *start_address;
list_t *instCTXs;
buffer_array_t *inst_bytes;
} ARM64AssemblyReader;
#define arm64_assembly_reader_cclass(member) cclass(arm64_assembly_reader, member)
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
ARM64AssemblyReader *arm64_assembly_reader_cclass(new)(void *address, void *pc);
void arm64_assembly_reader_cclass(reset)(ARM64AssemblyReader *self, void *address, void *pc);
ARM64InstructionCTX *arm64_assembly_reader_cclass(read_inst)(ARM64AssemblyReader *self);
#ifdef __cplusplus
}
#endif //__cplusplus
#endif
|
ZJNixiang/HookZz
|
src/platforms/backend-linux/memory-manager-linux.c
|
<filename>src/platforms/backend-linux/memory-manager-linux.c
#include "core.h"
#include "memory-helper-posix.h"
#include "memory_manager.h"
PLATFORM_API bool memory_manager_cclass(is_support_allocate_rx_memory)(memory_manager_t *self) { return true; }
PLATFORM_API void memory_manager_cclass(get_process_memory_layout)(memory_manager_t *self) {
char filename[64];
char buf[256];
FILE *fp;
// self process
int pid = -1;
// given pid, open /proc/pid/maps; or not, open current maps.
if (pid > 0) {
sprintf(filename, "/proc/%d/maps", pid);
} else {
sprintf(filename, "/proc/self/maps");
}
fp = fopen(filename, "r");
if (fp < 0) {
return;
}
while (fgets(buf, sizeof(buf), fp) != NULL) {
zz_addr_t start_addr, end_addr;
unsigned dev, sdev;
unsigned long inode;
unsigned long long offset;
char prot[5];
char path[64];
int len;
/* format in /proc/pid/maps is constructed as below in fs/proc/task_mmu.c
167 seq_printf(m,
168 "%08lx-%08lx %c%c%c%c %08llx %02x:%02x %lu ",
169 vma->vm_start,
170 vma->vm_end,
171 flags & VM_READ ? 'r' : '-',
172 flags & VM_WRITE ? 'w' : '-',
173 flags & VM_EXEC ? 'x' : '-',
174 flags & VM_MAYSHARE ? flags & VM_SHARED ? 'S' : 's' : 'p',
175 pgoff,
176 MAJOR(dev), MINOR(dev), ino);
177
178 if (file) {
179 seq_pad(m, ' ');
180 seq_file_path(m, file, "");
181 } else if (mm && is_stack(priv, vma)) {
182 seq_pad(m, ' ');
183 seq_printf(m, "[stack]");
184 }
*/
if (sscanf(buf, "%lx-%lx %s %llx %x:%x %lu %s", &start_addr, &end_addr, prot, &offset, &dev, &sdev, &inode,
path) != 8)
continue;
MemoryBlock *mb = SAFE_MALLOC_TYPE(MemoryBlock);
list_rpush(self->process_memory_layout, list_node_new(mb));
mb->address = (void *)start_addr;
mb->size = end_addr - start_addr;
mb->prot = (prot[0] == 'r' ? (1 << 0) : 0) | (prot[1] == 'w' ? (1 << 1) : 0) | (prot[2] == 'x' ? (1 << 2) : 0);
}
}
|
ZJNixiang/HookZz
|
src/thread_support/thread_stack.h
|
<gh_stars>1-10
#ifndef thread_support_thread_stack_h
#define thread_support_thread_stack_h
#include "core.h"
#include "hookzz.h"
#include "std_kit/std_list.h"
#include "std_kit/std_map.h"
typedef struct _thread_stack_manager_t {
uintptr_t thread_id;
list_t *call_stacks;
} thread_stack_manager_t;
typedef struct _call_stack_t {
uintptr_t call_id;
thread_stack_manager_t *thread_stack_manager;
void *reg_sp;
void *ret_addr;
map_t *context_kv;
} call_stack_t;
#define thread_stack_cclass(member) cclass(thread_stack, member)
#define call_stack_cclass(member) cclass(call_stack, member)
thread_stack_manager_t *thread_stack_cclass(shared_instance)();
void thread_stack_cclass(push_call_stack)(thread_stack_manager_t *self, call_stack_t *call_stack);
call_stack_t *thread_stack_cclass(pop_call_stack)(thread_stack_manager_t *self);
call_stack_t *call_stack_cclass(new)(thread_stack_manager_t *thread_stack_manager);
void call_stack_cclass(destory)(call_stack_t *self);
#endif
|
ZJNixiang/HookZz
|
srcxx/InterceptorRouting.h
|
#ifndef interceptor_routing_h
#define interceptor_routing_h
#include "ClosureBridge.h"
#include "hookzz.h"
#include "interceptor.h"
ARCH_API void *get_ret_addr_PTR(RegState *rs);
ARCH_API void *get_next_hop_addr_PTR(RegState *rs);
void interceptor_routing_begin(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR, void *ret_addr_PTR);
void interceptor_routing_end(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR);
void interceptor_routing_dynamic_binary_instrumentation(RegState *rs, hook_entry_t *entry, void *next_hop_addr_PTR);
void interceptor_routing_begin_bridge_handler(RegState *rs, ClosureBridgeInfo *cbInfo);
void interceptor_routing_end_bridge_handler(RegState *rs, ClosureBridgeInfo *cbInfo);
void interceptor_routing_dynamic_binary_instrumentation_bridge_handler(RegState *rs, ClosureBridgeInfo *cbInfo);
void interceptor_routing_common_bridge_handler(RegState *rs, ClosureBridgeInfo *cbInfo);
void interceptor_routing_begin_dynamic_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcbInfo);
void interceptor_routing_end_dynamic_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcbInfo);
void interceptor_routing_dynamic_common_bridge_handler(RegState *rs, DynamicClosureBridgeInfo *dcbInfo);
#endif
|
ZJNixiang/HookZz
|
srcxx/CommonClass/Manager.h
|
//
// Created by z on 2018/6/14.
//
#ifndef HOOKZZ_MANAGER_H
#define HOOKZZ_MANAGER_H
#include <iostream>
#include <vector>
#endif //HOOKZZ_MANAGER_H
|
ZJNixiang/HookZz
|
src/platforms/arch-arm64/instruction.h
|
<filename>src/platforms/arch-arm64/instruction.h
#ifndef platforms_arch_arm64_instruction_h
#define platforms_arch_arm64_instruction_h
#include "hookzz.h"
typedef struct _ARM64InstructionCTX {
zz_addr_t pc;
zz_addr_t address;
uint8_t size;
uint32_t bytes;
} ARM64InstructionCTX;
// get hex insn sub
uint32_t get_insn_sub(uint32_t insn, int start, int length);
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.