Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 | repos/gpt4all.zig/src | repos/gpt4all.zig/src/llm/chat.cpp | #include "ggml/ggml.h"
#include "utils.h"
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <map>
#include <string>
#include <vector>
#include "gptj.h"
#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
#include <signal.h>
#include <unistd.h>
#elif defined (_WIN32)
#include <signal.h>
#include <windows.h>
#endif
#define ANSI_COLOR_RED "\x1b[31m"
#define ANSI_COLOR_GREEN "\x1b[32m"
#define ANSI_COLOR_YELLOW "\x1b[33m"
#define ANSI_COLOR_BLUE "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN "\x1b[36m"
#define ANSI_COLOR_RESET "\x1b[0m"
#define ANSI_BOLD "\x1b[1m"
static bool is_interacting = false;
#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
void sigint_handler(int signo) {
printf(ANSI_COLOR_RESET);
if (signo == SIGINT) {
if (!is_interacting) {
is_interacting=true;
} else {
_exit(130);
}
}
}
#endif
const char * print_system_info(void) {
static std::string s;
s = "";
s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
return s.c_str();
}
extern "C" int cpp_main(int argc, char ** argv) {
ggml_time_init();
const int64_t t_main_start_us = ggml_time_us();
gpt_params params;
if (gpt_params_parse(argc, argv, params) == false) {
return 1;
}
if (params.seed < 0) {
params.seed = time(NULL);
}
fprintf(stderr, "%s: seed = %d\n", __func__, params.seed);
std::mt19937 rng(params.seed);
// if (params.prompt.empty()) {
// params.prompt = gpt_random_prompt(rng);
// }
// params.prompt = R"(// this function checks if the number n is prime
//bool is_prime(int n) {)";
int64_t t_load_us = 0;
gpt_vocab vocab;
gptj_model model;
// load the model
{
const int64_t t_start_us = ggml_time_us();
if (!gptj_model_load(params.model, model, vocab)) {
fprintf(stderr, "%s: failed to load model from '%s'\n", __func__, params.model.c_str());
return 1;
}
t_load_us = ggml_time_us() - t_start_us;
}
// print system information
{
fprintf(stderr, "\n");
fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
params.n_threads, std::thread::hardware_concurrency(), print_system_info());
}
int n_past = 0;
int64_t t_sample_us = 0;
int64_t t_predict_us = 0;
std::vector<float> logits;
std::vector<gpt_vocab::id> embd_inp;
// params.n_predict = std::min(params.n_predict, model.hparams.n_ctx - (int) embd_inp.size());
std::vector<gpt_vocab::id> instruct_inp = ::gpt_tokenize(vocab, " Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n");
std::vector<gpt_vocab::id> prompt_inp = ::gpt_tokenize(vocab, "### Instruction:\n\n");
std::vector<gpt_vocab::id> response_inp = ::gpt_tokenize(vocab, "### Response:\n\n");
embd_inp.insert(embd_inp.end(), instruct_inp.begin(), instruct_inp.end());
if(!params.prompt.empty()) {
std::vector<gpt_vocab::id> param_inp = ::gpt_tokenize(vocab, params.prompt);
embd_inp.insert(embd_inp.end(), prompt_inp.begin(), prompt_inp.end());
embd_inp.insert(embd_inp.end(), param_inp.begin(), param_inp.end());
embd_inp.insert(embd_inp.end(), response_inp.begin(), response_inp.end());
}
// fprintf(stderr, "\n");
// fprintf(stderr, "%s: prompt: '%s'\n", __func__, params.prompt.c_str());
// fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
// for (int i = 0; i < (int) embd_inp.size(); i++) {
// fprintf(stderr, "%6d -> '%s'\n", embd_inp[i], vocab.id_to_token.at(embd_inp[i]).c_str());
// }
// fprintf(stderr, "\n");
if (params.interactive) {
#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
struct sigaction sigint_action;
sigint_action.sa_handler = sigint_handler;
sigemptyset (&sigint_action.sa_mask);
sigint_action.sa_flags = 0;
sigaction(SIGINT, &sigint_action, NULL);
#elif defined (_WIN32)
signal(SIGINT, sigint_handler);
// Windows console ANSI color fix
DWORD mode = 0;
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
if (hConsole && hConsole != INVALID_HANDLE_VALUE && GetConsoleMode(hConsole, &mode)){
SetConsoleMode(hConsole, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
SetConsoleOutputCP(CP_UTF8);
}
#endif
fprintf(stderr, "%s: interactive mode on.\n", __func__);
// if(antiprompt_inp.size()) {
// fprintf(stderr, "%s: reverse prompt: '%s'\n", __func__, params.antiprompt.c_str());
// fprintf(stderr, "%s: number of tokens in reverse prompt = %zu\n", __func__, antiprompt_inp.size());
// for (int i = 0; i < (int) antiprompt_inp.size(); i++) {
// fprintf(stderr, "%6d -> '%s'\n", antiprompt_inp[i], vocab.id_to_token.at(antiprompt_inp[i]).c_str());
// }
// fprintf(stderr, "\n");
// }
}
fprintf(stderr, "sampling parameters: temp = %f, top_k = %d, top_p = %f\n", params.temp, params.top_k, params.top_p);
fprintf(stderr, "\n\n");
std::vector<gpt_vocab::id> embd;
// determine the required inference memory per token:
size_t mem_per_token = 0;
gptj_eval(model, params.n_threads, 0, { 0, 1, 2, 3 }, logits, mem_per_token);
//
int last_n_size = 64;
std::vector<gpt_vocab::id> last_n_tokens(last_n_size);
std::fill(last_n_tokens.begin(), last_n_tokens.end(), 0);
if (params.interactive) {
fprintf(stderr, "== Running in chat mode. ==\n"
#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
" - Press Ctrl+C to interject at any time.\n"
#endif
" - Press Return to return control to GPT4J.\n"
" - If you want to submit another line, end your input in '\\'.\n");
}
// we may want to slide the input window along with the context, but for now we restrict to the context length
int remaining_tokens = model.hparams.n_ctx - embd_inp.size();
int input_consumed = 0;
bool input_noecho = true;
// prompt user immediately after the starting prompt has been loaded
if (params.interactive_start) {
is_interacting = true;
}
// set the color for the prompt which will be output initially
if (params.use_color) {
printf(ANSI_COLOR_YELLOW);
}
while (remaining_tokens > 0) {
// predict
if (embd.size() > 0) {
const int64_t t_start_us = ggml_time_us();
if (!gptj_eval(model, params.n_threads, n_past, embd, logits, mem_per_token)) {
fprintf(stderr, "Failed to predict\n");
return 1;
}
t_predict_us += ggml_time_us() - t_start_us;
}
n_past += embd.size();
embd.clear();
if (embd_inp.size() <= input_consumed && !is_interacting) {
// out of user input, sample next token
const float top_k = params.top_k;
const float top_p = params.top_p;
const float temp = params.temp;
const float repeat_penalty = 1.30f; // model.hparams.repeat_penalty;
const int n_vocab = model.hparams.n_vocab;
gpt_vocab::id id = 0;
{
const int64_t t_start_sample_us = ggml_time_us();
// id = gpt_sample_top_k_top_p(vocab, logits.data() + (logits.size() - n_vocab), last_n_tokens, repeat_penalty, top_k, top_p, temp, rng);
id = gpt_sample_top_k_top_p(vocab, logits.data() + (logits.size() - n_vocab), top_k, top_p, temp, rng);
last_n_tokens.erase(last_n_tokens.begin());
last_n_tokens.push_back(id);
t_sample_us += ggml_time_us() - t_start_sample_us;
}
// add it to the context
embd.push_back(id);
// echo this to console
input_noecho = false;
// decrement remaining sampling budget
--remaining_tokens;
} else {
// some user input remains from prompt or interaction, forward it to processing
while (embd_inp.size() > input_consumed) {
// fprintf(stderr, "%6d -> '%s'\n", embd_inp[input_consumed], vocab.id_to_token.at(embd_inp[input_consumed]).c_str());
embd.push_back(embd_inp[input_consumed]);
last_n_tokens.erase(last_n_tokens.begin());
last_n_tokens.push_back(embd_inp[input_consumed]);
++input_consumed;
if (embd.size() > params.n_batch) {
break;
}
}
// reset color to default if we there is no pending user input
if (!input_noecho && params.use_color && embd_inp.size() == input_consumed) {
printf(ANSI_COLOR_RESET);
}
}
// display text
if (!input_noecho) {
for (auto id : embd) {
if (id != 50256)
printf("%s", vocab.id_to_token[id].c_str());
}
fflush(stdout);
}
// in interactive mode, and not currently processing queued inputs;
// check if we should prompt the user for more
if (params.interactive && embd_inp.size() <= input_consumed) {
// check for reverse prompt
// if (antiprompt_inp.size() && std::equal(antiprompt_inp.rbegin(), antiprompt_inp.rend(), last_n_tokens.rbegin())) {
// // reverse prompt found
// is_interacting = true;
// }
if (is_interacting) {
// input_consumed = 0;
// embd_inp.erase(embd_inp.begin());
input_consumed = embd_inp.size();
embd_inp.insert(embd_inp.end(), prompt_inp.begin(), prompt_inp.end());
// set the color for the prompt which will be output initially
if (params.use_color) {
printf(ANSI_COLOR_YELLOW);
}
printf("\n> ");
// currently being interactive
bool another_line=true;
while (another_line) {
fflush(stdout);
char buf[256] = {0};
int n_read;
if(params.use_color) printf(ANSI_BOLD ANSI_COLOR_GREEN);
if (scanf("%255[^\n]%n%*c", buf, &n_read) <= 0) {
// presumable empty line, consume the newline
if (scanf("%*c") <= 0) { /*ignore*/ }
n_read=0;
}
if(params.use_color) printf(ANSI_COLOR_RESET);
if (n_read > 0 && buf[n_read-1]=='\\') {
another_line = true;
buf[n_read-1] = '\n';
buf[n_read] = 0;
} else {
another_line = false;
buf[n_read] = '\n';
buf[n_read+1] = 0;
}
std::vector<gpt_vocab::id> line_inp = ::gpt_tokenize(vocab, buf);
embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
embd_inp.insert(embd_inp.end(), response_inp.begin(), response_inp.end());
remaining_tokens -= prompt_inp.size() + line_inp.size() + response_inp.size();
input_noecho = true; // do not echo this again
}
is_interacting = false;
}
}
// end of text token
if (embd.back() == 50256) {
if (params.interactive) {
is_interacting = true;
continue;
} else {
printf("\n");
fprintf(stderr, " [end of text]\n");
break;
}
}
}
#if defined (_WIN32)
signal(SIGINT, SIG_DFL);
#endif
// report timing
{
const int64_t t_main_end_us = ggml_time_us();
fprintf(stderr, "\n\n");
fprintf(stderr, "%s: mem per token = %8zu bytes\n", __func__, mem_per_token);
fprintf(stderr, "%s: load time = %8.2f ms\n", __func__, t_load_us/1000.0f);
fprintf(stderr, "%s: sample time = %8.2f ms\n", __func__, t_sample_us/1000.0f);
fprintf(stderr, "%s: predict time = %8.2f ms / %.2f ms per token\n", __func__, t_predict_us/1000.0f, t_predict_us/1000.0f/n_past);
fprintf(stderr, "%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us)/1000.0f);
}
ggml_free(model.ctx);
if (params.use_color) {
printf(ANSI_COLOR_RESET);
}
return 0;
}
|
0 | repos/gpt4all.zig/src | repos/gpt4all.zig/src/llm/llmodel.h | #ifndef LLMODEL_H
#define LLMODEL_H
#include <string>
#include <functional>
#include <vector>
class LLModel {
public:
explicit LLModel() {}
virtual ~LLModel() {}
virtual bool loadModel(const std::string &modelPath, std::istream &fin) = 0;
virtual bool isModelLoaded() const = 0;
struct PromptContext {
std::vector<float> logits;
int32_t n_past = 0; // number of tokens in past conversation
};
virtual void prompt(const std::string &prompt, std::function<bool(const std::string&)> response,
PromptContext &ctx, int32_t n_predict = 200, int32_t top_k = 40, float top_p = 0.9f,
float temp = 0.9f, int32_t n_batch = 9) = 0;
};
#endif // LLMODEL_H |
0 | repos/gpt4all.zig/src/llm | repos/gpt4all.zig/src/llm/ggml/ggml.h | #pragma once
//
// GGML Tensor Library
//
// This documentation is still a work in progress.
// If you wish some specific topics to be covered, feel free to drop a comment:
//
// https://github.com/ggerganov/whisper.cpp/issues/40
//
// ## Overview
//
// This library implements:
//
// - a set of tensor operations
// - automatic differentiation
// - basic optimization algorithms
//
// The aim of this library is to provide a minimalistic approach for various machine learning tasks. This includes,
// but is not limited to, the following:
//
// - linear regression
// - support vector machines
// - neural networks
//
// The library allows the user to define a certain function using the available tensor operations. This function
// definition is represented internally via a computation graph. Each tensor operation in the function definition
// corresponds to a node in the graph. Having the computation graph defined, the user can choose to compute the
// function's value and/or its gradient with respect to the input variables. Optionally, the function can be optimized
// using one of the available optimization algorithms.
//
// For example, here we define the function: f(x) = a*x^2 + b
//
// {
// struct ggml_init_params params = {
// .mem_size = 16*1024*1024,
// .mem_buffer = NULL,
// };
//
// // memory allocation happens here
// struct ggml_context * ctx = ggml_init(params);
//
// struct ggml_tensor * x = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 1);
//
// ggml_set_param(ctx, x); // x is an input variable
//
// struct ggml_tensor * a = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 1);
// struct ggml_tensor * b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 1);
// struct ggml_tensor * x2 = ggml_mul(ctx, x, x);
// struct ggml_tensor * f = ggml_add(ctx, ggml_mul(ctx, a, x2), b);
//
// ...
// }
//
// Notice that the function definition above does not involve any actual computation. The computation is performed only
// when the user explicitly requests it. For example, to compute the function's value at x = 2.0:
//
// {
// ...
//
// struct ggml_cgraph gf = ggml_build_forward(f);
//
// // set the input variable and parameter values
// ggml_set_f32(x, 2.0f);
// ggml_set_f32(a, 3.0f);
// ggml_set_f32(b, 4.0f);
//
// ggml_graph_compute(ctx0, &gf);
//
// printf("f = %f\n", ggml_get_f32_1d(f, 0));
//
// ...
// }
//
// The actual computation is performed in the ggml_graph_compute() function.
//
// The ggml_new_tensor_...() functions create new tensors. They are allocated in the memory buffer provided to the
// ggml_init() function. You have to be careful not to exceed the memory buffer size. Therefore, you have to know
// in advance how much memory you need for your computation. Alternatively, you can allocate a large enough memory
// and after defining the computation graph, call the ggml_used_mem() function to find out how much memory was
// actually needed.
//
// The ggml_set_param() function marks a tensor as an input variable. This is used by the automatic
// differentiation and optimization algorithms.
//
// The described approach allows to define the function graph once and then compute its forward or backward graphs
// multiple times. All computations will use the same memory buffer allocated in the ggml_init() function. This way
// the user can avoid the memory allocation overhead at runtime.
//
// The library supports multi-dimensional tensors - up to 4 dimensions. The FP16 and FP32 data types are first class
// citizens, but in theory the library can be extended to support FP8 and integer data types.
//
// Each tensor operation produces a new tensor. Initially the library was envisioned to support only the use of unary
// and binary operations. Most of the available operations fall into one of these two categories. With time, it became
// clear that the library needs to support more complex operations. The way to support these operations is not clear
// yet, but a few examples are demonstrated in the following operations:
//
// - ggml_permute()
// - ggml_conv_1d_1s()
// - ggml_conv_1d_2s()
//
// For each tensor operator, the library implements a forward and backward computation function. The forward function
// computes the output tensor value given the input tensor values. The backward function computes the adjoint of the
// input tensors given the adjoint of the output tensor. For a detailed explanation of what this means, take a
// calculus class, or watch the following video:
//
// What is Automatic Differentiation?
// https://www.youtube.com/watch?v=wG_nF1awSSY
//
//
// ## Tensor data (struct ggml_tensor)
//
// The tensors are stored in memory via the ggml_tensor struct. The structure provides information about the size of
// the tensor, the data type, and the memory buffer where the tensor data is stored. Additionally, it contains
// pointers to the "source" tensors - i.e. the tensors that were used to compute the current tensor. For example:
//
// {
// struct ggml_tensor * c = ggml_add(ctx, a, b);
//
// assert(c->src[0] == a);
// assert(c->src[1] == b);
// }
//
// The multi-dimensional tensors are stored in row-major order. The ggml_tensor struct contains fields for the
// number of elements in each dimension ("ne") as well as the number of bytes ("nb", a.k.a. stride). This allows
// to store tensors that are not contiguous in memory, which is useful for operations such as transposition and
// permutation. All tensor operations have to take the stride into account and not assume that the tensor is
// contiguous in memory.
//
// The data of the tensor is accessed via the "data" pointer. For example:
//
// {
// struct ggml_tensor * a = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 2, 3);
//
// // a[1, 2] = 1.0f;
// *(float *) ((char *) a->data + 2*a->nb[1] + 1*a->nb[0]) = 1.0f;
//
// // a[2, 0] = 2.0f;
// *(float *) ((char *) a->data + 0*a->nb[1] + 2*a->nb[0]) = 2.0f;
//
// ...
// }
//
// Alternatively, there are helper functions, such as ggml_get_f32_1d() and ggml_set_f32_1d() that can be used.
//
// ## The matrix multiplication operator (ggml_mul_mat)
//
// TODO
//
//
// ## Multi-threading
//
// TODO
//
//
// ## Overview of ggml.c
//
// TODO
//
//
// ## SIMD optimizations
//
// TODO
//
//
// ## Debugging ggml
//
// TODO
//
//
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#define GGML_MAX_DIMS 4
#define GGML_MAX_NODES 4096
#define GGML_MAX_PARAMS 16
#define GGML_MAX_CONTEXTS 64
#define GGML_MAX_OPT 4
#ifdef __ARM_NEON
// we use the built-in 16-bit float type
typedef __fp16 ggml_fp16_t;
#else
typedef uint16_t ggml_fp16_t;
#endif
// convert FP16 <-> FP32
float ggml_fp16_to_fp32(ggml_fp16_t x);
ggml_fp16_t ggml_fp32_to_fp16(float x);
struct ggml_object;
struct ggml_context;
enum ggml_type {
GGML_TYPE_Q4_0,
GGML_TYPE_Q4_1,
GGML_TYPE_I8,
GGML_TYPE_I16,
GGML_TYPE_I32,
GGML_TYPE_F16,
GGML_TYPE_F32,
GGML_TYPE_COUNT,
};
// available tensor operations:
enum ggml_op {
GGML_OP_NONE = 0,
GGML_OP_DUP,
GGML_OP_ADD,
GGML_OP_SUB,
GGML_OP_MUL,
GGML_OP_DIV,
GGML_OP_SQR,
GGML_OP_SQRT,
GGML_OP_SUM,
GGML_OP_MEAN,
GGML_OP_REPEAT,
GGML_OP_ABS,
GGML_OP_SGN,
GGML_OP_NEG,
GGML_OP_STEP,
GGML_OP_RELU,
GGML_OP_GELU,
GGML_OP_SILU,
GGML_OP_NORM, // normalize
GGML_OP_RMS_NORM,
GGML_OP_MUL_MAT,
GGML_OP_SCALE,
GGML_OP_CPY,
GGML_OP_RESHAPE,
GGML_OP_VIEW,
GGML_OP_PERMUTE,
GGML_OP_TRANSPOSE,
GGML_OP_GET_ROWS,
GGML_OP_DIAG_MASK_INF,
GGML_OP_SOFT_MAX,
GGML_OP_ROPE,
GGML_OP_CONV_1D_1S,
GGML_OP_CONV_1D_2S,
GGML_OP_FLASH_ATTN,
GGML_OP_FLASH_FF,
GGML_OP_COUNT,
};
// n-dimensional tensor
struct ggml_tensor {
enum ggml_type type;
int n_dims;
int ne[GGML_MAX_DIMS]; // number of elements
size_t nb[GGML_MAX_DIMS]; // stride in bytes:
// nb[0] = sizeof(type)
// nb[1] = nb[0] * ne[0] + padding
// nb[i] = nb[i-1] * ne[i-1]
// compute data
enum ggml_op op;
bool is_param;
struct ggml_tensor * grad;
struct ggml_tensor * src0;
struct ggml_tensor * src1;
struct ggml_tensor * opt[GGML_MAX_OPT];
// thread scheduling
int n_tasks;
// performance
int perf_runs;
int64_t perf_cycles;
int64_t perf_time_us;
void * data;
char padding[8];
};
// computation graph
struct ggml_cgraph {
int n_nodes;
int n_leafs;
int n_threads;
size_t work_size;
struct ggml_tensor * work;
struct ggml_tensor * nodes[GGML_MAX_NODES];
struct ggml_tensor * grads[GGML_MAX_NODES];
struct ggml_tensor * leafs[GGML_MAX_NODES];
// performance
int perf_runs;
int64_t perf_cycles;
int64_t perf_time_us;
};
// scratch buffer
struct ggml_scratch {
size_t offs;
size_t size;
void * data;
};
struct ggml_init_params {
// memory pool
size_t mem_size; // bytes
void * mem_buffer; // if NULL, memory will be allocated internally
};
void ggml_time_init(void); // call this once at the beginning of the program
int64_t ggml_time_ms(void);
int64_t ggml_time_us(void);
int64_t ggml_cycles(void);
int64_t ggml_cycles_per_ms(void);
void ggml_print_object (const struct ggml_object * obj);
void ggml_print_objects(const struct ggml_context * ctx);
int ggml_nelements(const struct ggml_tensor * tensor);
size_t ggml_nbytes (const struct ggml_tensor * tensor);
int ggml_blck_size (enum ggml_type type);
size_t ggml_type_size (enum ggml_type type); // size in bytes for all elements in a block
float ggml_type_sizef(enum ggml_type type); // ggml_type_size()/ggml_blck_size() as float
size_t ggml_element_size(const struct ggml_tensor * tensor);
struct ggml_context * ggml_init(struct ggml_init_params params);
void ggml_free(struct ggml_context * ctx);
size_t ggml_used_mem(const struct ggml_context * ctx);
size_t ggml_set_scratch(struct ggml_context * ctx, struct ggml_scratch scratch);
bool ggml_mlock_supported(void);
bool ggml_mlock(struct ggml_context * ctx, char ** err_p);
struct ggml_tensor * ggml_new_tensor(
struct ggml_context * ctx,
enum ggml_type type,
int n_dims,
const int *ne);
struct ggml_tensor * ggml_new_tensor_1d(
struct ggml_context * ctx,
enum ggml_type type,
int ne0);
struct ggml_tensor * ggml_new_tensor_2d(
struct ggml_context * ctx,
enum ggml_type type,
int ne0,
int ne1);
struct ggml_tensor * ggml_new_tensor_3d(
struct ggml_context * ctx,
enum ggml_type type,
int ne0,
int ne1,
int ne2);
struct ggml_tensor * ggml_new_tensor_4d(
struct ggml_context * ctx,
enum ggml_type type,
int ne0,
int ne1,
int ne2,
int ne3);
struct ggml_tensor * ggml_new_i32(struct ggml_context * ctx, int32_t value);
struct ggml_tensor * ggml_new_f32(struct ggml_context * ctx, float value);
struct ggml_tensor * ggml_dup_tensor (struct ggml_context * ctx, const struct ggml_tensor * src);
struct ggml_tensor * ggml_view_tensor(struct ggml_context * ctx, const struct ggml_tensor * src);
struct ggml_tensor * ggml_set_zero(struct ggml_tensor * tensor);
struct ggml_tensor * ggml_set_i32 (struct ggml_tensor * tensor, int32_t value);
struct ggml_tensor * ggml_set_f32 (struct ggml_tensor * tensor, float value);
int32_t ggml_get_i32_1d(const struct ggml_tensor * tensor, int i);
void ggml_set_i32_1d(const struct ggml_tensor * tensor, int i, int32_t value);
float ggml_get_f32_1d(const struct ggml_tensor * tensor, int i);
void ggml_set_f32_1d(const struct ggml_tensor * tensor, int i, float value);
void * ggml_get_data (const struct ggml_tensor * tensor);
float * ggml_get_data_f32(const struct ggml_tensor * tensor);
//
// operations on tensors with backpropagation
//
struct ggml_tensor * ggml_dup(
struct ggml_context * ctx,
struct ggml_tensor * a);
struct ggml_tensor * ggml_add(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b);
struct ggml_tensor * ggml_sub(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b);
struct ggml_tensor * ggml_mul(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b);
struct ggml_tensor * ggml_div(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b);
struct ggml_tensor * ggml_sqr(
struct ggml_context * ctx,
struct ggml_tensor * a);
struct ggml_tensor * ggml_sqrt(
struct ggml_context * ctx,
struct ggml_tensor * a);
// return scalar
// TODO: compute sum along rows
struct ggml_tensor * ggml_sum(
struct ggml_context * ctx,
struct ggml_tensor * a);
// mean along rows
struct ggml_tensor * ggml_mean(
struct ggml_context * ctx,
struct ggml_tensor * a);
// if a is the same shape as b, and a is not parameter, return a
// otherwise, return a new tensor: repeat(a) to fit in b
struct ggml_tensor * ggml_repeat(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b);
struct ggml_tensor * ggml_abs(
struct ggml_context * ctx,
struct ggml_tensor * a);
struct ggml_tensor * ggml_sgn(
struct ggml_context * ctx,
struct ggml_tensor * a);
struct ggml_tensor * ggml_neg(
struct ggml_context * ctx,
struct ggml_tensor * a);
struct ggml_tensor * ggml_step(
struct ggml_context * ctx,
struct ggml_tensor * a);
struct ggml_tensor * ggml_relu(
struct ggml_context * ctx,
struct ggml_tensor * a);
// TODO: double-check this computation is correct
struct ggml_tensor * ggml_gelu(
struct ggml_context * ctx,
struct ggml_tensor * a);
struct ggml_tensor * ggml_silu(
struct ggml_context * ctx,
struct ggml_tensor * a);
// normalize along rows
// TODO: eps is hardcoded to 1e-5 for now
struct ggml_tensor * ggml_norm(
struct ggml_context * ctx,
struct ggml_tensor * a);
struct ggml_tensor * ggml_rms_norm(
struct ggml_context * ctx,
struct ggml_tensor * a);
// A: m rows, n columns
// B: p rows, n columns (i.e. we transpose it internally)
// result is m columns, p rows
struct ggml_tensor * ggml_mul_mat(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b);
//
// operations on tensors without backpropagation
//
// in-place, returns view(a)
struct ggml_tensor * ggml_scale(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b);
// a -> b, return view(b)
struct ggml_tensor * ggml_cpy(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b);
// return view(a), b specifies the new shape
// TODO: when we start computing gradient, make a copy instead of view
struct ggml_tensor * ggml_reshape(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b);
// return view(a)
// TODO: when we start computing gradient, make a copy instead of view
struct ggml_tensor * ggml_reshape_2d(
struct ggml_context * ctx,
struct ggml_tensor * a,
int ne0,
int ne1);
// return view(a)
// TODO: when we start computing gradient, make a copy instead of view
struct ggml_tensor * ggml_reshape_3d(
struct ggml_context * ctx,
struct ggml_tensor * a,
int ne0,
int ne1,
int ne2);
// offset in bytes
struct ggml_tensor * ggml_view_1d(
struct ggml_context * ctx,
struct ggml_tensor * a,
int ne0,
size_t offset);
struct ggml_tensor * ggml_view_2d(
struct ggml_context * ctx,
struct ggml_tensor * a,
int ne0,
int ne1,
size_t nb1, // row stride in bytes
size_t offset);
struct ggml_tensor * ggml_permute(
struct ggml_context * ctx,
struct ggml_tensor * a,
int axis0,
int axis1,
int axis2,
int axis3);
// alias for ggml_permute(ctx, a, 1, 0, 2, 3)
struct ggml_tensor * ggml_transpose(
struct ggml_context * ctx,
struct ggml_tensor * a);
struct ggml_tensor * ggml_get_rows(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b);
// set elements above the diagonal to -INF
// in-place, returns view(a)
struct ggml_tensor * ggml_diag_mask_inf(
struct ggml_context * ctx,
struct ggml_tensor * a,
int n_past);
// in-place, returns view(a)
struct ggml_tensor * ggml_soft_max(
struct ggml_context * ctx,
struct ggml_tensor * a);
// rotary position embedding
// in-place, returns view(a)
// if mode == 1, skip n_past elements
// TODO: avoid creating a new tensor every time
struct ggml_tensor * ggml_rope(
struct ggml_context * ctx,
struct ggml_tensor * a,
int n_past,
int n_dims,
int mode);
// padding = 1
// TODO: we don't support extra parameters for now
// that's why we are hard-coding the stride, padding, and dilation
// not great ..
struct ggml_tensor * ggml_conv_1d_1s(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b);
struct ggml_tensor * ggml_conv_1d_2s(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b);
struct ggml_tensor * ggml_flash_attn(
struct ggml_context * ctx,
struct ggml_tensor * q,
struct ggml_tensor * k,
struct ggml_tensor * v,
bool masked);
struct ggml_tensor * ggml_flash_ff(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b0,
struct ggml_tensor * b1,
struct ggml_tensor * c0,
struct ggml_tensor * c1);
//
// automatic differentiation
//
void ggml_set_param(
struct ggml_context * ctx,
struct ggml_tensor * tensor);
void ggml_build_forward_expand(struct ggml_cgraph * cgraph, struct ggml_tensor * tensor);
struct ggml_cgraph ggml_build_forward (struct ggml_tensor * tensor);
struct ggml_cgraph ggml_build_backward(struct ggml_context * ctx, struct ggml_cgraph * gf, bool keep);
void ggml_graph_compute(struct ggml_context * ctx, struct ggml_cgraph * cgraph);
void ggml_graph_reset (struct ggml_cgraph * cgraph);
// print info and performance information for the graph
void ggml_graph_print(const struct ggml_cgraph * cgraph);
// dump the graph into a file using the dot format
void ggml_graph_dump_dot(const struct ggml_cgraph * gb, const struct ggml_cgraph * gf, const char * filename);
//
// optimization
//
// optimization methods
enum ggml_opt_type {
GGML_OPT_ADAM,
GGML_OPT_LBFGS,
};
// linesearch methods
enum ggml_linesearch {
GGML_LINESEARCH_DEFAULT = 1,
GGML_LINESEARCH_BACKTRACKING_ARMIJO = 0,
GGML_LINESEARCH_BACKTRACKING_WOLFE = 1,
GGML_LINESEARCH_BACKTRACKING_STRONG_WOLFE = 2,
};
// optimization return values
enum ggml_opt_result {
GGML_OPT_OK = 0,
GGML_OPT_DID_NOT_CONVERGE,
GGML_OPT_NO_CONTEXT,
GGML_OPT_INVALID_WOLFE,
GGML_OPT_FAIL,
GGML_LINESEARCH_FAIL = -128,
GGML_LINESEARCH_MINIMUM_STEP,
GGML_LINESEARCH_MAXIMUM_STEP,
GGML_LINESEARCH_MAXIMUM_ITERATIONS,
GGML_LINESEARCH_INVALID_PARAMETERS,
};
// optimization parameters
//
// see ggml.c (ggml_opt_default_params) for default values
//
struct ggml_opt_params {
enum ggml_opt_type type;
int n_threads;
// delta-based convergence test
//
// if past == 0 - disabled
// if past > 0:
// stop if |f(x) - f(x_past)| < delta * max(1, |f(x)|)
//
int past;
float delta;
// maximum number of iterations without improvement
//
// if 0 - disabled
// if > 0:
// assume convergence if no cost improvement in this number of iterations
//
int max_no_improvement;
bool print_forward_graph;
bool print_backward_graph;
// ADAM parameters
struct {
int n_iter;
float alpha; // learning rate
float beta1;
float beta2;
float eps; // epsilon for numerical stability
float eps_f; // epsilon for convergence test
float eps_g; // epsilon for convergence test
} adam;
// LBFGS parameters
struct {
int m; // number of corrections to approximate the inv. Hessian
int n_iter;
int max_linesearch;
float eps; // convergence tolerance
float ftol; // line search tolerance
float wolfe;
float min_step;
float max_step;
enum ggml_linesearch linesearch;
} lbfgs;
};
struct ggml_opt_params ggml_opt_default_params(enum ggml_opt_type type);
// optimize the function defined by the tensor f
enum ggml_opt_result ggml_opt(
struct ggml_context * ctx,
struct ggml_opt_params params,
struct ggml_tensor * f);
//
// quantization
//
size_t ggml_quantize_q4_0(const float * src, void * dst, int n, int k, int64_t * hist);
size_t ggml_quantize_q4_1(const float * src, void * dst, int n, int k, int64_t * hist);
//
// system info
//
int ggml_cpu_has_avx(void);
int ggml_cpu_has_avx2(void);
int ggml_cpu_has_avx512(void);
int ggml_cpu_has_fma(void);
int ggml_cpu_has_neon(void);
int ggml_cpu_has_arm_fma(void);
int ggml_cpu_has_f16c(void);
int ggml_cpu_has_fp16_va(void);
int ggml_cpu_has_wasm_simd(void);
int ggml_cpu_has_blas(void);
int ggml_cpu_has_sse3(void);
int ggml_cpu_has_vsx(void);
#ifdef __cplusplus
}
#endif
|
0 | repos/gpt4all.zig/src/llm | repos/gpt4all.zig/src/llm/ggml/ggml.c | // None of the below fix the "no asprintf on macos" bug in contrast to what
// stackoverflow says
#define _GNU_SOURCE
#define __GNU_SOURCE
#define __STDC_WANT_LIB_EXT2__ 1
// Defines CLOCK_MONOTONIC and asprintf on Linux
#define _POSIX_C_SOURCE 200809L // for clock_gettime()
#include "ggml.h"
#if defined(_MSC_VER) || defined(__MINGW32__)
#include <malloc.h> // using malloc.h with MSC/MINGW
#elif !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__)
#include <alloca.h>
#endif
#include <assert.h>
#include <errno.h>
#include <time.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdio.h>
#include <float.h>
// if C99 - static_assert is noop
// ref: https://stackoverflow.com/a/53923785/4039976
#ifndef static_assert
#define static_assert(cond, msg) struct global_scope_noop_trick
#endif
#if defined _MSC_VER || defined(__MINGW32__)
#if !defined(__MINGW32__)
#include <windows.h>
#else
// ref: https://github.com/ggerganov/whisper.cpp/issues/168
#include <windows.h>
#endif
typedef volatile LONG atomic_int;
typedef atomic_int atomic_bool;
static void atomic_store(atomic_int* ptr, LONG val) {
InterlockedExchange(ptr, val);
}
static LONG atomic_load(atomic_int* ptr) {
return InterlockedCompareExchange(ptr, 0, 0);
}
static LONG atomic_fetch_add(atomic_int* ptr, LONG inc) {
return InterlockedExchangeAdd(ptr, inc);
}
static LONG atomic_fetch_sub(atomic_int* ptr, LONG dec) {
return atomic_fetch_add(ptr, -(dec));
}
typedef HANDLE pthread_t;
typedef DWORD thread_ret_t;
static int pthread_create(pthread_t* out, void* unused, thread_ret_t(*func)(void*), void* arg) {
HANDLE handle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) func, arg, 0, NULL);
if (handle == NULL)
{
return EAGAIN;
}
*out = handle;
return 0;
}
static int pthread_join(pthread_t thread, void* unused) {
return (int) WaitForSingleObject(thread, INFINITE);
}
static int sched_yield (void) {
Sleep (0);
return 0;
}
#else
#include <pthread.h>
#include <stdatomic.h>
typedef void* thread_ret_t;
#endif
// __FMA__ and __F16C__ are not defined in MSVC, however they are implied with AVX2/AVX512
#if defined(_MSC_VER) && (defined(__AVX2__) || defined(__AVX512F__))
#ifndef __FMA__
#define __FMA__
#endif
#ifndef __F16C__
#define __F16C__
#endif
#ifndef __SSE3__
#define __SSE3__
#endif
#endif
#ifdef __HAIKU__
#define static_assert(cond, msg) _Static_assert(cond, msg)
#endif
#define GGML_MLOCK_SUPPORT 0
#ifdef __has_include
#if __has_include(<sys/mman.h>)
#undef GGML_MLOCK_SUPPORT
#define GGML_MLOCK_SUPPORT 1
#include <sys/mman.h>
#endif
#endif
/*#define GGML_PERF*/
#define GGML_DEBUG 0
#define GGML_GELU_FP16
#define GGML_SILU_FP16
#define GGML_SOFT_MAX_UNROLL 4
#define GGML_VEC_DOT_UNROLL 2
#ifdef GGML_USE_ACCELERATE
// uncomment to use vDSP for soft max computation
// note: not sure if it is actually faster
//#define GGML_SOFT_MAX_ACCELERATE
#endif
#if UINTPTR_MAX == 0xFFFFFFFF
#define GGML_MEM_ALIGN 4
#else
#define GGML_MEM_ALIGN 16
#endif
#define UNUSED(x) (void)(x)
#define SWAP(x, y, T) do { T SWAP = x; x = y; y = SWAP; } while (0)
#define GGML_ASSERT(x) \
do { \
if (!(x)) { \
fprintf(stderr, "GGML_ASSERT: %s:%d: %s\n", __FILE__, __LINE__, #x); \
abort(); \
} \
} while (0)
#ifdef GGML_USE_ACCELERATE
#include <Accelerate/Accelerate.h>
#elif GGML_USE_OPENBLAS
#include <cblas.h>
#endif
#undef MIN
#undef MAX
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
// floating point type used to accumulate sums
typedef double ggml_float;
// 16-bit float
// on Arm, we use __fp16
// on x86, we use uint16_t
#ifdef __ARM_NEON
// if YCM cannot find <arm_neon.h>, make a symbolic link to it, for example:
//
// $ ln -sfn /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include/arm_neon.h ./src/
//
#include <arm_neon.h>
#define GGML_COMPUTE_FP16_TO_FP32(x) ((float) (x))
#define GGML_COMPUTE_FP32_TO_FP16(x) (x)
#define GGML_FP16_TO_FP32(x) ((float) (x))
#define GGML_FP32_TO_FP16(x) (x)
#else
#ifdef __wasm_simd128__
#include <wasm_simd128.h>
#else
#ifdef __POWER9_VECTOR__
#include <altivec.h>
#undef bool
#define bool _Bool
#else
#include <immintrin.h>
#endif
#endif
#ifdef __F16C__
#ifdef _MSC_VER
#define GGML_COMPUTE_FP16_TO_FP32(x) _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128(x)))
#define GGML_COMPUTE_FP32_TO_FP16(x) _mm_extract_epi16(_mm_cvtps_ph(_mm_set_ss(x), 0), 0)
#else
#define GGML_COMPUTE_FP16_TO_FP32(x) _cvtsh_ss(x)
#define GGML_COMPUTE_FP32_TO_FP16(x) _cvtss_sh(x, 0)
#endif
#elif defined(__POWER9_VECTOR__)
#define GGML_COMPUTE_FP16_TO_FP32(x) ggml_compute_fp16_to_fp32(x)
#define GGML_COMPUTE_FP32_TO_FP16(x) ggml_compute_fp32_to_fp16(x)
/* the inline asm below is about 12% faster than the lookup method */
#define GGML_FP16_TO_FP32(x) GGML_COMPUTE_FP16_TO_FP32(x)
#define GGML_FP32_TO_FP16(x) GGML_COMPUTE_FP32_TO_FP16(x)
static inline float ggml_compute_fp16_to_fp32(ggml_fp16_t h) {
register float f;
register double d;
__asm__(
"mtfprd %0,%2\n"
"xscvhpdp %0,%0\n"
"frsp %1,%0\n" :
/* temp */ "=d"(d),
/* out */ "=f"(f):
/* in */ "r"(h));
return f;
}
static inline ggml_fp16_t ggml_compute_fp32_to_fp16(float f) {
register double d;
register ggml_fp16_t r;
__asm__( /* xscvdphp can work on double or single precision */
"xscvdphp %0,%2\n"
"mffprd %1,%0\n" :
/* temp */ "=d"(d),
/* out */ "=r"(r):
/* in */ "f"(f));
return r;
}
#else
// FP16 <-> FP32
// ref: https://github.com/Maratyszcza/FP16
static inline float fp32_from_bits(uint32_t w) {
union {
uint32_t as_bits;
float as_value;
} fp32;
fp32.as_bits = w;
return fp32.as_value;
}
static inline uint32_t fp32_to_bits(float f) {
union {
float as_value;
uint32_t as_bits;
} fp32;
fp32.as_value = f;
return fp32.as_bits;
}
static inline float ggml_compute_fp16_to_fp32(ggml_fp16_t h) {
const uint32_t w = (uint32_t) h << 16;
const uint32_t sign = w & UINT32_C(0x80000000);
const uint32_t two_w = w + w;
const uint32_t exp_offset = UINT32_C(0xE0) << 23;
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) || defined(__GNUC__) && !defined(__STRICT_ANSI__)
const float exp_scale = 0x1.0p-112f;
#else
const float exp_scale = fp32_from_bits(UINT32_C(0x7800000));
#endif
const float normalized_value = fp32_from_bits((two_w >> 4) + exp_offset) * exp_scale;
const uint32_t magic_mask = UINT32_C(126) << 23;
const float magic_bias = 0.5f;
const float denormalized_value = fp32_from_bits((two_w >> 17) | magic_mask) - magic_bias;
const uint32_t denormalized_cutoff = UINT32_C(1) << 27;
const uint32_t result = sign |
(two_w < denormalized_cutoff ? fp32_to_bits(denormalized_value) : fp32_to_bits(normalized_value));
return fp32_from_bits(result);
}
static inline ggml_fp16_t ggml_compute_fp32_to_fp16(float f) {
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) || defined(__GNUC__) && !defined(__STRICT_ANSI__)
const float scale_to_inf = 0x1.0p+112f;
const float scale_to_zero = 0x1.0p-110f;
#else
const float scale_to_inf = fp32_from_bits(UINT32_C(0x77800000));
const float scale_to_zero = fp32_from_bits(UINT32_C(0x08800000));
#endif
float base = (fabsf(f) * scale_to_inf) * scale_to_zero;
const uint32_t w = fp32_to_bits(f);
const uint32_t shl1_w = w + w;
const uint32_t sign = w & UINT32_C(0x80000000);
uint32_t bias = shl1_w & UINT32_C(0xFF000000);
if (bias < UINT32_C(0x71000000)) {
bias = UINT32_C(0x71000000);
}
base = fp32_from_bits((bias >> 1) + UINT32_C(0x07800000)) + base;
const uint32_t bits = fp32_to_bits(base);
const uint32_t exp_bits = (bits >> 13) & UINT32_C(0x00007C00);
const uint32_t mantissa_bits = bits & UINT32_C(0x00000FFF);
const uint32_t nonsign = exp_bits + mantissa_bits;
return (sign >> 16) | (shl1_w > UINT32_C(0xFF000000) ? UINT16_C(0x7E00) : nonsign);
}
#define GGML_COMPUTE_FP16_TO_FP32(x) ggml_compute_fp16_to_fp32(x)
#define GGML_COMPUTE_FP32_TO_FP16(x) ggml_compute_fp32_to_fp16(x)
#endif // __F16C__
#endif // __ARM_NEON
//
// global data
//
// precomputed gelu table for f16 (128 KB)
static ggml_fp16_t table_gelu_f16[1 << 16];
// precomputed silu table for f16 (128 KB)
static ggml_fp16_t table_silu_f16[1 << 16];
// precomputed exp table for f16 (128 KB)
static ggml_fp16_t table_exp_f16[1 << 16];
// precomputed f32 table for f16 (256 KB)
static float table_f32_f16[1 << 16];
// On ARM NEON, it's quicker to directly convert x -> x instead of calling into ggml_lookup_fp16_to_fp32,
// so we define GGML_FP16_TO_FP32 and GGML_FP32_TO_FP16 elsewhere for NEON.
// This is also true for POWER9.
#if !defined(GGML_FP16_TO_FP32) || !defined(GGML_FP32_TO_FP16)
inline static float ggml_lookup_fp16_to_fp32(ggml_fp16_t f) {
uint16_t s;
memcpy(&s, &f, sizeof(uint16_t));
return table_f32_f16[s];
}
#define GGML_FP16_TO_FP32(x) ggml_lookup_fp16_to_fp32(x)
#define GGML_FP32_TO_FP16(x) GGML_COMPUTE_FP32_TO_FP16(x)
#endif
// note: do not use these inside ggml.c
// these are meant to be used via the ggml.h API
float ggml_fp16_to_fp32(ggml_fp16_t x) {
return (float) GGML_FP16_TO_FP32(x);
}
ggml_fp16_t ggml_fp32_to_fp16(float x) {
return GGML_FP32_TO_FP16(x);
}
//
// timing
//
#if defined(_MSC_VER) || defined(__MINGW32__)
static int64_t timer_freq;
void ggml_time_init(void) {
LARGE_INTEGER frequency;
QueryPerformanceFrequency(&frequency);
timer_freq = frequency.QuadPart;
}
int64_t ggml_time_ms(void) {
LARGE_INTEGER t;
QueryPerformanceCounter(&t);
return (t.QuadPart * 1000) / timer_freq;
}
int64_t ggml_time_us(void) {
LARGE_INTEGER t;
QueryPerformanceCounter(&t);
return (t.QuadPart * 1000000) / timer_freq;
}
#else
void ggml_time_init(void) {}
int64_t ggml_time_ms(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (int64_t)ts.tv_sec*1000 + (int64_t)ts.tv_nsec/1000000;
}
int64_t ggml_time_us(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (int64_t)ts.tv_sec*1000000 + (int64_t)ts.tv_nsec/1000;
}
#endif
int64_t ggml_cycles(void) {
return clock();
}
int64_t ggml_cycles_per_ms(void) {
return CLOCKS_PER_SEC/1000;
}
#ifdef GGML_PERF
#define ggml_perf_time_ms() ggml_time_ms()
#define ggml_perf_time_us() ggml_time_us()
#define ggml_perf_cycles() ggml_cycles()
#define ggml_perf_cycles_per_ms() ggml_cycles_per_ms()
#else
#define ggml_perf_time_ms() 0
#define ggml_perf_time_us() 0
#define ggml_perf_cycles() 0
#define ggml_perf_cycles_per_ms() 0
#endif
//
// cache line
//
#if defined(__cpp_lib_hardware_interference_size)
#define CACHE_LINE_SIZE hardware_destructive_interference_size
#else
#if defined(__POWER9_VECTOR__)
#define CACHE_LINE_SIZE 128
#else
#define CACHE_LINE_SIZE 64
#endif
#endif
static const size_t CACHE_LINE_SIZE_F32 = CACHE_LINE_SIZE/sizeof(float);
//
// quantization
//
#define QK 32
// AVX routines provided by GH user Const-me
// ref: https://github.com/ggerganov/ggml/pull/27#issuecomment-1464934600
#if __AVX2__ || __AVX512F__
// Unpack 32 4-bit fields into 32 bytes
// The output vector contains 32 bytes, each one in [ 0 .. 15 ] interval
static inline __m256i bytesFromNibbles( const uint8_t* rsi )
{
// Load 16 bytes from memory
__m128i tmp = _mm_loadu_si128( ( const __m128i* )rsi );
// Expand bytes into uint16_t values
__m256i bytes = _mm256_cvtepu8_epi16( tmp );
// Unpack values into individual bytes
const __m256i lowMask = _mm256_set1_epi8( 0xF );
__m256i high = _mm256_andnot_si256( lowMask, bytes );
__m256i low = _mm256_and_si256( lowMask, bytes );
high = _mm256_slli_epi16( high, 4 );
bytes = _mm256_or_si256( low, high );
return bytes;
}
static inline __m128i packNibbles( __m256i bytes )
{
// Move bits within 16-bit lanes from 0000_abcd_0000_efgh into 0000_0000_abcd_efgh
const __m256i lowByte = _mm256_set1_epi16( 0xFF );
__m256i high = _mm256_andnot_si256( lowByte, bytes );
__m256i low = _mm256_and_si256( lowByte, bytes );
high = _mm256_srli_epi16( high, 4 );
bytes = _mm256_or_si256( low, high );
// Compress uint16_t lanes into bytes
__m128i r0 = _mm256_castsi256_si128( bytes );
__m128i r1 = _mm256_extracti128_si256( bytes, 1 );
return _mm_packus_epi16( r0, r1 );
}
#endif
// method 5
// blocks of QK elements
// represented with a single float (delta) and QK/2 8-bit ints (i.e QK 4-bit signed integer factors)
typedef struct {
float d; // delta
uint8_t qs[QK / 2]; // nibbles / quants
} block_q4_0;
static_assert(sizeof(block_q4_0) == sizeof(float) + QK / 2, "wrong q4_0 block size/padding");
// method 4
// blocks of QK elements
// represented with 2 floats (delta + min) and QK/2 8-bit ints (i.e QK 4-bit unsigned integer factors)
typedef struct {
float d;
float m;
uint8_t qs[QK / 2]; // nibbles / quants
} block_q4_1;
static_assert(sizeof(block_q4_1) == sizeof(float) * 2 + QK / 2, "wrong q4_1 block size/padding");
// reference implementation for deterministic creation of model files
static void quantize_row_q4_0_reference(const float * restrict x, block_q4_0 * restrict y, int k) {
assert(k % QK == 0);
const int nb = k / QK;
uint8_t pp[QK/2];
for (int i = 0; i < nb; i++) {
float amax = 0.0f; // absolute max
for (int l = 0; l < QK; l++) {
const float v = x[i*QK + l];
amax = MAX(amax, fabsf(v));
}
const float d = amax / ((1 << 3) - 1);
const float id = d ? 1.0f/d : 0.0f;
y[i].d = d;
for (int l = 0; l < QK; l += 2) {
const float v0 = x[i*QK + l + 0]*id;
const float v1 = x[i*QK + l + 1]*id;
const uint8_t vi0 = (int8_t)roundf(v0) + 8;
const uint8_t vi1 = (int8_t)roundf(v1) + 8;
assert(vi0 >= 0 && vi0 < 16);
assert(vi1 >= 0 && vi1 < 16);
pp[l/2] = vi0 | (vi1 << 4);
}
memcpy(y[i].qs, pp, sizeof(pp));
}
}
static void quantize_row_q4_0(const float * restrict x, void * restrict vy, int k) {
assert(k % QK == 0);
const int nb = k / QK;
block_q4_0 * restrict y = vy;
#if defined(__POWER9_VECTOR__)
const vector float v85 = vec_splats(8.5f);
for (int i = 0; i < nb; i++) {
float amax = 0.0f; // absolute max
vector float srcv [8];
vector float asrcv[8];
vector float amaxv[8];
for (int l = 0; l < 8; l++) srcv[l] = *(vector float *)(x + i*32 + 4*l);
for (int l = 0; l < 8; l++) asrcv[l] = vec_abs(srcv[l]);
for (int l = 0; l < 4; l++) amaxv[2*l] = vec_max(asrcv[2*l], asrcv[2*l+1]);
//for (int l = 0; l < 2; l++) amaxv[4*l] = vec_max(amaxv[4*l], amaxv[4*l+2]);
amaxv[0] = vec_max(amaxv[0], amaxv[2]);
amaxv[4] = vec_max(amaxv[4], amaxv[6]);
//for (int l = 0; l < 1; l++) amaxv[8*l] = vec_max(amaxv[8*l], amaxv[8*l+4]);
amaxv[0] = vec_max(amaxv[0], amaxv[4]);
amax = MAX(
MAX(vec_extract(amaxv[0], 0), vec_extract(amaxv[0], 1)),
MAX(vec_extract(amaxv[0], 2), vec_extract(amaxv[0], 3)));
const float d = amax / ((1 << 3) - 1);
const float id = d ? 1.0/d : 0.0;
y[i].d = d;
const vector float vid = vec_splats(id);
uint8_t * restrict pb = y[i].qs;
for (int l = 0; l < 8; l++) {
const vector float vf = vec_madd(srcv[l], vid, v85);
const vector signed int vi = vec_signed(vf);
pb[2*l + 0] = vec_extract(vi, 0) | (vec_extract(vi, 1) << 4);
pb[2*l + 1] = vec_extract(vi, 2) | (vec_extract(vi, 3) << 4);
}
}
#elif __ARM_NEON
for (int i = 0; i < nb; i++) {
float32x4_t srcv [8];
float32x4_t asrcv[8];
float32x4_t amaxv[8];
for (int l = 0; l < 8; l++) srcv[l] = vld1q_f32(x + i*32 + 4*l);
for (int l = 0; l < 8; l++) asrcv[l] = vabsq_f32(srcv[l]);
for (int l = 0; l < 4; l++) amaxv[2*l] = vmaxq_f32(asrcv[2*l], asrcv[2*l+1]);
for (int l = 0; l < 2; l++) amaxv[4*l] = vmaxq_f32(amaxv[4*l], amaxv[4*l+2]);
for (int l = 0; l < 1; l++) amaxv[8*l] = vmaxq_f32(amaxv[8*l], amaxv[8*l+4]);
// absolute max
const float amax = MAX(
MAX(vgetq_lane_f32(amaxv[0], 0), vgetq_lane_f32(amaxv[0], 1)),
MAX(vgetq_lane_f32(amaxv[0], 2), vgetq_lane_f32(amaxv[0], 3)));
const float d = amax / ((1 << 3) - 1);
const float id = d ? 1.0f/d : 0.0f;
y[i].d = d;
for (int l = 0; l < 8; l++) {
const float32x4_t v = vmulq_n_f32(srcv[l], id);
const float32x4_t vf = vaddq_f32(v, vdupq_n_f32(8.5f));
const int32x4_t vi = vcvtq_s32_f32(vf);
y[i].qs[2*l + 0] = vgetq_lane_s32(vi, 0) | (vgetq_lane_s32(vi, 1) << 4);
y[i].qs[2*l + 1] = vgetq_lane_s32(vi, 2) | (vgetq_lane_s32(vi, 3) << 4);
}
}
#elif defined(__AVX2__)
for (int i = 0; i < nb; i++) {
// Load elements into 4 AVX vectors
__m256 v0 = _mm256_loadu_ps( x );
__m256 v1 = _mm256_loadu_ps( x + 8 );
__m256 v2 = _mm256_loadu_ps( x + 16 );
__m256 v3 = _mm256_loadu_ps( x + 24 );
x += 32;
// Compute max(abs(e)) for the block
const __m256 signBit = _mm256_set1_ps( -0.0f );
__m256 maxAbs = _mm256_andnot_ps( signBit, v0 );
maxAbs = _mm256_max_ps( maxAbs, _mm256_andnot_ps( signBit, v1 ) );
maxAbs = _mm256_max_ps( maxAbs, _mm256_andnot_ps( signBit, v2 ) );
maxAbs = _mm256_max_ps( maxAbs, _mm256_andnot_ps( signBit, v3 ) );
__m128 max4 = _mm_max_ps( _mm256_extractf128_ps( maxAbs, 1 ), _mm256_castps256_ps128( maxAbs ) );
max4 = _mm_max_ps( max4, _mm_movehl_ps( max4, max4 ) );
max4 = _mm_max_ss( max4, _mm_movehdup_ps( max4 ) );
const float maxScalar = _mm_cvtss_f32( max4 );
// Quantize these floats
const float d = maxScalar / 7.0f;
y[i].d = d;
const float id = ( maxScalar != 0.0f ) ? 7.0f / maxScalar : 0.0f;
const __m256 mul = _mm256_set1_ps( id );
// Apply the multiplier
v0 = _mm256_mul_ps( v0, mul );
v1 = _mm256_mul_ps( v1, mul );
v2 = _mm256_mul_ps( v2, mul );
v3 = _mm256_mul_ps( v3, mul );
// Round to nearest integer
v0 = _mm256_round_ps( v0, _MM_ROUND_NEAREST );
v1 = _mm256_round_ps( v1, _MM_ROUND_NEAREST );
v2 = _mm256_round_ps( v2, _MM_ROUND_NEAREST );
v3 = _mm256_round_ps( v3, _MM_ROUND_NEAREST );
// Convert floats to integers
__m256i i0 = _mm256_cvtps_epi32( v0 );
__m256i i1 = _mm256_cvtps_epi32( v1 );
__m256i i2 = _mm256_cvtps_epi32( v2 );
__m256i i3 = _mm256_cvtps_epi32( v3 );
// Convert int32 to int16
i0 = _mm256_packs_epi32( i0, i1 ); // 0, 1, 2, 3, 8, 9, 10, 11, 4, 5, 6, 7, 12, 13, 14, 15
i2 = _mm256_packs_epi32( i2, i3 ); // 16, 17, 18, 19, 24, 25, 26, 27, 20, 21, 22, 23, 28, 29, 30, 31
// Convert int16 to int8
i0 = _mm256_packs_epi16( i0, i2 ); // 0, 1, 2, 3, 8, 9, 10, 11, 16, 17, 18, 19, 24, 25, 26, 27, 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31
// We got our precious signed bytes, but the order is now wrong
// These AVX2 pack instructions process 16-byte pieces independently
// The following instruction is fixing the order
const __m256i perm = _mm256_setr_epi32( 0, 4, 1, 5, 2, 6, 3, 7 );
i0 = _mm256_permutevar8x32_epi32( i0, perm );
// Apply offset to translate the range from [ -7 .. +7 ] into [ +1 .. +15 ]
const __m256i off = _mm256_set1_epi8( 8 );
i0 = _mm256_add_epi8( i0, off );
// Compress the vector into 4 bit/value, and store
__m128i res = packNibbles( i0 );
_mm_storeu_si128( ( __m128i* )y[i].qs, res );
}
#elif defined(__wasm_simd128__)
for (int i = 0; i < nb; i++) {
float amax = 0.0f; // absolute max
v128_t srcv [8];
v128_t asrcv[8];
v128_t amaxv[8];
for (int l = 0; l < 8; l++) srcv[l] = wasm_v128_load(x + i*32 + 4*l);
for (int l = 0; l < 8; l++) asrcv[l] = wasm_f32x4_abs(srcv[l]);
for (int l = 0; l < 4; l++) amaxv[2*l] = wasm_f32x4_max(asrcv[2*l], asrcv[2*l+1]);
for (int l = 0; l < 2; l++) amaxv[4*l] = wasm_f32x4_max(amaxv[4*l], amaxv[4*l+2]);
for (int l = 0; l < 1; l++) amaxv[8*l] = wasm_f32x4_max(amaxv[8*l], amaxv[8*l+4]);
amax = MAX(
MAX(wasm_f32x4_extract_lane(amaxv[0], 0), wasm_f32x4_extract_lane(amaxv[0], 1)),
MAX(wasm_f32x4_extract_lane(amaxv[0], 2), wasm_f32x4_extract_lane(amaxv[0], 3)));
const float d = amax / ((1 << 3) - 1);
const float id = d ? 1.0/d : 0.0;
y[i].d = d;
for (int l = 0; l < 8; l++) {
const v128_t v = wasm_f32x4_mul(srcv[l], wasm_f32x4_splat(id));
const v128_t vf = wasm_f32x4_add(v, wasm_f32x4_splat(8.5f));
const v128_t vi = wasm_i32x4_trunc_sat_f32x4(vf);
y[i].qs[2*l + 0] = wasm_i32x4_extract_lane(vi, 0) | (wasm_i32x4_extract_lane(vi, 1) << 4);
y[i].qs[2*l + 1] = wasm_i32x4_extract_lane(vi, 2) | (wasm_i32x4_extract_lane(vi, 3) << 4);
}
}
#else
// scalar
quantize_row_q4_0_reference(x, y, k);
#endif
}
static void quantize_row_q4_1_reference(const float * restrict x, void * restrict vy, int k) {
assert(k % QK == 0);
const int nb = k / QK;
block_q4_1 * restrict y = vy;
uint8_t pp[QK/2];
for (int i = 0; i < nb; i++) {
float min = FLT_MAX;
float max = -FLT_MAX;
for (int l = 0; l < QK; l++) {
const float v = x[i*QK + l];
if (v < min) min = v;
if (v > max) max = v;
}
const float d = (max - min) / ((1 << 4) - 1);
const float id = d ? 1.0f/d : 0.0f;
y[i].d = d;
y[i].m = min;
for (int l = 0; l < QK; l += 2) {
const float v0 = (x[i*QK + l + 0] - min)*id;
const float v1 = (x[i*QK + l + 1] - min)*id;
const uint8_t vi0 = roundf(v0);
const uint8_t vi1 = roundf(v1);
assert(vi0 >= 0 && vi0 < 16);
assert(vi1 >= 0 && vi1 < 16);
pp[l/2] = vi0 | (vi1 << 4);
}
memcpy(y[i].qs, pp, sizeof(pp));
}
}
static void quantize_row_q4_1(const float * restrict x, void * restrict vy, int k) {
assert(k % QK == 0);
const int nb = k / QK;
block_q4_1 * restrict y = vy;
#if defined(__AVX2__)
for (int i = 0; i < nb; i++) {
// Load elements into 4 AVX vectors
__m256 v0 = _mm256_loadu_ps( x );
__m256 v1 = _mm256_loadu_ps( x + 8 );
__m256 v2 = _mm256_loadu_ps( x + 16 );
__m256 v3 = _mm256_loadu_ps( x + 24 );
x += 32;
// Compute max for the block
__m256 vmax;
vmax = _mm256_max_ps( v0, v1 );
vmax = _mm256_max_ps( vmax, v2 );
vmax = _mm256_max_ps( vmax, v3 );
__m128 max4 = _mm_max_ps( _mm256_extractf128_ps( vmax, 1 ), _mm256_castps256_ps128( vmax ) );
max4 = _mm_max_ps( max4, _mm_movehl_ps( max4, max4 ) );
max4 = _mm_max_ss( max4, _mm_movehdup_ps( max4 ) );
const float maxScalar = _mm_cvtss_f32( max4 );
// Compute min for the block
__m256 vmin;
vmin = _mm256_min_ps( v0, v1 );
vmin = _mm256_min_ps( vmin, v2 );
vmin = _mm256_min_ps( vmin, v3 );
__m128 min4 = _mm_min_ps( _mm256_extractf128_ps( vmin, 1 ), _mm256_castps256_ps128( vmin ) );
min4 = _mm_min_ps( min4, _mm_movehl_ps( min4, min4 ) );
min4 = _mm_min_ss( min4, _mm_movehdup_ps( min4 ) );
const float minScalar = _mm_cvtss_f32( min4 );
// Quantize these floats
const float d = (maxScalar - minScalar) / ((1 << 4) - 1);
const float id = d ? 1.0f/d : 0.0f;
y[i].m = minScalar;
y[i].d = d;
// x = (x-min)*id
const __m256 mul = _mm256_set1_ps( id );
const __m256 off = _mm256_set1_ps( minScalar );
v0 = _mm256_mul_ps( _mm256_sub_ps( v0, off ), mul );
v1 = _mm256_mul_ps( _mm256_sub_ps( v1, off ), mul );
v2 = _mm256_mul_ps( _mm256_sub_ps( v2, off ), mul );
v3 = _mm256_mul_ps( _mm256_sub_ps( v3, off ), mul );
// Round to nearest integer
v0 = _mm256_round_ps( v0, _MM_ROUND_NEAREST );
v1 = _mm256_round_ps( v1, _MM_ROUND_NEAREST );
v2 = _mm256_round_ps( v2, _MM_ROUND_NEAREST );
v3 = _mm256_round_ps( v3, _MM_ROUND_NEAREST );
// Convert floats to integers
__m256i i0 = _mm256_cvtps_epi32( v0 );
__m256i i1 = _mm256_cvtps_epi32( v1 );
__m256i i2 = _mm256_cvtps_epi32( v2 );
__m256i i3 = _mm256_cvtps_epi32( v3 );
// Convert int32 to int16
i0 = _mm256_packs_epi32( i0, i1 ); // 0, 1, 2, 3, 8, 9, 10, 11, 4, 5, 6, 7, 12, 13, 14, 15
i2 = _mm256_packs_epi32( i2, i3 ); // 16, 17, 18, 19, 24, 25, 26, 27, 20, 21, 22, 23, 28, 29, 30, 31
// Convert int16 to int8
i0 = _mm256_packs_epi16( i0, i2 ); // 0, 1, 2, 3, 8, 9, 10, 11, 16, 17, 18, 19, 24, 25, 26, 27, 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31
// We got our precious signed bytes, but the order is now wrong
// These AVX2 pack instructions process 16-byte pieces independently
// The following instruction is fixing the order
const __m256i perm = _mm256_setr_epi32( 0, 4, 1, 5, 2, 6, 3, 7 );
i0 = _mm256_permutevar8x32_epi32( i0, perm );
// Compress the vector into 4 bit/value, and store
__m128i res = packNibbles( i0 );
_mm_storeu_si128( ( __m128i* )y[i].qs, res );
}
#elif __ARM_NEON
for (int i = 0; i < nb; i++) {
float32x4_t srcv[8];
float32x4_t minv[8];
float32x4_t maxv[8];
for (int l = 0; l < 8; l++) srcv[l] = vld1q_f32(x + i*32 + 4*l);
for (int l = 0; l < 4; l++) minv[2*l] = vminq_f32(srcv[2*l], srcv[2*l + 1]);
for (int l = 0; l < 2; l++) minv[4*l] = vminq_f32(minv[4*l], minv[4*l + 2]);
for (int l = 0; l < 1; l++) minv[8*l] = vminq_f32(minv[8*l], minv[8*l + 4]);
for (int l = 0; l < 4; l++) maxv[2*l] = vmaxq_f32(srcv[2*l], srcv[2*l + 1]);
for (int l = 0; l < 2; l++) maxv[4*l] = vmaxq_f32(maxv[4*l], maxv[4*l + 2]);
for (int l = 0; l < 1; l++) maxv[8*l] = vmaxq_f32(maxv[8*l], maxv[8*l + 4]);
const float min = vminvq_f32(minv[0]);
const float max = vmaxvq_f32(maxv[0]);
const float d = (max - min) / ((1 << 4) - 1);
const float id = d ? 1.0f/d : 0.0f;
y[i].d = d;
y[i].m = min;
const float32x4_t minv0 = vdupq_n_f32(min);
for (int l = 0; l < 8; l++) {
const float32x4_t v = vmulq_n_f32(vsubq_f32(srcv[l], minv0), id);
const int32x4_t vi = vcvtq_s32_f32(v);
y[i].qs[2*l + 0] = vgetq_lane_s32(vi, 0) | (vgetq_lane_s32(vi, 1) << 4);
y[i].qs[2*l + 1] = vgetq_lane_s32(vi, 2) | (vgetq_lane_s32(vi, 3) << 4);
}
}
#else
// scalar
quantize_row_q4_1_reference(x, vy, k);
#endif
}
static void dequantize_row_q4_0(const void * restrict vx, float * restrict y, int k) {
assert(k % QK == 0);
const int nb = k / QK;
const block_q4_0 * restrict x = vx;
#if defined(__AVX2__)
for (int i = 0; i < nb; i++) {
// scale factor
const __m256 d_v = _mm256_broadcast_ss(&x[i].d);
const uint8_t * restrict pp = x[i].qs;
for (int l = 0; l < QK; l += 32) {
// Load 32x4-bit integers into 32x8-bit integers
__m256i vx8 = bytesFromNibbles(pp+l/2);
// Subtract 8 from the integers
vx8 = _mm256_sub_epi8(vx8, _mm256_set1_epi8(8));
// Convert to 16-bit int
const __m256i vx16_lo = _mm256_cvtepi8_epi16(_mm256_extracti128_si256(vx8, 0));
const __m256i vx16_hi = _mm256_cvtepi8_epi16(_mm256_extracti128_si256(vx8, 1));
// Convert to 32-bit int -> float 32
const __m256 vf[4] = {
_mm256_cvtepi32_ps(_mm256_cvtepi16_epi32(_mm256_extracti128_si256(vx16_lo, 0))),
_mm256_cvtepi32_ps(_mm256_cvtepi16_epi32(_mm256_extracti128_si256(vx16_lo, 1))),
_mm256_cvtepi32_ps(_mm256_cvtepi16_epi32(_mm256_extracti128_si256(vx16_hi, 0))),
_mm256_cvtepi32_ps(_mm256_cvtepi16_epi32(_mm256_extracti128_si256(vx16_hi, 1)))
};
// Scale and store
for (int j = 0; j < 4; j++) {
const __m256 result = _mm256_mul_ps(vf[j], d_v);
_mm256_storeu_ps(y + i * QK + l + j*8, result);
}
}
}
#elif defined(__ARM_NEON)
for (int i = 0; i < nb; i++) {
const float32x4_t vd = vdupq_n_f32(x[i].d);
const uint8_t * restrict pp = x[i].qs;
for (int l = 0; l < QK; l += 16) {
// Load 16x4-bit integers into 8x8-bit integers
const uint8x8_t v8 = vld1_u8(pp + l/2);
// Expand 4-bit qs to 8-bit bytes
const uint8x8_t v0 = vand_u8(v8, vdup_n_u8(0x0f));
const uint8x8_t v1 = vshr_n_u8(v8, 4);
// Convert to signed 8-bit integers
const int8x8_t vs_0 = vreinterpret_s8_u8(v0);
const int8x8_t vs_1 = vreinterpret_s8_u8(v1);
// Subtract 8 from each byte
const int8x8_t vb_0 = vsub_s8(vs_0, vdup_n_s8(8));
const int8x8_t vb_1 = vsub_s8(vs_1, vdup_n_s8(8));
// Interleave and combine
const int8x8_t vx_0 = vzip1_s8(vb_0, vb_1);
const int8x8_t vx_1 = vzip2_s8(vb_0, vb_1);
const int8x16_t vq = vcombine_s8(vx_0, vx_1);
// convert to 2x int16x8_t
const int16x8_t vi_0 = vmovl_s8(vget_low_s8 (vq));
const int16x8_t vi_1 = vmovl_s8(vget_high_s8(vq));
// convert to 4x float32x4_t
const float32x4_t vf_0 = vcvtq_f32_s32(vmovl_s16(vget_low_s16 (vi_0)));
const float32x4_t vf_1 = vcvtq_f32_s32(vmovl_s16(vget_high_s16(vi_0)));
const float32x4_t vf_2 = vcvtq_f32_s32(vmovl_s16(vget_low_s16 (vi_1)));
const float32x4_t vf_3 = vcvtq_f32_s32(vmovl_s16(vget_high_s16(vi_1)));
// Multiply by d
const float32x4_t r0 = vmulq_f32(vf_0, vd);
const float32x4_t r1 = vmulq_f32(vf_1, vd);
const float32x4_t r2 = vmulq_f32(vf_2, vd);
const float32x4_t r3 = vmulq_f32(vf_3, vd);
// Store
vst1q_f32(y + i*QK + l + 0, r0);
vst1q_f32(y + i*QK + l + 4, r1);
vst1q_f32(y + i*QK + l + 8, r2);
vst1q_f32(y + i*QK + l + 12, r3);
}
}
#else
// scalar
for (int i = 0; i < nb; i++) {
const float d = x[i].d;
const uint8_t * restrict pp = x[i].qs;
for (int l = 0; l < QK; l += 2) {
const uint8_t vi = pp[l/2];
const int8_t vi0 = vi & 0xf;
const int8_t vi1 = vi >> 4;
const float v0 = (vi0 - 8)*d;
const float v1 = (vi1 - 8)*d;
//printf("d = %f, vi = %d, vi0 = %d, vi1 = %d, v0 = %f, v1 = %f\n", d, vi, vi0, vi1, v0, v1);
y[i*QK + l + 0] = v0;
y[i*QK + l + 1] = v1;
assert(!isnan(y[i*QK + l + 0]));
assert(!isnan(y[i*QK + l + 1]));
}
}
#endif
}
static void dequantize_row_q4_1(const void * restrict vx, float * restrict y, int k) {
assert(k % QK == 0);
const int nb = k / QK;
const block_q4_1 * restrict x = vx;
#if defined(__AVX2__)
for (int i = 0; i < nb; i++) {
const __m256 d_v = _mm256_broadcast_ss(&x[i].d);
const __m256 d_m = _mm256_broadcast_ss(&x[i].m);
const uint8_t * restrict pp = x[i].qs;
for (int l = 0; l < QK; l += 32) {
// Load 32x4-bit integers into 32x8-bit integers
__m256i vx8 = bytesFromNibbles(pp+l/2);
// Convert to 16-bit int
const __m256i vx16_lo = _mm256_cvtepi8_epi16(_mm256_extracti128_si256(vx8, 0));
const __m256i vx16_hi = _mm256_cvtepi8_epi16(_mm256_extracti128_si256(vx8, 1));
// Convert to 32-bit int -> float 32
const __m256 vf[4] = {
_mm256_cvtepi32_ps(_mm256_cvtepi16_epi32(_mm256_extracti128_si256(vx16_lo, 0))),
_mm256_cvtepi32_ps(_mm256_cvtepi16_epi32(_mm256_extracti128_si256(vx16_lo, 1))),
_mm256_cvtepi32_ps(_mm256_cvtepi16_epi32(_mm256_extracti128_si256(vx16_hi, 0))),
_mm256_cvtepi32_ps(_mm256_cvtepi16_epi32(_mm256_extracti128_si256(vx16_hi, 1)))
};
// Scale, add m and store
for (int j = 0; j < 4; j++) {
const __m256 result = _mm256_add_ps(_mm256_mul_ps(vf[j], d_v), d_m);
_mm256_storeu_ps(y + i * QK + l + j*8, result);
}
}
}
#elif defined(__ARM_NEON)
for (int i = 0; i < nb; i++) {
const float32x4_t vd = vdupq_n_f32(x[i].d);
const float32x4_t vm = vdupq_n_f32(x[i].m);
const uint8_t * restrict pp = x[i].qs;
for (int l = 0; l < QK; l += 16) {
// Load 16x4-bit integers into 8x8-bit integers
const uint8x8_t v8 = vld1_u8(pp + l/2);
// Expand 4-bit qs to 8-bit bytes
const uint8x8_t v0 = vand_u8(v8, vdup_n_u8(0x0f));
const uint8x8_t v1 = vshr_n_u8(v8, 4);
// Interleave and combine
const uint8x8_t vx_0 = vzip1_u8(v0, v1);
const uint8x8_t vx_1 = vzip2_u8(v0, v1);
const uint8x16_t vq = vcombine_u8(vx_0, vx_1);
// convert to 2x uint16x8_t
const uint16x8_t vi_0 = vmovl_u8(vget_low_u8 (vq));
const uint16x8_t vi_1 = vmovl_u8(vget_high_u8(vq));
// convert to 4x float32x4_t
const float32x4_t vf_0 = vcvtq_f32_u32(vmovl_u16(vget_low_u16 (vi_0)));
const float32x4_t vf_1 = vcvtq_f32_u32(vmovl_u16(vget_high_u16(vi_0)));
const float32x4_t vf_2 = vcvtq_f32_u32(vmovl_u16(vget_low_u16 (vi_1)));
const float32x4_t vf_3 = vcvtq_f32_u32(vmovl_u16(vget_high_u16(vi_1)));
// multiply by d and add m
const float32x4_t r0 = vmlaq_f32(vm, vf_0, vd);
const float32x4_t r1 = vmlaq_f32(vm, vf_1, vd);
const float32x4_t r2 = vmlaq_f32(vm, vf_2, vd);
const float32x4_t r3 = vmlaq_f32(vm, vf_3, vd);
// Store
vst1q_f32(y + i*QK + l + 0, r0);
vst1q_f32(y + i*QK + l + 4, r1);
vst1q_f32(y + i*QK + l + 8, r2);
vst1q_f32(y + i*QK + l + 12, r3);
}
}
#else
for (int i = 0; i < nb; i++) {
const float d = x[i].d;
const float m = x[i].m;
const uint8_t * restrict pp = x[i].qs;
for (int l = 0; l < QK; l += 2) {
const uint8_t vi = pp[l/2];
const int8_t vi0 = vi & 0xf;
const int8_t vi1 = vi >> 4;
const float v0 = vi0*d + m;
const float v1 = vi1*d + m;
y[i*QK + l + 0] = v0;
y[i*QK + l + 1] = v1;
assert(!isnan(y[i*QK + l + 0]));
assert(!isnan(y[i*QK + l + 1]));
}
}
#endif
}
//
// simd mappings
//
// we define a common set of C macros which map to specific intrinsics based on the current architecture
// we then implement the fundamental computation operations below using only these macros
// adding support for new architectures requires to define the corresponding SIMD macros
//
// GGML_F32_STEP / GGML_F16_STEP
// number of elements to process in a single step
//
// GGML_F32_EPR / GGML_F16_EPR
// number of elements to fit in a single register
//
#if defined(__ARM_NEON) && defined(__ARM_FEATURE_FMA)
#define GGML_SIMD
// F32 NEON
#define GGML_F32_STEP 16
#define GGML_F32_EPR 4
#define GGML_F32x4 float32x4_t
#define GGML_F32x4_ZERO vdupq_n_f32(0.0f)
#define GGML_F32x4_SET1(x) vdupq_n_f32(x)
#define GGML_F32x4_LOAD vld1q_f32
#define GGML_F32x4_STORE vst1q_f32
#define GGML_F32x4_FMA(a, b, c) vfmaq_f32(a, b, c)
#define GGML_F32x4_ADD vaddq_f32
#define GGML_F32x4_MUL vmulq_f32
#if defined(__ARM_FEATURE_QRDMX)
#define GGML_F32x4_REDUCE_ONE(x) vaddvq_f32(x)
#else
#define GGML_F32x4_REDUCE_ONE(x) \
(vgetq_lane_f32(x, 0) + \
vgetq_lane_f32(x, 1) + \
vgetq_lane_f32(x, 2) + \
vgetq_lane_f32(x, 3))
#endif
#define GGML_F32x4_REDUCE(res, x) \
{ \
for (int i = 0; i < GGML_F32_ARR/2; ++i) { \
x[2*i] = vaddq_f32(x[2*i], x[2*i+1]); \
} \
for (int i = 0; i < GGML_F32_ARR/4; ++i) { \
x[4*i] = vaddq_f32(x[4*i], x[4*i+2]); \
} \
for (int i = 0; i < GGML_F32_ARR/8; ++i) { \
x[8*i] = vaddq_f32(x[8*i], x[8*i+4]); \
} \
res = GGML_F32x4_REDUCE_ONE(x[0]); \
}
#define GGML_F32_VEC GGML_F32x4
#define GGML_F32_VEC_ZERO GGML_F32x4_ZERO
#define GGML_F32_VEC_SET1 GGML_F32x4_SET1
#define GGML_F32_VEC_LOAD GGML_F32x4_LOAD
#define GGML_F32_VEC_STORE GGML_F32x4_STORE
#define GGML_F32_VEC_FMA GGML_F32x4_FMA
#define GGML_F32_VEC_ADD GGML_F32x4_ADD
#define GGML_F32_VEC_MUL GGML_F32x4_MUL
#define GGML_F32_VEC_REDUCE GGML_F32x4_REDUCE
// F16 NEON
#if defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC)
#define GGML_F16_STEP 32
#define GGML_F16_EPR 8
#define GGML_F16x8 float16x8_t
#define GGML_F16x8_ZERO vdupq_n_f16(0.0f)
#define GGML_F16x8_SET1(x) vdupq_n_f16(x)
#define GGML_F16x8_LOAD vld1q_f16
#define GGML_F16x8_STORE vst1q_f16
#define GGML_F16x8_FMA(a, b, c) vfmaq_f16(a, b, c)
#define GGML_F16x8_ADD vaddq_f16
#define GGML_F16x8_MUL vmulq_f16
#define GGML_F16x8_REDUCE(res, x) \
{ \
for (int i = 0; i < GGML_F16_ARR/2; ++i) { \
x[2*i] = vaddq_f16(x[2*i], x[2*i+1]); \
} \
for (int i = 0; i < GGML_F16_ARR/4; ++i) { \
x[4*i] = vaddq_f16(x[4*i], x[4*i+2]); \
} \
for (int i = 0; i < GGML_F16_ARR/8; ++i) { \
x[8*i] = vaddq_f16(x[8*i], x[8*i+4]); \
} \
const float32x4_t t0 = vcvt_f32_f16(vget_low_f16 (x[0])); \
const float32x4_t t1 = vcvt_f32_f16(vget_high_f16(x[0])); \
res = (ggml_float) vaddvq_f32(vaddq_f32(t0, t1)); \
}
#define GGML_F16_VEC GGML_F16x8
#define GGML_F16_VEC_ZERO GGML_F16x8_ZERO
#define GGML_F16_VEC_SET1 GGML_F16x8_SET1
#define GGML_F16_VEC_LOAD(p, i) GGML_F16x8_LOAD(p)
#define GGML_F16_VEC_STORE(p, r, i) GGML_F16x8_STORE(p, r[i])
#define GGML_F16_VEC_FMA GGML_F16x8_FMA
#define GGML_F16_VEC_ADD GGML_F16x8_ADD
#define GGML_F16_VEC_MUL GGML_F16x8_MUL
#define GGML_F16_VEC_REDUCE GGML_F16x8_REDUCE
#else
// if FP16 vector arithmetic is not supported, we use FP32 instead
// and take advantage of the vcvt_ functions to convert to/from FP16
#define GGML_F16_STEP 16
#define GGML_F16_EPR 4
#define GGML_F32Cx4 float32x4_t
#define GGML_F32Cx4_ZERO vdupq_n_f32(0.0f)
#define GGML_F32Cx4_SET1(x) vdupq_n_f32(x)
#define GGML_F32Cx4_LOAD(x) vcvt_f32_f16(vld1_f16(x))
#define GGML_F32Cx4_STORE(x, y) vst1_f16(x, vcvt_f16_f32(y))
#define GGML_F32Cx4_FMA(a, b, c) vfmaq_f32(a, b, c)
#define GGML_F32Cx4_ADD vaddq_f32
#define GGML_F32Cx4_MUL vmulq_f32
#define GGML_F32Cx4_REDUCE GGML_F32x4_REDUCE
#define GGML_F16_VEC GGML_F32Cx4
#define GGML_F16_VEC_ZERO GGML_F32Cx4_ZERO
#define GGML_F16_VEC_SET1 GGML_F32Cx4_SET1
#define GGML_F16_VEC_LOAD(p, i) GGML_F32Cx4_LOAD(p)
#define GGML_F16_VEC_STORE(p, r, i) GGML_F32Cx4_STORE(p, r[i])
#define GGML_F16_VEC_FMA GGML_F32Cx4_FMA
#define GGML_F16_VEC_ADD GGML_F32Cx4_ADD
#define GGML_F16_VEC_MUL GGML_F32Cx4_MUL
#define GGML_F16_VEC_REDUCE GGML_F32Cx4_REDUCE
#endif
#elif defined(__AVX__)
#define GGML_SIMD
// F32 AVX
#define GGML_F32_STEP 32
#define GGML_F32_EPR 8
#define GGML_F32x8 __m256
#define GGML_F32x8_ZERO _mm256_setzero_ps()
#define GGML_F32x8_SET1(x) _mm256_set1_ps(x)
#define GGML_F32x8_LOAD _mm256_loadu_ps
#define GGML_F32x8_STORE _mm256_storeu_ps
#if defined(__FMA__)
#define GGML_F32x8_FMA(a, b, c) _mm256_fmadd_ps(b, c, a)
#else
#define GGML_F32x8_FMA(a, b, c) _mm256_add_ps(_mm256_mul_ps(b, c), a)
#endif
#define GGML_F32x8_ADD _mm256_add_ps
#define GGML_F32x8_MUL _mm256_mul_ps
#define GGML_F32x8_REDUCE(res, x) \
{ \
for (int i = 0; i < GGML_F32_ARR/2; ++i) { \
x[2*i] = _mm256_add_ps(x[2*i], x[2*i+1]); \
} \
for (int i = 0; i < GGML_F32_ARR/4; ++i) { \
x[4*i] = _mm256_add_ps(x[4*i], x[4*i+2]); \
} \
for (int i = 0; i < GGML_F32_ARR/8; ++i) { \
x[8*i] = _mm256_add_ps(x[8*i], x[8*i+4]); \
} \
const __m128 t0 = _mm_add_ps(_mm256_castps256_ps128(x[0]), \
_mm256_extractf128_ps(x[0], 1)); \
const __m128 t1 = _mm_hadd_ps(t0, t0); \
res = _mm_cvtss_f32(_mm_hadd_ps(t1, t1)); \
}
// TODO: is this optimal ?
#define GGML_F32_VEC GGML_F32x8
#define GGML_F32_VEC_ZERO GGML_F32x8_ZERO
#define GGML_F32_VEC_SET1 GGML_F32x8_SET1
#define GGML_F32_VEC_LOAD GGML_F32x8_LOAD
#define GGML_F32_VEC_STORE GGML_F32x8_STORE
#define GGML_F32_VEC_FMA GGML_F32x8_FMA
#define GGML_F32_VEC_ADD GGML_F32x8_ADD
#define GGML_F32_VEC_MUL GGML_F32x8_MUL
#define GGML_F32_VEC_REDUCE GGML_F32x8_REDUCE
// F16 AVX
#define GGML_F16_STEP 32
#define GGML_F16_EPR 8
// F16 arithmetic is not supported by AVX, so we use F32 instead
#define GGML_F32Cx8 __m256
#define GGML_F32Cx8_ZERO _mm256_setzero_ps()
#define GGML_F32Cx8_SET1(x) _mm256_set1_ps(x)
#if defined(__F16C__)
// the _mm256_cvt intrinsics require F16C
#define GGML_F32Cx8_LOAD(x) _mm256_cvtph_ps(_mm_loadu_si128((__m128i *)(x)))
#define GGML_F32Cx8_STORE(x, y) _mm_storeu_si128((__m128i *)(x), _mm256_cvtps_ph(y, 0))
#else
static inline __m256 __avx_f32cx8_load(ggml_fp16_t *x) {
float tmp[8];
for (int i = 0; i < 8; i++)
tmp[i] = GGML_FP16_TO_FP32(x[i]);
return _mm256_loadu_ps(tmp);
}
static inline void __avx_f32cx8_store(ggml_fp16_t *x, __m256 y) {
float arr[8];
_mm256_storeu_ps(arr, y);
for (int i = 0; i < 8; i++)
x[i] = GGML_FP16_TO_FP32(arr[i]);
}
#define GGML_F32Cx8_LOAD(x) __avx_f32cx8_load(x)
#define GGML_F32Cx8_STORE(x, y) __avx_f32cx8_store(x, y)
#endif
#define GGML_F32Cx8_FMA GGML_F32x8_FMA
#define GGML_F32Cx8_ADD _mm256_add_ps
#define GGML_F32Cx8_MUL _mm256_mul_ps
#define GGML_F32Cx8_REDUCE GGML_F32x8_REDUCE
#define GGML_F16_VEC GGML_F32Cx8
#define GGML_F16_VEC_ZERO GGML_F32Cx8_ZERO
#define GGML_F16_VEC_SET1 GGML_F32Cx8_SET1
#define GGML_F16_VEC_LOAD(p, i) GGML_F32Cx8_LOAD(p)
#define GGML_F16_VEC_STORE(p, r, i) GGML_F32Cx8_STORE(p, r[i])
#define GGML_F16_VEC_FMA GGML_F32Cx8_FMA
#define GGML_F16_VEC_ADD GGML_F32Cx8_ADD
#define GGML_F16_VEC_MUL GGML_F32Cx8_MUL
#define GGML_F16_VEC_REDUCE GGML_F32Cx8_REDUCE
#elif defined(__POWER9_VECTOR__)
#define GGML_SIMD
// F32 POWER9
#define GGML_F32_STEP 32
#define GGML_F32_EPR 4
#define GGML_F32x4 vector float
#define GGML_F32x4_ZERO 0.0f
#define GGML_F32x4_SET1 vec_splats
#define GGML_F32x4_LOAD(p) vec_xl(0, p)
#define GGML_F32x4_STORE(p, r) vec_xst(r, 0, p)
#define GGML_F32x4_FMA(a, b, c) vec_madd(b, c, a)
#define GGML_F32x4_ADD vec_add
#define GGML_F32x4_MUL vec_mul
#define GGML_F32x4_REDUCE(res, x) \
{ \
for (int i = 0; i < GGML_F32_ARR/2; ++i) { \
x[2*i] = vec_add(x[2*i], x[2*i+1]); \
} \
for (int i = 0; i < GGML_F32_ARR/4; ++i) { \
x[4*i] = vec_add(x[4*i], x[4*i+2]); \
} \
for (int i = 0; i < GGML_F32_ARR/8; ++i) { \
x[8*i] = vec_add(x[8*i], x[8*i+4]); \
} \
res = vec_extract(x[0], 0) + \
vec_extract(x[0], 1) + \
vec_extract(x[0], 2) + \
vec_extract(x[0], 3); \
}
#define GGML_F32_VEC GGML_F32x4
#define GGML_F32_VEC_ZERO GGML_F32x4_ZERO
#define GGML_F32_VEC_SET1 GGML_F32x4_SET1
#define GGML_F32_VEC_LOAD GGML_F32x4_LOAD
#define GGML_F32_VEC_STORE GGML_F32x4_STORE
#define GGML_F32_VEC_FMA GGML_F32x4_FMA
#define GGML_F32_VEC_ADD GGML_F32x4_ADD
#define GGML_F32_VEC_MUL GGML_F32x4_MUL
#define GGML_F32_VEC_REDUCE GGML_F32x4_REDUCE
// F16 POWER9
#define GGML_F16_STEP GGML_F32_STEP
#define GGML_F16_EPR GGML_F32_EPR
#define GGML_F16_VEC GGML_F32x4
#define GGML_F16_VEC_ZERO GGML_F32x4_ZERO
#define GGML_F16_VEC_SET1 GGML_F32x4_SET1
#define GGML_F16_VEC_FMA GGML_F32x4_FMA
#define GGML_F16_VEC_REDUCE GGML_F32x4_REDUCE
// Use vec_xl, not vec_ld, in case the load address is not aligned.
#define GGML_F16_VEC_LOAD(p, i) (i & 0x1) ? \
vec_extract_fp32_from_shorth(vec_xl(0, p - GGML_F16_EPR)) : \
vec_extract_fp32_from_shortl(vec_xl(0, p))
#define GGML_ENDIAN_BYTE(i) ((unsigned char *)&(uint16_t){1})[i]
#define GGML_F16_VEC_STORE(p, r, i) \
if (i & 0x1) \
vec_xst(vec_pack_to_short_fp32(r[i - GGML_ENDIAN_BYTE(1)], \
r[i - GGML_ENDIAN_BYTE(0)]), \
0, p - GGML_F16_EPR)
#elif defined(__wasm_simd128__)
#define GGML_SIMD
// F32 WASM
#define GGML_F32_STEP 16
#define GGML_F32_EPR 4
#define GGML_F32x4 v128_t
#define GGML_F32x4_ZERO wasm_f32x4_splat(0.0f)
#define GGML_F32x4_SET1(x) wasm_f32x4_splat(x)
#define GGML_F32x4_LOAD wasm_v128_load
#define GGML_F32x4_STORE wasm_v128_store
#define GGML_F32x4_FMA(a, b, c) wasm_f32x4_add(wasm_f32x4_mul(b, c), a)
#define GGML_F32x4_ADD wasm_f32x4_add
#define GGML_F32x4_MUL wasm_f32x4_mul
#define GGML_F32x4_REDUCE(res, x) \
{ \
for (int i = 0; i < GGML_F32_ARR/2; ++i) { \
x[2*i] = wasm_f32x4_add(x[2*i], x[2*i+1]); \
} \
for (int i = 0; i < GGML_F32_ARR/4; ++i) { \
x[4*i] = wasm_f32x4_add(x[4*i], x[4*i+2]); \
} \
for (int i = 0; i < GGML_F32_ARR/8; ++i) { \
x[8*i] = wasm_f32x4_add(x[8*i], x[8*i+4]); \
} \
res = wasm_f32x4_extract_lane(x[0], 0) + \
wasm_f32x4_extract_lane(x[0], 1) + \
wasm_f32x4_extract_lane(x[0], 2) + \
wasm_f32x4_extract_lane(x[0], 3); \
}
#define GGML_F32_VEC GGML_F32x4
#define GGML_F32_VEC_ZERO GGML_F32x4_ZERO
#define GGML_F32_VEC_SET1 GGML_F32x4_SET1
#define GGML_F32_VEC_LOAD GGML_F32x4_LOAD
#define GGML_F32_VEC_STORE GGML_F32x4_STORE
#define GGML_F32_VEC_FMA GGML_F32x4_FMA
#define GGML_F32_VEC_ADD GGML_F32x4_ADD
#define GGML_F32_VEC_MUL GGML_F32x4_MUL
#define GGML_F32_VEC_REDUCE GGML_F32x4_REDUCE
// F16 WASM
#define GGML_F16_STEP 16
#define GGML_F16_EPR 4
inline static v128_t __wasm_f16x4_load(const ggml_fp16_t * p) {
float tmp[4];
tmp[0] = GGML_FP16_TO_FP32(p[0]);
tmp[1] = GGML_FP16_TO_FP32(p[1]);
tmp[2] = GGML_FP16_TO_FP32(p[2]);
tmp[3] = GGML_FP16_TO_FP32(p[3]);
return wasm_v128_load(tmp);
}
inline static void __wasm_f16x4_store(ggml_fp16_t * p, v128_t x) {
float tmp[4];
wasm_v128_store(tmp, x);
p[0] = GGML_FP32_TO_FP16(tmp[0]);
p[1] = GGML_FP32_TO_FP16(tmp[1]);
p[2] = GGML_FP32_TO_FP16(tmp[2]);
p[3] = GGML_FP32_TO_FP16(tmp[3]);
}
#define GGML_F16x4 v128_t
#define GGML_F16x4_ZERO wasm_f32x4_splat(0.0f)
#define GGML_F16x4_SET1(x) wasm_f32x4_splat(x)
#define GGML_F16x4_LOAD(x) __wasm_f16x4_load(x)
#define GGML_F16x4_STORE(x, y) __wasm_f16x4_store(x, y)
#define GGML_F16x4_FMA GGML_F32x4_FMA
#define GGML_F16x4_ADD wasm_f32x4_add
#define GGML_F16x4_MUL wasm_f32x4_mul
#define GGML_F16x4_REDUCE(res, x) \
{ \
for (int i = 0; i < GGML_F16_ARR/2; ++i) { \
x[2*i] = wasm_f32x4_add(x[2*i], x[2*i+1]); \
} \
for (int i = 0; i < GGML_F16_ARR/4; ++i) { \
x[4*i] = wasm_f32x4_add(x[4*i], x[4*i+2]); \
} \
for (int i = 0; i < GGML_F16_ARR/8; ++i) { \
x[8*i] = wasm_f32x4_add(x[8*i], x[8*i+4]); \
} \
res = wasm_f32x4_extract_lane(x[0], 0) + \
wasm_f32x4_extract_lane(x[0], 1) + \
wasm_f32x4_extract_lane(x[0], 2) + \
wasm_f32x4_extract_lane(x[0], 3); \
}
#define GGML_F16_VEC GGML_F16x4
#define GGML_F16_VEC_ZERO GGML_F16x4_ZERO
#define GGML_F16_VEC_SET1 GGML_F16x4_SET1
#define GGML_F16_VEC_LOAD(p, i) GGML_F16x4_LOAD(p)
#define GGML_F16_VEC_STORE(p, r, i) GGML_F16x4_STORE(p, r[i])
#define GGML_F16_VEC_FMA GGML_F16x4_FMA
#define GGML_F16_VEC_ADD GGML_F16x4_ADD
#define GGML_F16_VEC_MUL GGML_F16x4_MUL
#define GGML_F16_VEC_REDUCE GGML_F16x4_REDUCE
#elif defined(__SSE3__)
#define GGML_SIMD
// F32 SSE
#define GGML_F32_STEP 32
#define GGML_F32_EPR 4
#define GGML_F32x4 __m128
#define GGML_F32x4_ZERO _mm_setzero_ps()
#define GGML_F32x4_SET1(x) _mm_set1_ps(x)
#define GGML_F32x4_LOAD _mm_loadu_ps
#define GGML_F32x4_STORE _mm_storeu_ps
#if defined(__FMA__)
// TODO: Does this work?
#define GGML_F32x4_FMA(a, b, c) _mm_fmadd_ps(b, c, a)
#else
#define GGML_F32x4_FMA(a, b, c) _mm_add_ps(_mm_mul_ps(b, c), a)
#endif
#define GGML_F32x4_ADD _mm_add_ps
#define GGML_F32x4_MUL _mm_mul_ps
#define GGML_F32x4_REDUCE(res, x) \
{ \
for (int i = 0; i < GGML_F32_ARR/2; ++i) { \
x[2*i] = _mm_add_ps(x[2*i], x[2*i+1]); \
} \
for (int i = 0; i < GGML_F32_ARR/4; ++i) { \
x[4*i] = _mm_add_ps(x[4*i], x[4*i+2]); \
} \
for (int i = 0; i < GGML_F32_ARR/8; ++i) { \
x[8*i] = _mm_add_ps(x[8*i], x[8*i+4]); \
} \
const __m128 t0 = _mm_hadd_ps(x[0], x[0]); \
res = _mm_cvtss_f32(_mm_hadd_ps(t0, t0)); \
}
// TODO: is this optimal ?
#define GGML_F32_VEC GGML_F32x4
#define GGML_F32_VEC_ZERO GGML_F32x4_ZERO
#define GGML_F32_VEC_SET1 GGML_F32x4_SET1
#define GGML_F32_VEC_LOAD GGML_F32x4_LOAD
#define GGML_F32_VEC_STORE GGML_F32x4_STORE
#define GGML_F32_VEC_FMA GGML_F32x4_FMA
#define GGML_F32_VEC_ADD GGML_F32x4_ADD
#define GGML_F32_VEC_MUL GGML_F32x4_MUL
#define GGML_F32_VEC_REDUCE GGML_F32x4_REDUCE
// F16 SSE
#define GGML_F16_STEP 32
#define GGML_F16_EPR 4
static inline __m128 __sse_f16x4_load(ggml_fp16_t *x) {
float tmp[4];
tmp[0] = GGML_FP16_TO_FP32(x[0]);
tmp[1] = GGML_FP16_TO_FP32(x[1]);
tmp[2] = GGML_FP16_TO_FP32(x[2]);
tmp[3] = GGML_FP16_TO_FP32(x[3]);
return _mm_loadu_ps(tmp);
}
static inline void __sse_f16x4_store(ggml_fp16_t *x, __m128 y) {
float arr[4];
_mm_storeu_ps(arr, y);
x[0] = GGML_FP32_TO_FP16(arr[0]);
x[1] = GGML_FP32_TO_FP16(arr[1]);
x[2] = GGML_FP32_TO_FP16(arr[2]);
x[3] = GGML_FP32_TO_FP16(arr[3]);
}
#define GGML_F32Cx4 __m128
#define GGML_F32Cx4_ZERO _mm_setzero_ps()
#define GGML_F32Cx4_SET1(x) _mm_set1_ps(x)
#define GGML_F32Cx4_LOAD(x) __sse_f16x4_load(x)
#define GGML_F32Cx4_STORE(x, y) __sse_f16x4_store(x, y)
#define GGML_F32Cx4_FMA GGML_F32x4_FMA
#define GGML_F32Cx4_ADD _mm_add_ps
#define GGML_F32Cx4_MUL _mm_mul_ps
#define GGML_F32Cx4_REDUCE GGML_F32x4_REDUCE
#define GGML_F16_VEC GGML_F32Cx4
#define GGML_F16_VEC_ZERO GGML_F32Cx4_ZERO
#define GGML_F16_VEC_SET1 GGML_F32Cx4_SET1
#define GGML_F16_VEC_LOAD(p, i) GGML_F32Cx4_LOAD(p)
#define GGML_F16_VEC_STORE(p, r, i) GGML_F32Cx4_STORE(p, r[i])
#define GGML_F16_VEC_FMA GGML_F32Cx4_FMA
#define GGML_F16_VEC_ADD GGML_F32Cx4_ADD
#define GGML_F16_VEC_MUL GGML_F32Cx4_MUL
#define GGML_F16_VEC_REDUCE GGML_F32Cx4_REDUCE
#endif
// GGML_F32_ARR / GGML_F16_ARR
// number of registers to use per step
#ifdef GGML_SIMD
#define GGML_F32_ARR (GGML_F32_STEP/GGML_F32_EPR)
#define GGML_F16_ARR (GGML_F16_STEP/GGML_F16_EPR)
#endif
//
// fundamental operations
//
inline static void ggml_vec_set_i8(const int n, int8_t * x, const int8_t v) { for (int i = 0; i < n; ++i) x[i] = v; }
inline static void ggml_vec_set_i16(const int n, int16_t * x, const int16_t v) { for (int i = 0; i < n; ++i) x[i] = v; }
inline static void ggml_vec_set_i32(const int n, int32_t * x, const int32_t v) { for (int i = 0; i < n; ++i) x[i] = v; }
inline static void ggml_vec_set_f16(const int n, ggml_fp16_t * x, const int32_t v) { for (int i = 0; i < n; ++i) x[i] = v; }
inline static void ggml_vec_add_f32 (const int n, float * z, const float * x, const float * y) { for (int i = 0; i < n; ++i) z[i] = x[i] + y[i]; }
inline static void ggml_vec_acc_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] += x[i]; }
inline static void ggml_vec_acc1_f32(const int n, float * y, const float v) { for (int i = 0; i < n; ++i) y[i] += v; }
inline static void ggml_vec_sub_f32 (const int n, float * z, const float * x, const float * y) { for (int i = 0; i < n; ++i) z[i] = x[i] - y[i]; }
inline static void ggml_vec_set_f32 (const int n, float * x, const float v) { for (int i = 0; i < n; ++i) x[i] = v; }
inline static void ggml_vec_cpy_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = x[i]; }
inline static void ggml_vec_neg_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = -x[i]; }
inline static void ggml_vec_mul_f32 (const int n, float * z, const float * x, const float * y) { for (int i = 0; i < n; ++i) z[i] = x[i]*y[i]; }
inline static void ggml_vec_div_f32 (const int n, float * z, const float * x, const float * y) { for (int i = 0; i < n; ++i) z[i] = x[i]/y[i]; }
inline static void ggml_vec_dot_f32(const int n, float * restrict s, const float * restrict x, const float * restrict y) {
#ifdef GGML_SIMD
float sumf = 0.0f;
const int np = (n & ~(GGML_F32_STEP - 1));
GGML_F32_VEC sum[GGML_F32_ARR] = { GGML_F32_VEC_ZERO };
GGML_F32_VEC ax[GGML_F32_ARR];
GGML_F32_VEC ay[GGML_F32_ARR];
for (int i = 0; i < np; i += GGML_F32_STEP) {
for (int j = 0; j < GGML_F32_ARR; j++) {
ax[j] = GGML_F32_VEC_LOAD(x + i + j*GGML_F32_EPR);
ay[j] = GGML_F32_VEC_LOAD(y + i + j*GGML_F32_EPR);
sum[j] = GGML_F32_VEC_FMA(sum[j], ax[j], ay[j]);
}
}
// reduce sum0..sum3 to sum0
GGML_F32_VEC_REDUCE(sumf, sum);
// leftovers
for (int i = np; i < n; ++i) {
sumf += x[i]*y[i];
}
#else
// scalar
ggml_float sumf = 0.0;
for (int i = 0; i < n; ++i) {
sumf += (ggml_float)(x[i]*y[i]);
}
#endif
*s = sumf;
}
#if __AVX512F__ && QK == 32
static inline __m512 dot_q4_0_oneblock_avx512(
__m512 acc,
const block_q4_0 * restrict x,
const block_q4_0 * restrict y,
int i
) {
// Compute combined scale for the block
__m512 d = _mm512_set1_ps( x[i].d * y[i].d );
__m256i bx = bytesFromNibbles( x[i].qs );
__m256i by = bytesFromNibbles( y[i].qs );
// Now we have a vector with bytes in [ 0 .. 15 ] interval. Offset them into [ -8 .. +7 ] interval.
const __m256i off = _mm256_set1_epi8( 8 );
bx = _mm256_sub_epi8( bx, off );
by = _mm256_sub_epi8( by, off );
// Sign-extend 16 signed bytes into int16_t
__m512i x32 = _mm512_cvtepi8_epi16( bx );
__m512i y32 = _mm512_cvtepi8_epi16( by );
// Compute products of int16_t integers, add pairwise
__m512i i64 = _mm512_madd_epi16( x32, y32 );
// Convert int32_t to float
__m512 p = _mm512_cvtepi32_ps( i64 );
// Apply the scale, and accumulate
return _mm512_fmadd_ps( d, p, acc );
}
#endif
inline static void ggml_vec_dot_f16(const int n, float * restrict s, ggml_fp16_t * restrict x, ggml_fp16_t * restrict y) {
ggml_float sumf = 0.0;
#if defined(GGML_SIMD)
const int np = (n & ~(GGML_F16_STEP - 1));
GGML_F16_VEC sum[GGML_F16_ARR] = { GGML_F16_VEC_ZERO };
GGML_F16_VEC ax[GGML_F16_ARR];
GGML_F16_VEC ay[GGML_F16_ARR];
for (int i = 0; i < np; i += GGML_F16_STEP) {
for (int j = 0; j < GGML_F16_ARR; j++) {
ax[j] = GGML_F16_VEC_LOAD(x + i + j*GGML_F16_EPR, j);
ay[j] = GGML_F16_VEC_LOAD(y + i + j*GGML_F16_EPR, j);
sum[j] = GGML_F16_VEC_FMA(sum[j], ax[j], ay[j]);
}
}
// reduce sum0..sum3 to sum0
GGML_F16_VEC_REDUCE(sumf, sum);
// leftovers
for (int i = np; i < n; ++i) {
sumf += (ggml_float)(GGML_FP16_TO_FP32(x[i])*GGML_FP16_TO_FP32(y[i]));
}
#else
for (int i = 0; i < n; ++i) {
sumf += (ggml_float)(GGML_FP16_TO_FP32(x[i])*GGML_FP16_TO_FP32(y[i]));
}
#endif
*s = sumf;
}
static void ggml_vec_dot_q4_0(const int n, float * restrict s, const void * restrict vx, const void * restrict vy) {
const int nb = n / QK;
assert(n % QK == 0);
assert(nb % 2 == 0);
const block_q4_0 * restrict x = vx;
const block_q4_0 * restrict y = vy;
ggml_float sumf = 0.0;
#if defined(__ARM_NEON)
float sum0 = 0.0f;
float sum1 = 0.0f;
for (int i = 0; i < nb; i += 2) {
const block_q4_0 * restrict x0 = &x[i + 0];
const block_q4_0 * restrict y0 = &y[i + 0];
const block_q4_0 * restrict x1 = &x[i + 1];
const block_q4_0 * restrict y1 = &y[i + 1];
const uint8x16_t m4b = vdupq_n_u8(0xf);
const int8x16_t s8b = vdupq_n_s8(0x8);
const uint8x16_t v0_0 = vld1q_u8(x0->qs);
const uint8x16_t v1_0 = vld1q_u8(y0->qs);
const uint8x16_t v0_1 = vld1q_u8(x1->qs);
const uint8x16_t v1_1 = vld1q_u8(y1->qs);
// 4-bit -> 8-bit
const int8x16_t v0_0l = vreinterpretq_s8_u8(vandq_u8(v0_0, m4b));
const int8x16_t v1_0l = vreinterpretq_s8_u8(vandq_u8(v1_0, m4b));
const int8x16_t v0_0h = vreinterpretq_s8_u8(vshrq_n_u8(v0_0, 4));
const int8x16_t v1_0h = vreinterpretq_s8_u8(vshrq_n_u8(v1_0, 4));
const int8x16_t v0_1l = vreinterpretq_s8_u8(vandq_u8(v0_1, m4b));
const int8x16_t v1_1l = vreinterpretq_s8_u8(vandq_u8(v1_1, m4b));
const int8x16_t v0_1h = vreinterpretq_s8_u8(vshrq_n_u8(v0_1, 4));
const int8x16_t v1_1h = vreinterpretq_s8_u8(vshrq_n_u8(v1_1, 4));
// sub 8
const int8x16_t v0_0ls = vsubq_s8(v0_0l, s8b);
const int8x16_t v1_0ls = vsubq_s8(v1_0l, s8b);
const int8x16_t v0_0hs = vsubq_s8(v0_0h, s8b);
const int8x16_t v1_0hs = vsubq_s8(v1_0h, s8b);
const int8x16_t v0_1ls = vsubq_s8(v0_1l, s8b);
const int8x16_t v1_1ls = vsubq_s8(v1_1l, s8b);
const int8x16_t v0_1hs = vsubq_s8(v0_1h, s8b);
const int8x16_t v1_1hs = vsubq_s8(v1_1h, s8b);
#if defined(__ARM_FEATURE_DOTPROD)
// dot product into int16x8_t
int32x4_t p_0 = vdotq_s32(vdupq_n_s32(0), v0_0ls, v1_0ls);
int32x4_t p_1 = vdotq_s32(vdupq_n_s32(0), v0_1ls, v1_1ls);
p_0 = vdotq_s32(p_0, v0_0hs, v1_0hs);
p_1 = vdotq_s32(p_1, v0_1hs, v1_1hs);
// scalar
#if defined(__ARM_FEATURE_QRDMX)
sum0 += x0->d * y0->d * vaddvq_s32(p_0);
sum1 += x1->d * y1->d * vaddvq_s32(p_1);
#else
sum0 += x0->d * y0->d * (vgetq_lane_s32(p_0, 0) + vgetq_lane_s32(p_0, 1) + vgetq_lane_s32(p_0, 2) + vgetq_lane_s32(p_0, 3));
sum1 += x1->d * y1->d * (vgetq_lane_s32(p_1, 0) + vgetq_lane_s32(p_1, 1) + vgetq_lane_s32(p_1, 2) + vgetq_lane_s32(p_1, 3));
#endif
#else
const int16x8_t pl0l = vmull_s8(vget_low_s8 (v0_0ls), vget_low_s8 (v1_0ls));
const int16x8_t pl0h = vmull_s8(vget_high_s8(v0_0ls), vget_high_s8(v1_0ls));
const int16x8_t ph0l = vmull_s8(vget_low_s8 (v0_0hs), vget_low_s8 (v1_0hs));
const int16x8_t ph0h = vmull_s8(vget_high_s8(v0_0hs), vget_high_s8(v1_0hs));
const int16x8_t pl1l = vmull_s8(vget_low_s8 (v0_1ls), vget_low_s8 (v1_1ls));
const int16x8_t pl1h = vmull_s8(vget_high_s8(v0_1ls), vget_high_s8(v1_1ls));
const int16x8_t ph1l = vmull_s8(vget_low_s8 (v0_1hs), vget_low_s8 (v1_1hs));
const int16x8_t ph1h = vmull_s8(vget_high_s8(v0_1hs), vget_high_s8(v1_1hs));
const int16x8_t pl_0 = vaddq_s16(pl0l, pl0h);
const int16x8_t ph_0 = vaddq_s16(ph0l, ph0h);
const int16x8_t pl_1 = vaddq_s16(pl1l, pl1h);
const int16x8_t ph_1 = vaddq_s16(ph1l, ph1h);
const int16x8_t p_0 = vaddq_s16(pl_0, ph_0);
const int16x8_t p_1 = vaddq_s16(pl_1, ph_1);
// scalar
#if defined(__ARM_FEATURE_QRDMX)
sum0 += x0->d * y0->d * vaddvq_s16(p_0);
sum1 += x1->d * y1->d * vaddvq_s16(p_1);
#else
sum0 += x0->d * y0->d * (vgetq_lane_s16(p_0, 0) + vgetq_lane_s16(p_0, 1) + vgetq_lane_s16(p_0, 2) + vgetq_lane_s16(p_0, 3) + vgetq_lane_s16(p_0, 4) + vgetq_lane_s16(p_0, 5) + vgetq_lane_s16(p_0, 6) + vgetq_lane_s16(p_0, 7));
sum1 += x1->d * y1->d * (vgetq_lane_s16(p_1, 0) + vgetq_lane_s16(p_1, 1) + vgetq_lane_s16(p_1, 2) + vgetq_lane_s16(p_1, 3) + vgetq_lane_s16(p_1, 4) + vgetq_lane_s16(p_1, 5) + vgetq_lane_s16(p_1, 6) + vgetq_lane_s16(p_1, 7));
#endif
#endif
}
sumf = (ggml_float)(sum0 + sum1);
#elif defined(__AVX512F__)
// Initialize accumulator with zeros
__m512 acc0 = _mm512_setzero_ps();
__m512 acc1 = _mm512_setzero_ps();
const int superblock_size = 8;
const int superblock_count = nb / superblock_size;
const int remainder = nb % superblock_size;
for (int superblock_ix = 0; superblock_ix < superblock_count; superblock_ix += 1) {
int i = superblock_ix * superblock_size;
acc0 = dot_q4_0_oneblock_avx512( acc0, x, y, i+0 );
acc1 = dot_q4_0_oneblock_avx512( acc1, x, y, i+1 );
acc0 = dot_q4_0_oneblock_avx512( acc0, x, y, i+2 );
acc1 = dot_q4_0_oneblock_avx512( acc1, x, y, i+3 );
acc0 = dot_q4_0_oneblock_avx512( acc0, x, y, i+4 );
acc1 = dot_q4_0_oneblock_avx512( acc1, x, y, i+5 );
acc0 = dot_q4_0_oneblock_avx512( acc0, x, y, i+6 );
acc1 = dot_q4_0_oneblock_avx512( acc1, x, y, i+7 );
}
// Remainders
for (int i = superblock_count * superblock_size; i < nb; ++i) {
acc0 = dot_q4_0_oneblock_avx512( acc0, x, y, i );
}
// Horizontal sum of all lanes of the accumulator
sumf = _mm512_reduce_add_ps( acc0 ) + _mm512_reduce_add_ps( acc1 );
#elif defined(__AVX2__)
// Initialize accumulator with zeros
__m256 acc = _mm256_setzero_ps();
// Main loop
for (int i = 0; i < nb; ++i) {
// Compute combined scale for the block
const __m256 d = _mm256_mul_ps( _mm256_broadcast_ss( &x[i].d ), _mm256_broadcast_ss( &y[i].d ) );
// Load 16 bytes, and unpack 4 bit fields into bytes, making 32 bytes
__m256i bx = bytesFromNibbles( x[i].qs );
__m256i by = bytesFromNibbles( y[i].qs );
// Now we have a vector with bytes in [ 0 .. 15 ] interval. Offset them into [ -8 .. +7 ] interval.
const __m256i off = _mm256_set1_epi8( 8 );
bx = _mm256_sub_epi8( bx, off );
by = _mm256_sub_epi8( by, off );
// Sign-extend first 16 signed bytes into int16_t
__m256i x16 = _mm256_cvtepi8_epi16( _mm256_castsi256_si128( bx ) );
__m256i y16 = _mm256_cvtepi8_epi16( _mm256_castsi256_si128( by ) );
// Compute products of int16_t integers, add pairwise
__m256i i32 = _mm256_madd_epi16( x16, y16 );
// Sign-extend last 16 signed bytes into int16_t vectors
x16 = _mm256_cvtepi8_epi16( _mm256_extracti128_si256( bx, 1 ) );
y16 = _mm256_cvtepi8_epi16( _mm256_extracti128_si256( by, 1 ) );
// Accumulate products of int16_t integers
i32 = _mm256_add_epi32( i32, _mm256_madd_epi16( x16, y16 ) );
// Convert int32_t to float
__m256 p = _mm256_cvtepi32_ps( i32 );
// Apply the scale, and accumulate
acc = _mm256_fmadd_ps( d, p, acc );
}
// Return horizontal sum of the acc vector
__m128 res = _mm256_extractf128_ps( acc, 1 );
res = _mm_add_ps( res, _mm256_castps256_ps128( acc ) );
res = _mm_add_ps( res, _mm_movehl_ps( res, res ) );
res = _mm_add_ss( res, _mm_movehdup_ps( res ) );
sumf = _mm_cvtss_f32( res );
#elif defined(__wasm_simd128__)
// wasm simd
float sum0 = 0.0f;
float sum1 = 0.0f;
for (int i = 0; i < nb; i += 2) {
const block_q4_0 * restrict x0 = &px[i + 0];
const block_q4_0 * restrict y0 = &py[i + 0];
const block_q4_0 * restrict x1 = &px[i + 1];
const block_q4_0 * restrict y1 = &py[i + 1];
const v128_t m4b = wasm_u8x16_splat(0xf);
const v128_t s8b = wasm_i8x16_splat(0x8);
const v128_t v0_0 = wasm_v128_load(x0.qs);
const v128_t v0_1 = wasm_v128_load(y0.qs);
const v128_t v1_0 = wasm_v128_load(x1.qs);
const v128_t v1_1 = wasm_v128_load(y1.qs);
// 4-bit -> 8-bit
const v128_t v0_0l = wasm_v128_and(v0_0, m4b);
const v128_t v1_0l = wasm_v128_and(v1_0, m4b);
const v128_t v0_0h = wasm_u8x16_shr(v0_0, 4);
const v128_t v1_0h = wasm_u8x16_shr(v1_0, 4);
const v128_t v0_1l = wasm_v128_and(v0_1, m4b);
const v128_t v1_1l = wasm_v128_and(v1_1, m4b);
const v128_t v0_1h = wasm_u8x16_shr(v0_1, 4);
const v128_t v1_1h = wasm_u8x16_shr(v1_1, 4);
// sub 8
const v128_t v0_0ls = wasm_i8x16_sub(v0_0l, s8b);
const v128_t v1_0ls = wasm_i8x16_sub(v1_0l, s8b);
const v128_t v0_0hs = wasm_i8x16_sub(v0_0h, s8b);
const v128_t v1_0hs = wasm_i8x16_sub(v1_0h, s8b);
const v128_t v0_1ls = wasm_i8x16_sub(v0_1l, s8b);
const v128_t v1_1ls = wasm_i8x16_sub(v1_1l, s8b);
const v128_t v0_1hs = wasm_i8x16_sub(v0_1h, s8b);
const v128_t v1_1hs = wasm_i8x16_sub(v1_1h, s8b);
// dot product into int16x8_t
const v128_t pl0l = wasm_i16x8_mul(wasm_i16x8_extend_low_i8x16(v0_0ls), wasm_i16x8_extend_low_i8x16(v1_0ls));
const v128_t pl0h = wasm_i16x8_mul(wasm_i16x8_extend_high_i8x16(v0_0ls), wasm_i16x8_extend_high_i8x16(v1_0ls));
const v128_t ph0l = wasm_i16x8_mul(wasm_i16x8_extend_low_i8x16(v0_0hs), wasm_i16x8_extend_low_i8x16(v1_0hs));
const v128_t ph0h = wasm_i16x8_mul(wasm_i16x8_extend_high_i8x16(v0_0hs), wasm_i16x8_extend_high_i8x16(v1_0hs));
const v128_t pl1l = wasm_i16x8_mul(wasm_i16x8_extend_low_i8x16(v0_1ls), wasm_i16x8_extend_low_i8x16(v1_1ls));
const v128_t pl1h = wasm_i16x8_mul(wasm_i16x8_extend_high_i8x16(v0_1ls), wasm_i16x8_extend_high_i8x16(v1_1ls));
const v128_t ph1l = wasm_i16x8_mul(wasm_i16x8_extend_low_i8x16(v0_1hs), wasm_i16x8_extend_low_i8x16(v1_1hs));
const v128_t ph1h = wasm_i16x8_mul(wasm_i16x8_extend_high_i8x16(v0_1hs), wasm_i16x8_extend_high_i8x16(v1_1hs));
const v128_t pl_0 = wasm_i16x8_add(pl0l, pl0h);
const v128_t ph_0 = wasm_i16x8_add(ph0l, ph0h);
const v128_t pl_1 = wasm_i16x8_add(pl1l, pl1h);
const v128_t ph_1 = wasm_i16x8_add(ph1l, ph1h);
const v128_t p_0 = wasm_i16x8_add(pl_0, ph_0);
const v128_t p_1 = wasm_i16x8_add(pl_1, ph_1);
sum0 += x0->d * y0->d * (
wasm_i16x8_extract_lane(p_0, 0) + wasm_i16x8_extract_lane(p_0, 1) +
wasm_i16x8_extract_lane(p_0, 2) + wasm_i16x8_extract_lane(p_0, 3) +
wasm_i16x8_extract_lane(p_0, 4) + wasm_i16x8_extract_lane(p_0, 5) +
wasm_i16x8_extract_lane(p_0, 6) + wasm_i16x8_extract_lane(p_0, 7));
sum1 += x1->d * y1->d * (
wasm_i16x8_extract_lane(p_1, 0) + wasm_i16x8_extract_lane(p_1, 1) +
wasm_i16x8_extract_lane(p_1, 2) + wasm_i16x8_extract_lane(p_1, 3) +
wasm_i16x8_extract_lane(p_1, 4) + wasm_i16x8_extract_lane(p_1, 5) +
wasm_i16x8_extract_lane(p_1, 6) + wasm_i16x8_extract_lane(p_1, 7));
}
sumf = sum0 + sum1;
#else
// scalar
for (int i = 0; i < nb; i++) {
const float d0 = x[i].d;
const float d1 = y[i].d;
const uint8_t * restrict p0 = x[i].qs;
const uint8_t * restrict p1 = y[i].qs;
for (int j = 0; j < QK/2; j++) {
const uint8_t v0 = p0[j];
const uint8_t v1 = p1[j];
const float f0 = d0*((int8_t) (v0 & 0xf) - 8);
const float f1 = d0*((int8_t) (v0 >> 4) - 8);
const float f2 = d1*((int8_t) (v1 & 0xf) - 8);
const float f3 = d1*((int8_t) (v1 >> 4) - 8);
sumf += f0*f2 + f1*f3;
}
}
#endif
*s = sumf;
}
static void ggml_vec_dot_q4_1(const int n, float * restrict s, const void * restrict vx, const void * restrict vy) {
const int nb = n / QK;
const block_q4_1 * restrict x = vx;
const block_q4_1 * restrict y = vy;
float sumf = 0.0;
#if defined(__AVX2__)
// Initialize accumulator with zeros
__m256 acc = _mm256_setzero_ps();
// Accumulator for constant offsets
float acc_offset = 0.0f;
// Main loop
for (int i = 0; i < nb; ++i) {
const float * d0 = &x[i].d;
const float * d1 = &y[i].d;
const float * m0 = &x[i].m;
const float * m1 = &y[i].m;
const __m256 d0v = _mm256_broadcast_ss( d0 );
const __m256 d1v = _mm256_broadcast_ss( d1 );
const __m256 m0v = _mm256_broadcast_ss( m0 );
const __m256 m1v = _mm256_broadcast_ss( m1 );
// Compute combined scale for the block
const __m256 scale_01 = _mm256_mul_ps( d0v, d1v );
// Compute cross scales for the block
const __m256 scale_0 = _mm256_mul_ps( d0v, m1v );
const __m256 scale_1 = _mm256_mul_ps( m0v, d1v );
const __m256 cross_scales = _mm256_blend_ps( scale_0, scale_1, 0xAA /* 0b10101010 */ );
// Load 16 bytes, and unpack 4 bit fields into bytes, making 32 bytes
__m256i bx = bytesFromNibbles( x[i].qs );
__m256i by = bytesFromNibbles( y[i].qs );
// Now we have a vector with bytes in [ 0 .. 15 ] interval.
// Sign-extend first 16 signed bytes into int16_t
__m256i x16 = _mm256_cvtepi8_epi16( _mm256_castsi256_si128( bx ) );
__m256i y16 = _mm256_cvtepi8_epi16( _mm256_castsi256_si128( by ) );
// Compute products of int16_t integers, add pairwise
__m256i i32 = _mm256_madd_epi16( x16, y16 );
// Sign-extend last 16 signed bytes into int16_t vectors
__m256i x16_h = _mm256_cvtepi8_epi16( _mm256_extracti128_si256( bx, 1 ) );
__m256i y16_h = _mm256_cvtepi8_epi16( _mm256_extracti128_si256( by, 1 ) );
// Accumulate products of int16_t integers
i32 = _mm256_add_epi32( i32, _mm256_madd_epi16( x16_h, y16_h ) );
// compute sums of unsigned bytes in bx, by in blocks of 8.
// This results in a layout like X100 0000 X200 0000 X300 0000 X400 0000,
// which we then interleave as X100 Y100 X200 Y200 X300 Y300 X400 Y400.
// so if we then cast to 8 singles, we get 8 floats like [ x0_7, y0_7, x8_15, y8_15, x16_23, y16_23, x24_31, y24_31 ]
__m256i xsumi = _mm256_sad_epu8( bx, _mm256_setzero_si256() );
__m256i ysumi = _mm256_sad_epu8( by, _mm256_setzero_si256() );
__m256i sumsi = _mm256_or_si256( xsumi, _mm256_slli_si256( ysumi, 4 ) );
__m256 sums = _mm256_cvtepi32_ps( sumsi );
// Convert int32_t to float
__m256 p = _mm256_cvtepi32_ps( i32 );
// Apply the scale, and accumulate
// acc += d0*d1*x*y + d0*m1*x + d1*m0*y
acc = _mm256_fmadd_ps( scale_01, p, acc );
acc = _mm256_fmadd_ps( cross_scales, sums, acc );
// acc_offset += m0*m1 (for each entry in the block)
acc_offset += (*m0)*(*m1);
}
// Return horizontal sum of the acc vector
__m128 res = _mm256_extractf128_ps( acc, 1 );
res = _mm_add_ps( res, _mm256_castps256_ps128( acc ) );
res = _mm_add_ps( res, _mm_movehl_ps( res, res ) );
res = _mm_add_ss( res, _mm_movehdup_ps( res ) );
sumf = _mm_cvtss_f32( res ) + acc_offset * QK;
#elif defined(__ARM_NEON)
float sum00 = 0.0f;
float sum01 = 0.0f;
float sum10 = 0.0f;
float sum11 = 0.0f;
for (int i = 0; i < nb; ++i) {
const block_q4_1 * restrict x0 = &x[i + 0];
const block_q4_1 * restrict y0 = &y[i + 0];
const uint8x16_t m4b = vdupq_n_u8(0xf);
const uint8x16_t v0_0 = vld1q_u8(x0->qs);
const uint8x16_t v1_0 = vld1q_u8(y0->qs);
// and with 0xf
const uint8x16_t v0_0l = vandq_u8(v0_0, m4b);
const uint8x16_t v1_0l = vandq_u8(v1_0, m4b);
const uint8x16_t v0_0h = vshrq_n_u8(v0_0, 4);
const uint8x16_t v1_0h = vshrq_n_u8(v1_0, 4);
// dot product into uint16x8_t
const uint16x8_t pl0l = vmull_u8(vget_low_u8 (v0_0l), vget_low_u8 (v1_0l));
const uint16x8_t pl0h = vmull_u8(vget_high_u8(v0_0l), vget_high_u8(v1_0l));
const uint16x8_t ph0l = vmull_u8(vget_low_u8 (v0_0h), vget_low_u8 (v1_0h));
const uint16x8_t ph0h = vmull_u8(vget_high_u8(v0_0h), vget_high_u8(v1_0h));
const uint16x8_t pl0 = vaddq_u16(pl0l, pl0h);
const uint16x8_t ph0 = vaddq_u16(ph0l, ph0h);
sum00 += x0->m*y0->m;
sum01 += y0->m*x0->d*(vaddvq_u8(v0_0l) + vaddvq_u8(v0_0h));
sum10 += x0->m*y0->d*(vaddvq_u8(v1_0l) + vaddvq_u8(v1_0h));
sum11 += x0->d*y0->d*vaddvq_u16(vaddq_u16(pl0, ph0));
}
sumf = QK*sum00 + sum01 + sum10 + sum11;
#else
// scalar
for (int i = 0; i < nb; i++) {
const float d0 = x[i].d;
const float d1 = y[i].d;
const float m0 = x[i].m;
const float m1 = y[i].m;
const uint8_t * restrict p0 = x[i].qs;
const uint8_t * restrict p1 = y[i].qs;
for (int j = 0; j < QK/2; j++) {
const uint8_t v0 = p0[j];
const uint8_t v1 = p1[j];
const float f0 = d0*(v0 & 0xf) + m0;
const float f1 = d0*(v0 >> 4) + m0;
const float f2 = d1*(v1 & 0xf) + m1;
const float f3 = d1*(v1 >> 4) + m1;
sumf += f0*f2 + f1*f3;
}
}
#endif
*s = sumf;
}
// compute GGML_VEC_DOT_UNROLL dot products at once
// xs - x row stride in bytes
inline static void ggml_vec_dot_f16_unroll(const int n, const int xs, float * restrict s, void * restrict xv, ggml_fp16_t * restrict y) {
ggml_float sumf[GGML_VEC_DOT_UNROLL] = { 0.0 };
ggml_fp16_t * restrict x[GGML_VEC_DOT_UNROLL];
for (int i = 0; i < GGML_VEC_DOT_UNROLL; ++i) {
x[i] = (ggml_fp16_t *) ((char *) xv + i*xs);
}
#if defined(GGML_SIMD)
const int np = (n & ~(GGML_F16_STEP - 1));
GGML_F16_VEC sum[GGML_VEC_DOT_UNROLL][GGML_F16_ARR] = { { GGML_F16_VEC_ZERO } };
GGML_F16_VEC ax[GGML_F16_ARR];
GGML_F16_VEC ay[GGML_F16_ARR];
for (int i = 0; i < np; i += GGML_F16_STEP) {
for (int j = 0; j < GGML_F16_ARR; j++) {
ay[j] = GGML_F16_VEC_LOAD(y + i + j*GGML_F16_EPR, j);
for (int k = 0; k < GGML_VEC_DOT_UNROLL; ++k) {
ax[j] = GGML_F16_VEC_LOAD(x[k] + i + j*GGML_F16_EPR, j);
sum[k][j] = GGML_F16_VEC_FMA(sum[k][j], ax[j], ay[j]);
}
}
}
// reduce sum0..sum3 to sum0
for (int k = 0; k < GGML_VEC_DOT_UNROLL; ++k) {
GGML_F16_VEC_REDUCE(sumf[k], sum[k]);
}
// leftovers
for (int i = np; i < n; ++i) {
for (int j = 0; j < GGML_VEC_DOT_UNROLL; ++j) {
sumf[j] += (ggml_float)(GGML_FP16_TO_FP32(x[j][i])*GGML_FP16_TO_FP32(y[i]));
}
}
#else
for (int i = 0; i < n; ++i) {
for (int j = 0; j < GGML_VEC_DOT_UNROLL; ++j) {
sumf[j] += (ggml_float)(GGML_FP16_TO_FP32(x[j][i])*GGML_FP16_TO_FP32(y[i]));
}
}
#endif
for (int i = 0; i < GGML_VEC_DOT_UNROLL; ++i) {
s[i] = sumf[i];
}
}
inline static void ggml_vec_mad_f32(const int n, float * restrict y, const float * restrict x, const float v) {
#if defined(GGML_SIMD)
const int np = (n & ~(GGML_F32_STEP - 1));
GGML_F32_VEC vx = GGML_F32_VEC_SET1(v);
GGML_F32_VEC ax[GGML_F32_ARR];
GGML_F32_VEC ay[GGML_F32_ARR];
for (int i = 0; i < np; i += GGML_F32_STEP) {
for (int j = 0; j < GGML_F32_ARR; j++) {
ax[j] = GGML_F32_VEC_LOAD(x + i + j*GGML_F32_EPR);
ay[j] = GGML_F32_VEC_LOAD(y + i + j*GGML_F32_EPR);
ay[j] = GGML_F32_VEC_FMA(ay[j], ax[j], vx);
GGML_F32_VEC_STORE(y + i + j*GGML_F32_EPR, ay[j]);
}
}
// leftovers
for (int i = np; i < n; ++i) {
y[i] += x[i]*v;
}
#else
// scalar
for (int i = 0; i < n; ++i) {
y[i] += x[i]*v;
}
#endif
}
//inline static void ggml_vec_scale_f32(const int n, float * y, const float v) { for (int i = 0; i < n; ++i) y[i] *= v; }
inline static void ggml_vec_scale_f32(const int n, float * y, const float v) {
#if defined(GGML_SIMD)
const int np = (n & ~(GGML_F32_STEP - 1));
GGML_F32_VEC vx = GGML_F32_VEC_SET1(v);
GGML_F32_VEC ay[GGML_F32_ARR];
for (int i = 0; i < np; i += GGML_F32_STEP) {
for (int j = 0; j < GGML_F32_ARR; j++) {
ay[j] = GGML_F32_VEC_LOAD(y + i + j*GGML_F32_EPR);
ay[j] = GGML_F32_VEC_MUL(ay[j], vx);
GGML_F32_VEC_STORE(y + i + j*GGML_F32_EPR, ay[j]);
}
}
// leftovers
for (int i = np; i < n; ++i) {
y[i] *= v;
}
#else
// scalar
for (int i = 0; i < n; ++i) {
y[i] *= v;
}
#endif
}
inline static void ggml_vec_norm_f32 (const int n, float * s, const float * x) { ggml_vec_dot_f32(n, s, x, x); *s = sqrtf(*s); }
inline static void ggml_vec_sqr_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = x[i]*x[i]; }
inline static void ggml_vec_sqrt_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = sqrtf(x[i]); }
inline static void ggml_vec_abs_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = fabsf(x[i]); }
inline static void ggml_vec_sgn_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = (x[i] > 0.f) ? 1.f : ((x[i] < 0.f) ? -1.f : 0.f); }
inline static void ggml_vec_step_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = (x[i] > 0.f) ? 1.f : 0.f; }
inline static void ggml_vec_relu_f32 (const int n, float * y, const float * x) { for (int i = 0; i < n; ++i) y[i] = (x[i] > 0.f) ? x[i] : 0.f; }
static const float GELU_COEF_A = 0.044715f;
static const float SQRT_2_OVER_PI = 0.79788456080286535587989211986876f;
inline static float ggml_gelu_f32(float x) {
return 0.5f*x*(1.0f + tanhf(SQRT_2_OVER_PI*x*(1.0f + GELU_COEF_A*x*x)));
}
inline static void ggml_vec_gelu_f16(const int n, ggml_fp16_t * y, const ggml_fp16_t * x) {
const uint16_t * i16 = (const uint16_t *) x;
for (int i = 0; i < n; ++i) {
y[i] = table_gelu_f16[i16[i]];
}
}
#ifdef GGML_GELU_FP16
inline static void ggml_vec_gelu_f32(const int n, float * y, const float * x) {
uint16_t t;
for (int i = 0; i < n; ++i) {
ggml_fp16_t fp16 = GGML_FP32_TO_FP16(x[i]);
memcpy(&t, &fp16, sizeof(uint16_t));
y[i] = GGML_FP16_TO_FP32(table_gelu_f16[t]);
}
}
#else
inline static void ggml_vec_gelu_f32(const int n, float * y, const float * x) {
for (int i = 0; i < n; ++i) {
y[i] = ggml_gelu_f32(x[i]);
}
}
#endif
// Sigmoid Linear Unit (SiLU) function
inline static float ggml_silu_f32(float x) {
return x/(1.0f + expf(-x));
}
inline static void ggml_vec_silu_f16(const int n, ggml_fp16_t * y, const ggml_fp16_t * x) {
const uint16_t * i16 = (const uint16_t *) x;
for (int i = 0; i < n; ++i) {
y[i] = table_silu_f16[i16[i]];
}
}
#ifdef GGML_SILU_FP16
inline static void ggml_vec_silu_f32(const int n, float * y, const float * x) {
uint16_t t;
for (int i = 0; i < n; ++i) {
ggml_fp16_t fp16 = GGML_FP32_TO_FP16(x[i]);
memcpy(&t, &fp16, sizeof(uint16_t));
y[i] = GGML_FP16_TO_FP32(table_silu_f16[t]);
}
}
#else
inline static void ggml_vec_silu_f32(const int n, float * y, const float * x) {
for (int i = 0; i < n; ++i) {
y[i] = ggml_silu_f32(x[i]);
}
}
#endif
inline static void ggml_vec_sum_f32(const int n, float * s, const float * x) {
#ifndef GGML_USE_ACCELERATE
ggml_float sum = 0.0;
for (int i = 0; i < n; ++i) {
sum += (ggml_float)x[i];
}
*s = sum;
#else
vDSP_sve(x, 1, s, n);
#endif
}
inline static void ggml_vec_max_f32(const int n, float * s, const float * x) {
#ifndef GGML_USE_ACCELERATE
float max = -INFINITY;
for (int i = 0; i < n; ++i) {
max = MAX(max, x[i]);
}
*s = max;
#else
vDSP_maxv(x, 1, s, n);
#endif
}
inline static void ggml_vec_norm_inv_f32(const int n, float * s, const float * x) {
ggml_vec_norm_f32(n, s, x);
*s = 1.f/(*s);
}
//
// logging
//
#if (GGML_DEBUG >= 1)
#define GGML_PRINT_DEBUG(...) printf(__VA_ARGS__)
#else
#define GGML_PRINT_DEBUG(...)
#endif
#if (GGML_DEBUG >= 5)
#define GGML_PRINT_DEBUG_5(...) printf(__VA_ARGS__)
#else
#define GGML_PRINT_DEBUG_5(...)
#endif
#if (GGML_DEBUG >= 10)
#define GGML_PRINT_DEBUG_10(...) printf(__VA_ARGS__)
#else
#define GGML_PRINT_DEBUG_10(...)
#endif
#define GGML_PRINT(...) printf(__VA_ARGS__)
//
// data types
//
static const int GGML_BLCK_SIZE[GGML_TYPE_COUNT] = {
QK,
QK,
1,
1,
1,
1,
1,
};
static_assert(GGML_TYPE_COUNT == 7, "GGML_TYPE_COUNT != 5");
static const size_t GGML_TYPE_SIZE[GGML_TYPE_COUNT] = {
sizeof(block_q4_0),
sizeof(block_q4_1),
sizeof(int8_t ),
sizeof(int16_t),
sizeof(int32_t),
sizeof(ggml_fp16_t),
sizeof(float ),
};
// don't forget to update the array above when adding new types
static_assert(GGML_TYPE_COUNT == 7, "GGML_TYPE_COUNT != 5");
static const char * GGML_OP_LABEL[GGML_OP_COUNT] = {
"NONE",
"DUP",
"ADD",
"SUB",
"MUL",
"DIV",
"SQR",
"SQRT",
"SUM",
"MEAN",
"REPEAT",
"ABS",
"SGN",
"NEG",
"STEP",
"RELU",
"GELU",
"SILU",
"NORM",
"RMS_NORM",
"MUL_MAT",
"SCALE",
"CPY",
"RESHAPE",
"VIEW",
"PERMUTE",
"TRANSPOSE",
"GET_ROWS",
"DIAG_MASK_INF",
"SOFT_MAX",
"ROPE",
"CONV_1D_1S",
"CONV_1D_2S",
"FLASH_ATTN",
"FLASH_FF",
};
static_assert(GGML_OP_COUNT == 35, "GGML_OP_COUNT != 35");
static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = {
"none",
"x",
"x+y",
"x-y",
"x*y",
"x/y",
"x^2",
"√x",
"Σx",
"Σx/n",
"repeat(x)",
"abs(x)",
"sgn(x)",
"-x",
"step(x)",
"relu(x)",
"gelu(x)",
"silu(x)",
"norm(x)",
"rms_norm(x)",
"X*Y",
"x*v",
"x-\\>y",
"reshape(x)",
"view(x)",
"permute(x)",
"transpose(x)",
"get_rows(x)",
"diag_mask_inf(x)",
"soft_max(x)",
"rope(x)",
"conv_1d_1s(x)",
"conv_1d_2s(x)",
"flash_attn(x)",
"flash_ff(x)",
};
static_assert(GGML_OP_COUNT == 35, "GGML_OP_COUNT != 35");
//
// ggml object
//
struct ggml_object {
size_t offs;
size_t size;
struct ggml_object * next;
char padding[8];
};
static const size_t GGML_OBJECT_SIZE = sizeof(struct ggml_object);
static_assert(sizeof(struct ggml_object)%GGML_MEM_ALIGN == 0, "ggml_object size must be a multiple of GGML_MEM_ALIGN");
static_assert(sizeof(struct ggml_tensor)%GGML_MEM_ALIGN == 0, "ggml_tensor size must be a multiple of GGML_MEM_ALIGN");
//
// ggml context
//
struct ggml_context {
size_t mem_size;
void * mem_buffer;
bool mem_buffer_owned;
bool mem_buffer_mlocked;
int n_objects;
struct ggml_object * objects_begin;
struct ggml_object * objects_end;
struct ggml_scratch scratch;
struct ggml_scratch scratch_save;
};
struct ggml_context_container {
bool used;
struct ggml_context context;
};
//
// compute types
//
enum ggml_task_type {
GGML_TASK_INIT = 0,
GGML_TASK_COMPUTE,
GGML_TASK_FINALIZE,
};
struct ggml_compute_params {
enum ggml_task_type type;
int ith, nth;
// work buffer for all threads
size_t wsize;
void * wdata;
};
//
// ggml state
//
struct ggml_state {
struct ggml_context_container contexts[GGML_MAX_CONTEXTS];
};
// global state
static struct ggml_state g_state;
static atomic_int g_state_barrier = 0;
// barrier via spin lock
inline static void ggml_critical_section_start(void) {
int processing = atomic_fetch_add(&g_state_barrier, 1);
while (processing > 0) {
// wait for other threads to finish
atomic_fetch_sub(&g_state_barrier, 1);
sched_yield(); // TODO: reconsider this
processing = atomic_fetch_add(&g_state_barrier, 1);
}
}
// TODO: make this somehow automatically executed
// some sort of "sentry" mechanism
inline static void ggml_critical_section_end(void) {
atomic_fetch_sub(&g_state_barrier, 1);
}
////////////////////////////////////////////////////////////////////////////////
void ggml_print_object(const struct ggml_object * obj) {
GGML_PRINT(" - ggml_object: offset = %zu, size = %zu, next = %p\n",
obj->offs, obj->size, (const void *) obj->next);
}
void ggml_print_objects(const struct ggml_context * ctx) {
struct ggml_object * obj = ctx->objects_begin;
GGML_PRINT("%s: objects in context %p:\n", __func__, (const void *) ctx);
while (obj != NULL) {
ggml_print_object(obj);
obj = obj->next;
}
GGML_PRINT("%s: --- end ---\n", __func__);
}
int ggml_nelements(const struct ggml_tensor * tensor) {
static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
return tensor->ne[0]*tensor->ne[1]*tensor->ne[2]*tensor->ne[3];
}
int ggml_nrows(const struct ggml_tensor * tensor) {
static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
return tensor->ne[1]*tensor->ne[2]*tensor->ne[3];
}
size_t ggml_nbytes(const struct ggml_tensor * tensor) {
static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
return (ggml_nelements(tensor)*GGML_TYPE_SIZE[tensor->type])/GGML_BLCK_SIZE[tensor->type];
}
int ggml_blck_size(enum ggml_type type) {
return GGML_BLCK_SIZE[type];
}
size_t ggml_type_size(enum ggml_type type) {
return GGML_TYPE_SIZE[type];
}
float ggml_type_sizef(enum ggml_type type) {
return ((float)(GGML_TYPE_SIZE[type]))/GGML_BLCK_SIZE[type];
}
size_t ggml_element_size(const struct ggml_tensor * tensor) {
return GGML_TYPE_SIZE[tensor->type];
}
static inline bool ggml_is_scalar(const struct ggml_tensor * tensor) {
static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
return tensor->ne[0] == 1 && tensor->ne[1] == 1 && tensor->ne[2] == 1 && tensor->ne[3] == 1;
}
static inline bool ggml_is_vector(const struct ggml_tensor * tensor) {
static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
return tensor->ne[1] == 1 && tensor->ne[2] == 1 && tensor->ne[3] == 1;
}
static inline bool ggml_is_matrix(const struct ggml_tensor * tensor) {
static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
return tensor->ne[2] == 1 && tensor->ne[3] == 1;
}
static inline bool ggml_can_mul_mat(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
return
(t0->ne[0] == t1->ne[0]) &&
(t0->ne[2] == t1->ne[2]) &&
(t0->ne[3] == t1->ne[3]);
}
static inline bool ggml_is_transposed(const struct ggml_tensor * tensor) {
return tensor->nb[0] > tensor->nb[1];
}
static inline bool ggml_is_contiguous(const struct ggml_tensor * tensor) {
static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
return
tensor->nb[0] == GGML_TYPE_SIZE[tensor->type] &&
tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/GGML_BLCK_SIZE[tensor->type] &&
tensor->nb[2] == tensor->nb[1]*tensor->ne[1] &&
tensor->nb[3] == tensor->nb[2]*tensor->ne[2];
}
static inline bool ggml_is_padded_1d(const struct ggml_tensor * tensor) {
static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
return
tensor->nb[0] == GGML_TYPE_SIZE[tensor->type] &&
tensor->nb[2] == tensor->nb[1]*tensor->ne[1] &&
tensor->nb[3] == tensor->nb[2]*tensor->ne[2];
}
static inline bool ggml_are_same_shape(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
return
(t0->ne[0] == t1->ne[0] ) &&
(t0->ne[1] == t1->ne[1] ) &&
(t0->ne[2] == t1->ne[2] ) &&
(t0->ne[3] == t1->ne[3] );
}
// check if t1 can be represented as a repeatition of t0
static inline bool ggml_can_repeat(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
return
(t1->ne[0]%t0->ne[0] == 0) &&
(t1->ne[1]%t0->ne[1] == 0) &&
(t1->ne[2]%t0->ne[2] == 0) &&
(t1->ne[3]%t0->ne[3] == 0);
}
static inline int ggml_up32(int n) {
return (n + 31) & ~31;
}
static inline int ggml_up64(int n) {
return (n + 63) & ~63;
}
static inline int ggml_up(int n, int m) {
// assert m is a power of 2
GGML_ASSERT((m & (m - 1)) == 0);
return (n + m - 1) & ~(m - 1);
}
// assert that pointer is aligned to GGML_MEM_ALIGN
#define ggml_assert_aligned(ptr) \
GGML_ASSERT(((uintptr_t) (ptr))%GGML_MEM_ALIGN == 0)
////////////////////////////////////////////////////////////////////////////////
struct ggml_context * ggml_init(struct ggml_init_params params) {
// make this function thread safe
ggml_critical_section_start();
static bool is_first_call = true;
if (is_first_call) {
// initialize time system (required on Windows)
ggml_time_init();
// initialize GELU, SILU and EXP F32 tables
{
const uint64_t t_start = ggml_time_us(); UNUSED(t_start);
ggml_fp16_t ii;
for (int i = 0; i < (1 << 16); ++i) {
uint16_t ui = i;
memcpy(&ii, &ui, sizeof(ii));
const float f = table_f32_f16[i] = GGML_COMPUTE_FP16_TO_FP32(ii);
table_gelu_f16[i] = GGML_FP32_TO_FP16(ggml_gelu_f32(f));
table_silu_f16[i] = GGML_FP32_TO_FP16(ggml_silu_f32(f));
table_exp_f16[i] = GGML_FP32_TO_FP16(expf(f));
}
const uint64_t t_end = ggml_time_us(); UNUSED(t_end);
GGML_PRINT_DEBUG("%s: GELU, SILU and EXP tables initialized in %f ms\n", __func__, (t_end - t_start)/1000.0f);
}
// initialize g_state
{
const uint64_t t_start = ggml_time_us(); UNUSED(t_start);
g_state = (struct ggml_state) {
/*.contexts =*/ { { 0 } },
};
for (int i = 0; i < GGML_MAX_CONTEXTS; ++i) {
g_state.contexts[i].used = false;
}
const uint64_t t_end = ggml_time_us(); UNUSED(t_end);
GGML_PRINT_DEBUG("%s: g_state initialized in %f ms\n", __func__, (t_end - t_start)/1000.0f);
}
is_first_call = false;
}
// find non-used context in g_state
struct ggml_context * ctx = NULL;
for (int i = 0; i < GGML_MAX_CONTEXTS; i++) {
if (!g_state.contexts[i].used) {
g_state.contexts[i].used = true;
ctx = &g_state.contexts[i].context;
GGML_PRINT_DEBUG("%s: found unused context %d\n", __func__, i);
break;
}
}
if (ctx == NULL) {
GGML_PRINT_DEBUG("%s: no unused context found\n", __func__);
ggml_critical_section_end();
return NULL;
}
*ctx = (struct ggml_context) {
/*.mem_size =*/ params.mem_size,
/*.mem_buffer =*/ params.mem_buffer ? params.mem_buffer : malloc(params.mem_size),
/*.mem_buffer_owned =*/ params.mem_buffer ? false : true,
/*.mem_buffer_mlocked =*/ false,
/*.n_objects =*/ 0,
/*.objects_begin =*/ NULL,
/*.objects_end =*/ NULL,
/*.scratch =*/ { 0, 0, NULL, },
/*.scratch_save =*/ { 0, 0, NULL, },
};
GGML_ASSERT(ctx->mem_buffer != NULL); // check for allocation failure
ggml_assert_aligned(ctx->mem_buffer);
GGML_PRINT_DEBUG("%s: context initialized\n", __func__);
ggml_critical_section_end();
return ctx;
}
void ggml_free(struct ggml_context * ctx) {
// make this function thread safe
ggml_critical_section_start();
bool found = false;
for (int i = 0; i < GGML_MAX_CONTEXTS; i++) {
if (&g_state.contexts[i].context == ctx) {
g_state.contexts[i].used = false;
GGML_PRINT_DEBUG("%s: context %d with %d objects has been freed. memory used = %zu\n",
__func__, i, ctx->n_objects, ctx->objects_end->offs + ctx->objects_end->size);
#if GGML_MLOCK_SUPPORT
if (ctx->mem_buffer_mlocked) {
if (munlock(ctx->mem_buffer, ctx->mem_size)) {
fprintf(stderr, "%s: failed to munlock buffer: %s\n", __func__, strerror(errno));
}
}
#endif
if (ctx->mem_buffer_owned) {
free(ctx->mem_buffer);
}
found = true;
break;
}
}
if (!found) {
GGML_PRINT_DEBUG("%s: context not found\n", __func__);
}
ggml_critical_section_end();
}
size_t ggml_used_mem(const struct ggml_context * ctx) {
return ctx->objects_end->offs + ctx->objects_end->size;
}
size_t ggml_set_scratch(struct ggml_context * ctx, struct ggml_scratch scratch) {
const size_t result = ctx->scratch.data ? ctx->scratch.offs : 0;
ctx->scratch = scratch;
return result;
}
bool ggml_mlock_supported(void) {
return GGML_MLOCK_SUPPORT;
}
#if GGML_MLOCK_SUPPORT
#ifdef __APPLE__
#define MLOCK_SUGGESTION "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or\n" \
"decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MLOCK (ulimit -l)."
#else
#define MLOCK_SUGGESTION "Try increasing RLIMIT_MLOCK (ulimit -l)."
#endif
bool ggml_mlock(struct ggml_context * ctx, char ** err_p) {
if (ctx->mem_buffer_mlocked) {
return true;
}
if (mlock(ctx->mem_buffer, ctx->mem_size)) {
#ifndef __APPLE__
int ret = asprintf(err_p, "failed to mlock %zu-byte buffer: %s\n" MLOCK_SUGGESTION,
ctx->mem_size, strerror(errno));
GGML_ASSERT(ret >= 0);
#endif
return false;
}
ctx->mem_buffer_mlocked = true;
return true;
}
#else // GGML_MLOCK_SUPPORT
bool ggml_mlock(struct ggml_context * ctx, char ** err_p) {
*err_p = strdup("can't mlock because it's not supported on this system");
return false;
}
#endif // GGML_MLOCK_SUPPORT
////////////////////////////////////////////////////////////////////////////////
struct ggml_tensor * ggml_new_tensor_impl(
struct ggml_context * ctx,
enum ggml_type type,
int n_dims,
const int* ne,
void* data) {
// always insert objects at the end of the context's memory pool
struct ggml_object * obj_cur = ctx->objects_end;
const size_t cur_offs = obj_cur == NULL ? 0 : obj_cur->offs;
const size_t cur_size = obj_cur == NULL ? 0 : obj_cur->size;
const size_t cur_end = cur_offs + cur_size;
size_t size_needed = 0;
if (data == NULL) {
size_needed += GGML_TYPE_SIZE[type]*(ne[0]/GGML_BLCK_SIZE[type]);
for (int i = 1; i < n_dims; i++) {
size_needed *= ne[i];
}
// align to GGML_MEM_ALIGN
size_needed = ((size_needed + GGML_MEM_ALIGN - 1)/GGML_MEM_ALIGN)*GGML_MEM_ALIGN;
}
char * const mem_buffer = ctx->mem_buffer;
struct ggml_object * const obj_new = (struct ggml_object *)(mem_buffer + cur_end);
if (ctx->scratch.data == NULL || data != NULL) {
size_needed += sizeof(struct ggml_tensor);
if (cur_end + size_needed + GGML_OBJECT_SIZE > ctx->mem_size) {
GGML_PRINT("%s: not enough space in the context's memory pool (needed %zu, available %zu)\n",
__func__, cur_end + size_needed + GGML_OBJECT_SIZE, ctx->mem_size);
assert(false);
return NULL;
}
*obj_new = (struct ggml_object) {
.offs = cur_end + GGML_OBJECT_SIZE,
.size = size_needed,
.next = NULL,
};
} else {
if (ctx->scratch.offs + size_needed > ctx->scratch.size) {
GGML_PRINT("%s: not enough space in the scratch memory\n", __func__);
assert(false);
return NULL;
}
if (cur_end + sizeof(struct ggml_tensor) + GGML_OBJECT_SIZE > ctx->mem_size) {
GGML_PRINT("%s: not enough space in the context's memory pool (needed %zu, available %zu)\n",
__func__, cur_end + sizeof(struct ggml_tensor) + GGML_OBJECT_SIZE, ctx->mem_size);
assert(false);
return NULL;
}
data = (char * const) ctx->scratch.data + ctx->scratch.offs;
*obj_new = (struct ggml_object) {
.offs = cur_end + GGML_OBJECT_SIZE,
.size = sizeof(struct ggml_tensor),
.next = NULL,
};
//printf("scratch offs = %zu, size_needed = %zu\n", ctx->scratch.offs, size_needed);
ctx->scratch.offs += size_needed;
}
if (obj_cur != NULL) {
obj_cur->next = obj_new;
} else {
// this is the first object in this context
ctx->objects_begin = obj_new;
}
ctx->objects_end = obj_new;
//printf("%s: inserted new object at %zu, size = %zu\n", __func__, cur_end, obj_new->size);
struct ggml_tensor * const result = (struct ggml_tensor *)(mem_buffer + obj_new->offs);
ggml_assert_aligned(result);
*result = (struct ggml_tensor) {
/*.type =*/ type,
/*.n_dims =*/ n_dims,
/*.ne =*/ { 1, 1, 1, 1 },
/*.nb =*/ { 0, 0, 0, 0 },
/*.op =*/ GGML_OP_NONE,
/*.is_param =*/ false,
/*.grad =*/ NULL,
/*.src0 =*/ NULL,
/*.src1 =*/ NULL,
/*.opt =*/ { NULL },
/*.n_tasks =*/ 0,
/*.perf_runs =*/ 0,
/*.perf_cycles =*/ 0,
/*.perf_time_us =*/ 0,
/*.data =*/ data == NULL ? (void *)(result + 1) : data,
/*.pad =*/ { 0 },
};
ggml_assert_aligned(result->data);
for (int i = 0; i < n_dims; i++) {
result->ne[i] = ne[i];
}
result->nb[0] = GGML_TYPE_SIZE[type];
result->nb[1] = result->nb[0]*(result->ne[0]/GGML_BLCK_SIZE[type]);
for (int i = 2; i < GGML_MAX_DIMS; i++) {
result->nb[i] = result->nb[i - 1]*result->ne[i - 1];
}
ctx->n_objects++;
return result;
}
struct ggml_tensor * ggml_new_tensor(
struct ggml_context * ctx,
enum ggml_type type,
int n_dims,
const int * ne) {
return ggml_new_tensor_impl(ctx, type, n_dims, ne, NULL);
}
struct ggml_tensor * ggml_new_tensor_1d(
struct ggml_context * ctx,
enum ggml_type type,
int ne0) {
return ggml_new_tensor(ctx, type, 1, &ne0);
}
struct ggml_tensor * ggml_new_tensor_2d(
struct ggml_context * ctx,
enum ggml_type type,
int ne0,
int ne1) {
const int ne[2] = { ne0, ne1 };
return ggml_new_tensor(ctx, type, 2, ne);
}
struct ggml_tensor * ggml_new_tensor_3d(
struct ggml_context * ctx,
enum ggml_type type,
int ne0,
int ne1,
int ne2) {
const int ne[3] = { ne0, ne1, ne2 };
return ggml_new_tensor(ctx, type, 3, ne);
}
struct ggml_tensor * ggml_new_tensor_4d(
struct ggml_context * ctx,
enum ggml_type type,
int ne0,
int ne1,
int ne2,
int ne3) {
const int ne[4] = { ne0, ne1, ne2, ne3 };
return ggml_new_tensor(ctx, type, 4, ne);
}
struct ggml_tensor * ggml_new_i32(struct ggml_context * ctx, int32_t value) {
ctx->scratch_save = ctx->scratch;
ctx->scratch.data = NULL;
struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 1);
ctx->scratch = ctx->scratch_save;
ggml_set_i32(result, value);
return result;
}
struct ggml_tensor * ggml_new_f32(struct ggml_context * ctx, float value) {
ctx->scratch_save = ctx->scratch;
ctx->scratch.data = NULL;
struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 1);
ctx->scratch = ctx->scratch_save;
ggml_set_f32(result, value);
return result;
}
struct ggml_tensor * ggml_dup_tensor(struct ggml_context * ctx, const struct ggml_tensor * src) {
return ggml_new_tensor_impl(ctx, src->type, src->n_dims, src->ne, NULL);
}
struct ggml_tensor * ggml_set_zero(struct ggml_tensor * tensor) {
memset(tensor->data, 0, ggml_nbytes(tensor));
return tensor;
}
struct ggml_tensor * ggml_set_i32 (struct ggml_tensor * tensor, int32_t value) {
const int n = ggml_nrows(tensor);
const int nc = tensor->ne[0];
const size_t n1 = tensor->nb[1];
char * const data = tensor->data;
switch (tensor->type) {
case GGML_TYPE_Q4_0:
{
GGML_ASSERT(false);
} break;
case GGML_TYPE_Q4_1:
{
GGML_ASSERT(false);
} break;
case GGML_TYPE_I8:
{
assert(tensor->nb[0] == sizeof(int8_t));
for (int i = 0; i < n; i++) {
ggml_vec_set_i8(nc, (int8_t *)(data + i*n1), value);
}
} break;
case GGML_TYPE_I16:
{
assert(tensor->nb[0] == sizeof(int16_t));
for (int i = 0; i < n; i++) {
ggml_vec_set_i16(nc, (int16_t *)(data + i*n1), value);
}
} break;
case GGML_TYPE_I32:
{
assert(tensor->nb[0] == sizeof(int32_t));
for (int i = 0; i < n; i++) {
ggml_vec_set_i32(nc, (int32_t *)(data + i*n1), value);
}
} break;
case GGML_TYPE_F16:
{
assert(tensor->nb[0] == sizeof(ggml_fp16_t));
for (int i = 0; i < n; i++) {
ggml_vec_set_f16(nc, (ggml_fp16_t *)(data + i*n1), value);
}
} break;
case GGML_TYPE_F32:
{
assert(tensor->nb[0] == sizeof(float));
for (int i = 0; i < n; i++) {
ggml_vec_set_f32(nc, (float *)(data + i*n1), value);
}
} break;
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
return tensor;
}
struct ggml_tensor * ggml_set_f32(struct ggml_tensor * tensor, float value) {
const int n = ggml_nrows(tensor);
const int nc = tensor->ne[0];
const size_t n1 = tensor->nb[1];
char * const data = tensor->data;
switch (tensor->type) {
case GGML_TYPE_Q4_0:
{
GGML_ASSERT(false);
} break;
case GGML_TYPE_Q4_1:
{
GGML_ASSERT(false);
} break;
case GGML_TYPE_I8:
{
assert(tensor->nb[0] == sizeof(int8_t));
for (int i = 0; i < n; i++) {
ggml_vec_set_i8(nc, (int8_t *)(data + i*n1), value);
}
} break;
case GGML_TYPE_I16:
{
assert(tensor->nb[0] == sizeof(int16_t));
for (int i = 0; i < n; i++) {
ggml_vec_set_i16(nc, (int16_t *)(data + i*n1), value);
}
} break;
case GGML_TYPE_I32:
{
assert(tensor->nb[0] == sizeof(int32_t));
for (int i = 0; i < n; i++) {
ggml_vec_set_i32(nc, (int32_t *)(data + i*n1), value);
}
} break;
case GGML_TYPE_F16:
{
assert(tensor->nb[0] == sizeof(ggml_fp16_t));
for (int i = 0; i < n; i++) {
ggml_vec_set_f16(nc, (ggml_fp16_t *)(data + i*n1), value);
}
} break;
case GGML_TYPE_F32:
{
assert(tensor->nb[0] == sizeof(float));
for (int i = 0; i < n; i++) {
ggml_vec_set_f32(nc, (float *)(data + i*n1), value);
}
} break;
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
return tensor;
}
int32_t ggml_get_i32_1d(const struct ggml_tensor * tensor, int i) {
switch (tensor->type) {
case GGML_TYPE_Q4_0:
{
GGML_ASSERT(false);
} break;
case GGML_TYPE_Q4_1:
{
GGML_ASSERT(false);
} break;
case GGML_TYPE_I8:
{
GGML_ASSERT(tensor->nb[0] == sizeof(int8_t));
return ((int8_t *)(tensor->data))[i];
} break;
case GGML_TYPE_I16:
{
GGML_ASSERT(tensor->nb[0] == sizeof(int16_t));
return ((int16_t *)(tensor->data))[i];
} break;
case GGML_TYPE_I32:
{
GGML_ASSERT(tensor->nb[0] == sizeof(int32_t));
return ((int32_t *)(tensor->data))[i];
} break;
case GGML_TYPE_F16:
{
GGML_ASSERT(tensor->nb[0] == sizeof(ggml_fp16_t));
return GGML_FP16_TO_FP32(((ggml_fp16_t *)(tensor->data))[i]);
} break;
case GGML_TYPE_F32:
{
GGML_ASSERT(tensor->nb[0] == sizeof(float));
return ((float *)(tensor->data))[i];
} break;
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
return 0.0f;
}
void ggml_set_i32_1d(const struct ggml_tensor * tensor, int i, int32_t value) {
switch (tensor->type) {
case GGML_TYPE_Q4_0:
{
GGML_ASSERT(false);
} break;
case GGML_TYPE_Q4_1:
{
GGML_ASSERT(false);
} break;
case GGML_TYPE_I8:
{
GGML_ASSERT(tensor->nb[0] == sizeof(int8_t));
((int8_t *)(tensor->data))[i] = value;
} break;
case GGML_TYPE_I16:
{
GGML_ASSERT(tensor->nb[0] == sizeof(int16_t));
((int16_t *)(tensor->data))[i] = value;
} break;
case GGML_TYPE_I32:
{
GGML_ASSERT(tensor->nb[0] == sizeof(int32_t));
((int32_t *)(tensor->data))[i] = value;
} break;
case GGML_TYPE_F16:
{
GGML_ASSERT(tensor->nb[0] == sizeof(ggml_fp16_t));
((ggml_fp16_t *)(tensor->data))[i] = GGML_FP32_TO_FP16(value);
} break;
case GGML_TYPE_F32:
{
GGML_ASSERT(tensor->nb[0] == sizeof(float));
((float *)(tensor->data))[i] = value;
} break;
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
float ggml_get_f32_1d(const struct ggml_tensor * tensor, int i) {
switch (tensor->type) {
case GGML_TYPE_Q4_0:
{
GGML_ASSERT(false);
} break;
case GGML_TYPE_Q4_1:
{
GGML_ASSERT(false);
} break;
case GGML_TYPE_I8:
{
GGML_ASSERT(tensor->nb[0] == sizeof(int8_t));
return ((int8_t *)(tensor->data))[i];
} break;
case GGML_TYPE_I16:
{
GGML_ASSERT(tensor->nb[0] == sizeof(int16_t));
return ((int16_t *)(tensor->data))[i];
} break;
case GGML_TYPE_I32:
{
GGML_ASSERT(tensor->nb[0] == sizeof(int32_t));
return ((int32_t *)(tensor->data))[i];
} break;
case GGML_TYPE_F16:
{
GGML_ASSERT(tensor->nb[0] == sizeof(ggml_fp16_t));
return GGML_FP16_TO_FP32(((ggml_fp16_t *)(tensor->data))[i]);
} break;
case GGML_TYPE_F32:
{
GGML_ASSERT(tensor->nb[0] == sizeof(float));
return ((float *)(tensor->data))[i];
} break;
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
return 0.0f;
}
void ggml_set_f32_1d(const struct ggml_tensor * tensor, int i, float value) {
switch (tensor->type) {
case GGML_TYPE_Q4_0:
{
GGML_ASSERT(false);
} break;
case GGML_TYPE_Q4_1:
{
GGML_ASSERT(false);
} break;
case GGML_TYPE_I8:
{
GGML_ASSERT(tensor->nb[0] == sizeof(int8_t));
((int8_t *)(tensor->data))[i] = value;
} break;
case GGML_TYPE_I16:
{
GGML_ASSERT(tensor->nb[0] == sizeof(int16_t));
((int16_t *)(tensor->data))[i] = value;
} break;
case GGML_TYPE_I32:
{
GGML_ASSERT(tensor->nb[0] == sizeof(int32_t));
((int32_t *)(tensor->data))[i] = value;
} break;
case GGML_TYPE_F16:
{
GGML_ASSERT(tensor->nb[0] == sizeof(ggml_fp16_t));
((ggml_fp16_t *)(tensor->data))[i] = GGML_FP32_TO_FP16(value);
} break;
case GGML_TYPE_F32:
{
GGML_ASSERT(tensor->nb[0] == sizeof(float));
((float *)(tensor->data))[i] = value;
} break;
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
void * ggml_get_data(const struct ggml_tensor * tensor) {
return tensor->data;
}
float * ggml_get_data_f32(const struct ggml_tensor * tensor) {
assert(tensor->type == GGML_TYPE_F32);
return (float *)(tensor->data);
}
struct ggml_tensor * ggml_view_tensor(
struct ggml_context * ctx,
const struct ggml_tensor * src) {
return ggml_new_tensor_impl(ctx, src->type, src->n_dims, src->ne, src->data);
}
////////////////////////////////////////////////////////////////////////////////
// ggml_dup
struct ggml_tensor * ggml_dup_impl(
struct ggml_context * ctx,
struct ggml_tensor * a,
bool inplace) {
bool is_node = false;
if (!inplace && (a->grad)) {
is_node = true;
}
struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
result->op = GGML_OP_DUP;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = NULL;
return result;
}
struct ggml_tensor * ggml_dup(
struct ggml_context * ctx,
struct ggml_tensor * a) {
return ggml_dup_impl(ctx, a, false);
}
struct ggml_tensor * ggml_dup_inplace(
struct ggml_context * ctx,
struct ggml_tensor * a) {
return ggml_dup_impl(ctx, a, true);
}
// ggml_add
struct ggml_tensor * ggml_add_impl(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b,
bool inplace) {
GGML_ASSERT(ggml_are_same_shape(a, b));
bool is_node = false;
if (!inplace && (a->grad || b->grad)) {
is_node = true;
}
struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
result->op = GGML_OP_ADD;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = b;
return result;
}
struct ggml_tensor * ggml_add(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b) {
return ggml_add_impl(ctx, a, b, false);
}
struct ggml_tensor * ggml_add_inplace(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b) {
return ggml_add_impl(ctx, a, b, true);
}
// ggml_sub
struct ggml_tensor * ggml_sub_impl(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b,
bool inplace) {
GGML_ASSERT(ggml_are_same_shape(a, b));
bool is_node = false;
if (!inplace && (a->grad || b->grad)) {
is_node = true;
}
struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
result->op = GGML_OP_SUB;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = b;
return result;
}
struct ggml_tensor * ggml_sub(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b) {
return ggml_sub_impl(ctx, a, b, false);
}
struct ggml_tensor * ggml_sub_inplace(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b) {
return ggml_sub_impl(ctx, a, b, true);
}
// ggml_mul
struct ggml_tensor * ggml_mul_impl(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b,
bool inplace) {
GGML_ASSERT(ggml_are_same_shape(a, b));
bool is_node = false;
if (!inplace && (a->grad || b->grad)) {
is_node = true;
}
if (inplace) {
GGML_ASSERT(is_node == false);
}
struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
result->op = GGML_OP_MUL;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = b;
return result;
}
struct ggml_tensor * ggml_mul(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b) {
return ggml_mul_impl(ctx, a, b, false);
}
struct ggml_tensor * ggml_mul_inplace(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b) {
return ggml_mul_impl(ctx, a, b, true);
}
// ggml_div
struct ggml_tensor * ggml_div_impl(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b,
bool inplace) {
GGML_ASSERT(ggml_are_same_shape(a, b));
bool is_node = false;
if (!inplace && (a->grad || b->grad)) {
is_node = true;
}
if (inplace) {
GGML_ASSERT(is_node == false);
}
struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
result->op = GGML_OP_DIV;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = b;
return result;
}
struct ggml_tensor * ggml_div(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b) {
return ggml_div_impl(ctx, a, b, false);
}
struct ggml_tensor * ggml_div_inplace(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b) {
return ggml_div_impl(ctx, a, b, true);
}
// ggml_sqr
struct ggml_tensor * ggml_sqr_impl(
struct ggml_context * ctx,
struct ggml_tensor * a,
bool inplace) {
bool is_node = false;
if (!inplace && (a->grad)) {
is_node = true;
}
struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
result->op = GGML_OP_SQR;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = NULL;
return result;
}
struct ggml_tensor * ggml_sqr(
struct ggml_context * ctx,
struct ggml_tensor * a) {
return ggml_sqr_impl(ctx, a, false);
}
struct ggml_tensor * ggml_sqr_inplace(
struct ggml_context * ctx,
struct ggml_tensor * a) {
return ggml_sqr_impl(ctx, a, true);
}
// ggml_sqrt
struct ggml_tensor * ggml_sqrt_impl(
struct ggml_context * ctx,
struct ggml_tensor * a,
bool inplace) {
bool is_node = false;
if (!inplace && (a->grad)) {
is_node = true;
}
struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
result->op = GGML_OP_SQRT;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = NULL;
return result;
}
struct ggml_tensor * ggml_sqrt(
struct ggml_context * ctx,
struct ggml_tensor * a) {
return ggml_sqrt_impl(ctx, a, false);
}
struct ggml_tensor * ggml_sqrt_inplace(
struct ggml_context * ctx,
struct ggml_tensor * a) {
return ggml_sqrt_impl(ctx, a, true);
}
// ggml_sum
struct ggml_tensor * ggml_sum(
struct ggml_context * ctx,
struct ggml_tensor * a) {
bool is_node = false;
if (a->grad) {
is_node = true;
}
struct ggml_tensor * result = ggml_new_tensor_1d(ctx, a->type, 1);
result->op = GGML_OP_SUM;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = NULL;
return result;
}
// ggml_mean
struct ggml_tensor * ggml_mean(
struct ggml_context * ctx,
struct ggml_tensor * a) {
bool is_node = false;
if (a->grad) {
GGML_ASSERT(false); // TODO: implement
is_node = true;
}
int ne[GGML_MAX_DIMS] = { 1, a->ne[1], a->ne[2], a->ne[3] };
struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, a->n_dims, ne);
result->op = GGML_OP_MEAN;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = NULL;
return result;
}
// ggml_repeat
struct ggml_tensor * ggml_repeat(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b) {
GGML_ASSERT(ggml_can_repeat(a, b));
bool is_node = false;
if (a->grad) {
is_node = true;
}
if (ggml_are_same_shape(a, b) && !is_node) {
return a;
}
struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, b->n_dims, b->ne);
result->op = GGML_OP_REPEAT;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = b;
return result;
}
// ggml_abs
struct ggml_tensor * ggml_abs_impl(
struct ggml_context * ctx,
struct ggml_tensor * a,
bool inplace) {
bool is_node = false;
if (!inplace && (a->grad)) {
is_node = true;
}
struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
result->op = GGML_OP_ABS;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = NULL;
return result;
}
struct ggml_tensor * ggml_abs(
struct ggml_context * ctx,
struct ggml_tensor * a) {
return ggml_abs_impl(ctx, a, false);
}
struct ggml_tensor * ggml_abs_inplace(
struct ggml_context * ctx,
struct ggml_tensor * a) {
return ggml_abs_impl(ctx, a, true);
}
// ggml_sgn
struct ggml_tensor * ggml_sgn_impl(
struct ggml_context * ctx,
struct ggml_tensor * a,
bool inplace) {
bool is_node = false;
if (!inplace && (a->grad)) {
is_node = true;
}
struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
result->op = GGML_OP_SGN;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = NULL;
return result;
}
struct ggml_tensor * ggml_sgn(
struct ggml_context * ctx,
struct ggml_tensor * a) {
return ggml_sgn_impl(ctx, a, false);
}
struct ggml_tensor * ggml_sgn_inplace(
struct ggml_context * ctx,
struct ggml_tensor * a) {
return ggml_sgn_impl(ctx, a, true);
}
// ggml_neg
struct ggml_tensor * ggml_neg_impl(
struct ggml_context * ctx,
struct ggml_tensor * a,
bool inplace) {
bool is_node = false;
if (!inplace && (a->grad)) {
is_node = true;
}
struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
result->op = GGML_OP_NEG;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = NULL;
return result;
}
struct ggml_tensor * ggml_neg(
struct ggml_context * ctx,
struct ggml_tensor * a) {
return ggml_neg_impl(ctx, a, false);
}
struct ggml_tensor * ggml_neg_inplace(
struct ggml_context * ctx,
struct ggml_tensor * a) {
return ggml_neg_impl(ctx, a, true);
}
// ggml_step
struct ggml_tensor * ggml_step_impl(
struct ggml_context * ctx,
struct ggml_tensor * a,
bool inplace) {
bool is_node = false;
if (!inplace && (a->grad)) {
is_node = true;
}
struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
result->op = GGML_OP_STEP;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = NULL;
return result;
}
struct ggml_tensor * ggml_step(
struct ggml_context * ctx,
struct ggml_tensor * a) {
return ggml_step_impl(ctx, a, false);
}
struct ggml_tensor * ggml_step_inplace(
struct ggml_context * ctx,
struct ggml_tensor * a) {
return ggml_step_impl(ctx, a, true);
}
// ggml_relu
struct ggml_tensor * ggml_relu_impl(
struct ggml_context * ctx,
struct ggml_tensor * a,
bool inplace) {
bool is_node = false;
if (!inplace && (a->grad)) {
is_node = true;
}
struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
result->op = GGML_OP_RELU;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = NULL;
return result;
}
struct ggml_tensor * ggml_relu(
struct ggml_context * ctx,
struct ggml_tensor * a) {
return ggml_relu_impl(ctx, a, false);
}
struct ggml_tensor * ggml_relu_inplace(
struct ggml_context * ctx,
struct ggml_tensor * a) {
return ggml_relu_impl(ctx, a, true);
}
// ggml_gelu
struct ggml_tensor * ggml_gelu_impl(
struct ggml_context * ctx,
struct ggml_tensor * a,
bool inplace) {
bool is_node = false;
if (!inplace && (a->grad)) {
is_node = true;
}
struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
result->op = GGML_OP_GELU;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = NULL;
return result;
}
struct ggml_tensor * ggml_gelu(
struct ggml_context * ctx,
struct ggml_tensor * a) {
return ggml_gelu_impl(ctx, a, false);
}
struct ggml_tensor * ggml_gelu_inplace(
struct ggml_context * ctx,
struct ggml_tensor * a) {
return ggml_gelu_impl(ctx, a, true);
}
// ggml_silu
struct ggml_tensor * ggml_silu_impl(
struct ggml_context * ctx,
struct ggml_tensor * a,
bool inplace) {
bool is_node = false;
if (!inplace && (a->grad)) {
is_node = true;
}
struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
result->op = GGML_OP_SILU;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = NULL;
return result;
}
struct ggml_tensor * ggml_silu(
struct ggml_context * ctx,
struct ggml_tensor * a) {
return ggml_silu_impl(ctx, a, false);
}
struct ggml_tensor * ggml_silu_inplace(
struct ggml_context * ctx,
struct ggml_tensor * a) {
return ggml_silu_impl(ctx, a, true);
}
// ggml_norm
struct ggml_tensor * ggml_norm_impl(
struct ggml_context * ctx,
struct ggml_tensor * a,
bool inplace) {
bool is_node = false;
if (!inplace && (a->grad)) {
GGML_ASSERT(false); // TODO: implement backward
is_node = true;
}
struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
result->op = GGML_OP_NORM;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = NULL; // TODO: maybe store epsilon here?
return result;
}
struct ggml_tensor * ggml_norm(
struct ggml_context * ctx,
struct ggml_tensor * a) {
return ggml_norm_impl(ctx, a, false);
}
struct ggml_tensor * ggml_norm_inplace(
struct ggml_context * ctx,
struct ggml_tensor * a) {
return ggml_norm_impl(ctx, a, true);
}
struct ggml_tensor * ggml_rms_norm_impl(
struct ggml_context * ctx,
struct ggml_tensor * a,
bool inplace) {
bool is_node = false;
if (!inplace && (a->grad)) {
GGML_ASSERT(false); // TODO: implement backward
is_node = true;
}
struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
result->op = GGML_OP_RMS_NORM;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = NULL; // TODO: maybe store epsilon here?
return result;
}
struct ggml_tensor * ggml_rms_norm(
struct ggml_context * ctx,
struct ggml_tensor * a) {
return ggml_rms_norm_impl(ctx, a, false);
}
struct ggml_tensor * ggml_rms_norm_inplace(
struct ggml_context * ctx,
struct ggml_tensor * a) {
return ggml_rms_norm_impl(ctx, a, true);
}
// ggml_mul_mat
struct ggml_tensor * ggml_mul_mat(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b) {
GGML_ASSERT(ggml_can_mul_mat(a, b));
GGML_ASSERT(!ggml_is_transposed(a));
bool is_node = false;
if (a->grad || b->grad) {
is_node = true;
}
const int ne[4] = { a->ne[1], b->ne[1], a->ne[2], b->ne[3] };
struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, MIN(a->n_dims, b->n_dims), ne);
result->op = GGML_OP_MUL_MAT;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = b;
return result;
}
// ggml_scale
struct ggml_tensor * ggml_scale_impl(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b,
bool inplace) {
GGML_ASSERT(ggml_is_scalar(b));
GGML_ASSERT(ggml_is_padded_1d(a));
bool is_node = false;
if (!inplace && (a->grad || b->grad)) {
GGML_ASSERT(false); // TODO: implement backward
is_node = true;
}
// TODO: when implement backward, fix this:
//struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
struct ggml_tensor * result = ggml_view_tensor(ctx, a);
result->op = GGML_OP_SCALE;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = b;
return result;
}
struct ggml_tensor * ggml_scale(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b) {
return ggml_scale_impl(ctx, a, b, false);
}
struct ggml_tensor * ggml_scale_inplace(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b) {
return ggml_scale_impl(ctx, a, b, true);
}
// ggml_cpy
struct ggml_tensor * ggml_cpy_impl(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b,
bool inplace) {
GGML_ASSERT(ggml_nelements(a) == ggml_nelements(b));
bool is_node = false;
if (!inplace && (a->grad || b->grad)) {
GGML_ASSERT(false); // TODO: implement backward
is_node = true;
}
// make a view of the destination
struct ggml_tensor * result = ggml_view_tensor(ctx, b);
result->op = GGML_OP_CPY;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = b;
return result;
}
struct ggml_tensor * ggml_cpy(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b) {
return ggml_cpy_impl(ctx, a, b, false);
}
struct ggml_tensor * ggml_cpy_inplace(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b) {
return ggml_cpy_impl(ctx, a, b, true);
}
// ggml_reshape
struct ggml_tensor * ggml_reshape(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b) {
GGML_ASSERT(ggml_is_contiguous(a));
GGML_ASSERT(ggml_is_contiguous(b));
GGML_ASSERT(ggml_nelements(a) == ggml_nelements(b));
bool is_node = false;
if (a->grad || b->grad) {
GGML_ASSERT(false); // TODO: implement backward
is_node = true;
}
struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, b->n_dims, b->ne, a->data);
result->op = GGML_OP_RESHAPE;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = NULL;
return result;
}
struct ggml_tensor * ggml_reshape_2d(
struct ggml_context * ctx,
struct ggml_tensor * a,
int ne0,
int ne1) {
GGML_ASSERT(ggml_is_contiguous(a));
GGML_ASSERT(ggml_nelements(a) == ne0*ne1);
bool is_node = false;
if (a->grad) {
GGML_ASSERT(false); // TODO: implement backward
is_node = true;
}
const int ne[2] = { ne0, ne1 };
struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 2, ne, a->data);
result->op = GGML_OP_RESHAPE;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = NULL;
return result;
}
struct ggml_tensor * ggml_reshape_3d(
struct ggml_context * ctx,
struct ggml_tensor * a,
int ne0,
int ne1,
int ne2) {
GGML_ASSERT(ggml_is_contiguous(a));
GGML_ASSERT(ggml_nelements(a) == ne0*ne1*ne2);
bool is_node = false;
if (a->grad) {
GGML_ASSERT(false); // TODO: implement backward
is_node = true;
}
const int ne[3] = { ne0, ne1, ne2 };
struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 3, ne, a->data);
result->op = GGML_OP_RESHAPE;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = NULL;
return result;
}
// ggml_view_1d
struct ggml_tensor * ggml_view_1d(
struct ggml_context * ctx,
struct ggml_tensor * a,
int ne0,
size_t offset) {
if (a->grad) {
GGML_ASSERT(false); // gradient propagation is not supported
}
struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 1, &ne0, (char *) a->data + offset);
result->op = GGML_OP_VIEW;
result->grad = NULL;
result->src0 = a;
result->src1 = NULL; // TODO: maybe store the offset here?
return result;
}
// ggml_view_2d
struct ggml_tensor * ggml_view_2d(
struct ggml_context * ctx,
struct ggml_tensor * a,
int ne0,
int ne1,
size_t nb1,
size_t offset) {
if (a->grad) {
GGML_ASSERT(false); // gradient propagation is not supported
}
const int ne[GGML_MAX_DIMS] = { ne0, ne1, 1, 1 };
struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 2, ne, (char *) a->data + offset);
result->nb[1] = nb1;
result->nb[2] = result->nb[1]*ne1;
result->nb[3] = result->nb[2];
result->op = GGML_OP_VIEW;
result->grad = NULL;
result->src0 = a;
result->src1 = NULL; // TODO: maybe store the offset here?
return result;
}
// ggml_permute
struct ggml_tensor * ggml_permute(
struct ggml_context * ctx,
struct ggml_tensor * a,
int axis0,
int axis1,
int axis2,
int axis3) {
GGML_ASSERT(axis0 >= 0 && axis0 < GGML_MAX_DIMS);
GGML_ASSERT(axis1 >= 0 && axis1 < GGML_MAX_DIMS);
GGML_ASSERT(axis2 >= 0 && axis2 < GGML_MAX_DIMS);
GGML_ASSERT(axis3 >= 0 && axis3 < GGML_MAX_DIMS);
GGML_ASSERT(axis0 != axis1);
GGML_ASSERT(axis0 != axis2);
GGML_ASSERT(axis0 != axis3);
GGML_ASSERT(axis1 != axis2);
GGML_ASSERT(axis1 != axis3);
GGML_ASSERT(axis2 != axis3);
bool is_node = false;
if (a->grad) {
GGML_ASSERT(false); // TODO: implement backward
is_node = true;
}
struct ggml_tensor * result = ggml_view_tensor(ctx, a);
int ne[GGML_MAX_DIMS];
int nb[GGML_MAX_DIMS];
ne[axis0] = a->ne[0];
ne[axis1] = a->ne[1];
ne[axis2] = a->ne[2];
ne[axis3] = a->ne[3];
nb[axis0] = a->nb[0];
nb[axis1] = a->nb[1];
nb[axis2] = a->nb[2];
nb[axis3] = a->nb[3];
result->ne[0] = ne[0];
result->ne[1] = ne[1];
result->ne[2] = ne[2];
result->ne[3] = ne[3];
result->nb[0] = nb[0];
result->nb[1] = nb[1];
result->nb[2] = nb[2];
result->nb[3] = nb[3];
result->op = GGML_OP_PERMUTE;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = NULL; // TODO: maybe store the permutation here?
return result;
}
// ggml_transpose
struct ggml_tensor * ggml_transpose(
struct ggml_context * ctx,
struct ggml_tensor * a) {
bool is_node = false;
if (a->grad) {
GGML_ASSERT(false); // TODO: implement backward
is_node = true;
}
struct ggml_tensor * result = ggml_view_tensor(ctx, a);
result->ne[0] = a->ne[1];
result->ne[1] = a->ne[0];
result->nb[0] = a->nb[1];
result->nb[1] = a->nb[0];
result->op = GGML_OP_TRANSPOSE;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = NULL;
return result;
}
// ggml_get_rows
struct ggml_tensor * ggml_get_rows(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b) {
GGML_ASSERT(ggml_is_matrix(a) && ggml_is_vector(b) && b->type == GGML_TYPE_I32);
bool is_node = false;
if (a->grad || b->grad) {
GGML_ASSERT(false); // TODO: implement backward
is_node = true;
}
// TODO: implement non F32 return
//struct ggml_tensor * result = ggml_new_tensor_2d(ctx, a->type, a->ne[0], b->ne[0]);
struct ggml_tensor * result = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, a->ne[0], b->ne[0]);
result->op = GGML_OP_GET_ROWS;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = b;
return result;
}
// ggml_diag_mask_inf
struct ggml_tensor * ggml_diag_mask_inf(
struct ggml_context * ctx,
struct ggml_tensor * a,
int n_past) {
bool is_node = false;
if (a->grad) {
GGML_ASSERT(false); // TODO: implement backward
is_node = true;
}
// TODO: when implement backward, fix this:
//struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
struct ggml_tensor * result = ggml_view_tensor(ctx, a);
struct ggml_tensor * b = ggml_new_i32(ctx, n_past);
result->op = GGML_OP_DIAG_MASK_INF;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = b;
return result;
}
// ggml_soft_max
struct ggml_tensor * ggml_soft_max(
struct ggml_context * ctx,
struct ggml_tensor * a) {
bool is_node = false;
if (a->grad) {
GGML_ASSERT(false); // TODO: implement backward
is_node = true;
}
// TODO: when implement backward, fix this:
//struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
struct ggml_tensor * result = ggml_view_tensor(ctx, a);
result->op = GGML_OP_SOFT_MAX;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = NULL;
return result;
}
// ggml_rope
struct ggml_tensor * ggml_rope(
struct ggml_context * ctx,
struct ggml_tensor * a,
int n_past,
int n_dims,
int mode) {
GGML_ASSERT(n_past >= 0);
bool is_node = false;
if (a->grad) {
GGML_ASSERT(false); // TODO: implement backward
is_node = true;
}
// TODO: when implement backward, fix this:
//struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
struct ggml_tensor * result = ggml_view_tensor(ctx, a);
struct ggml_tensor * b = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 3);
((int32_t *) b->data)[0] = n_past;
((int32_t *) b->data)[1] = n_dims;
((int32_t *) b->data)[2] = mode;
result->op = GGML_OP_ROPE;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = b;
return result;
}
// ggml_conv_1d_1s
struct ggml_tensor * ggml_conv_1d_1s(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b) {
GGML_ASSERT(ggml_is_matrix(b));
GGML_ASSERT(a->ne[1] == b->ne[1]);
GGML_ASSERT(a->ne[3] == 1);
bool is_node = false;
if (a->grad || b->grad) {
GGML_ASSERT(false); // TODO: implement backward
is_node = true;
}
const int ne[4] = { b->ne[0], a->ne[2], 1, 1, };
struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 2, ne);
result->op = GGML_OP_CONV_1D_1S;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = b;
return result;
}
// ggml_conv_1d_2s
struct ggml_tensor * ggml_conv_1d_2s(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b) {
GGML_ASSERT(ggml_is_matrix(b));
GGML_ASSERT(a->ne[1] == b->ne[1]);
GGML_ASSERT(a->ne[3] == 1);
bool is_node = false;
if (a->grad || b->grad) {
GGML_ASSERT(false); // TODO: implement backward
is_node = true;
}
const int ne[4] = { b->ne[0]/2, a->ne[2], 1, 1, };
struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 2, ne);
result->op = GGML_OP_CONV_1D_2S;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = b;
return result;
}
// ggml_flash_attn
struct ggml_tensor * ggml_flash_attn(
struct ggml_context * ctx,
struct ggml_tensor * q,
struct ggml_tensor * k,
struct ggml_tensor * v,
bool masked) {
GGML_ASSERT(ggml_can_mul_mat(k, q));
// TODO: check if vT can be multiplied by (k*qT)
bool is_node = false;
if (q->grad || k->grad || v->grad) {
GGML_ASSERT(false); // TODO: implement backward
is_node = true;
}
//struct ggml_tensor * result = ggml_dup_tensor(ctx, q);
struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, q->ne);
result->op = GGML_OP_FLASH_ATTN;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = q;
result->src1 = k;
result->opt[0] = v;
result->opt[1] = ggml_new_i32(ctx, masked ? 1 : 0);
return result;
}
// ggml_flash_ff
struct ggml_tensor * ggml_flash_ff(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b0,
struct ggml_tensor * b1,
struct ggml_tensor * c0,
struct ggml_tensor * c1) {
GGML_ASSERT(ggml_can_mul_mat(b0, a));
// TODO: more checks
bool is_node = false;
if (a->grad || b0->grad || b1->grad || c0->grad || c1->grad) {
GGML_ASSERT(false); // TODO: implement backward
is_node = true;
}
//struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, a->ne);
result->op = GGML_OP_FLASH_FF;
result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result->src0 = a;
result->src1 = b0;
result->opt[0] = b1;
result->opt[1] = c0;
result->opt[2] = c1;
return result;
}
////////////////////////////////////////////////////////////////////////////////
void ggml_set_param(
struct ggml_context * ctx,
struct ggml_tensor * tensor) {
tensor->is_param = true;
GGML_ASSERT(tensor->grad == NULL);
tensor->grad = ggml_dup_tensor(ctx, tensor);
}
// ggml_compute_forward_dup
static void ggml_compute_forward_dup_f16(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
GGML_ASSERT(params->ith == 0);
GGML_ASSERT(ggml_is_contiguous(dst));
GGML_ASSERT(ggml_nelements(dst) == ggml_nelements(src0));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int ne00 = src0->ne[0];
const int ne01 = src0->ne[1];
const int ne02 = src0->ne[2];
const int ne03 = src0->ne[3];
const size_t nb00 = src0->nb[0];
const size_t nb01 = src0->nb[1];
const size_t nb02 = src0->nb[2];
const size_t nb03 = src0->nb[3];
if (ggml_is_contiguous(src0) && src0->type == dst->type) {
memcpy(dst->data, src0->data, ggml_nelements(dst) * GGML_TYPE_SIZE[src0->type]);
return;
}
if (src0->nb[0] == sizeof(ggml_fp16_t)) {
if (dst->type == GGML_TYPE_F16) {
size_t id = 0;
const size_t rs = ne00*nb00;
for (int i03 = 0; i03 < ne03; i03++) {
for (int i02 = 0; i02 < ne02; i02++) {
for (int i01 = 0; i01 < ne01; i01++) {
const char * src0_ptr = (char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03;
char * dst_ptr = (char *) dst->data + id*rs;
memcpy(dst_ptr, src0_ptr, rs);
id++;
}
}
}
} else if (dst->type == GGML_TYPE_F32) {
size_t id = 0;
float * dst_ptr = (float *) dst->data;
for (int i03 = 0; i03 < ne03; i03++) {
for (int i02 = 0; i02 < ne02; i02++) {
for (int i01 = 0; i01 < ne01; i01++) {
for (int i00 = 0; i00 < ne00; i00++) {
const ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
dst_ptr[id] = GGML_FP16_TO_FP32(*src0_ptr);
id++;
}
}
}
}
} else {
GGML_ASSERT(false); // TODO: implement
}
} else {
//printf("%s: this is not optimal - fix me\n", __func__);
if (dst->type == GGML_TYPE_F32) {
size_t id = 0;
float * dst_ptr = (float *) dst->data;
for (int i03 = 0; i03 < ne03; i03++) {
for (int i02 = 0; i02 < ne02; i02++) {
for (int i01 = 0; i01 < ne01; i01++) {
for (int i00 = 0; i00 < ne00; i00++) {
const ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
dst_ptr[id] = GGML_FP16_TO_FP32(*src0_ptr);
id++;
}
}
}
}
} else if (dst->type == GGML_TYPE_F16) {
size_t id = 0;
ggml_fp16_t * dst_ptr = (ggml_fp16_t *) dst->data;
for (int i03 = 0; i03 < ne03; i03++) {
for (int i02 = 0; i02 < ne02; i02++) {
for (int i01 = 0; i01 < ne01; i01++) {
for (int i00 = 0; i00 < ne00; i00++) {
const ggml_fp16_t * src0_ptr = (ggml_fp16_t *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
dst_ptr[id] = *src0_ptr;
id++;
}
}
}
}
} else {
GGML_ASSERT(false); // TODO: implement
}
}
}
static void ggml_compute_forward_dup_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
GGML_ASSERT(params->ith == 0);
GGML_ASSERT(ggml_is_contiguous(dst));
GGML_ASSERT(ggml_nelements(dst) == ggml_nelements(src0));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int ne00 = src0->ne[0];
const int ne01 = src0->ne[1];
const int ne02 = src0->ne[2];
const int ne03 = src0->ne[3];
const size_t nb00 = src0->nb[0];
const size_t nb01 = src0->nb[1];
const size_t nb02 = src0->nb[2];
const size_t nb03 = src0->nb[3];
if (ggml_is_contiguous(src0) && src0->type == dst->type) {
memcpy(dst->data, src0->data, ggml_nelements(dst) * GGML_TYPE_SIZE[src0->type]);
return;
}
if (src0->nb[0] == sizeof(float)) {
if (dst->type == GGML_TYPE_F32) {
size_t id = 0;
const size_t rs = ne00*nb00;
for (int i03 = 0; i03 < ne03; i03++) {
for (int i02 = 0; i02 < ne02; i02++) {
for (int i01 = 0; i01 < ne01; i01++) {
const char * src0_ptr = (char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03;
char * dst_ptr = (char *) dst->data + id*rs;
memcpy(dst_ptr, src0_ptr, rs);
id++;
}
}
}
} else if (dst->type == GGML_TYPE_F16) {
size_t id = 0;
ggml_fp16_t * dst_ptr = (ggml_fp16_t *) dst->data;
for (int i03 = 0; i03 < ne03; i03++) {
for (int i02 = 0; i02 < ne02; i02++) {
for (int i01 = 0; i01 < ne01; i01++) {
for (int i00 = 0; i00 < ne00; i00++) {
const float * src0_ptr = (float *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
dst_ptr[id] = GGML_FP32_TO_FP16(*src0_ptr);
id++;
}
}
}
}
} else {
GGML_ASSERT(false); // TODO: implement
}
} else {
//printf("%s: this is not optimal - fix me\n", __func__);
if (dst->type == GGML_TYPE_F32) {
size_t id = 0;
float * dst_ptr = (float *) dst->data;
for (int i03 = 0; i03 < ne03; i03++) {
for (int i02 = 0; i02 < ne02; i02++) {
for (int i01 = 0; i01 < ne01; i01++) {
for (int i00 = 0; i00 < ne00; i00++) {
const float * src0_ptr = (float *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
dst_ptr[id] = *src0_ptr;
id++;
}
}
}
}
} else if (dst->type == GGML_TYPE_F16) {
size_t id = 0;
ggml_fp16_t * dst_ptr = (ggml_fp16_t *) dst->data;
for (int i03 = 0; i03 < ne03; i03++) {
for (int i02 = 0; i02 < ne02; i02++) {
for (int i01 = 0; i01 < ne01; i01++) {
for (int i00 = 0; i00 < ne00; i00++) {
const float * src0_ptr = (float *) ((char *) src0->data + i00*nb00 + i01*nb01 + i02*nb02 + i03*nb03);
dst_ptr[id] = GGML_FP32_TO_FP16(*src0_ptr);
id++;
}
}
}
}
} else {
GGML_ASSERT(false); // TODO: implement
}
}
}
static void ggml_compute_forward_dup(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_F16:
{
ggml_compute_forward_dup_f16(params, src0, dst);
} break;
case GGML_TYPE_F32:
{
ggml_compute_forward_dup_f32(params, src0, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
// ggml_compute_forward_add
static void ggml_compute_forward_add_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
GGML_ASSERT(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int ith = params->ith;
const int nth = params->nth;
const int n = ggml_nrows(src0);
const int nc = src0->ne[0];
const size_t nb00 = src0->nb[0];
const size_t nb01 = src0->nb[1];
const size_t nb10 = src1->nb[0];
const size_t nb11 = src1->nb[1];
const size_t nb0 = dst->nb[0];
const size_t nb1 = dst->nb[1];
GGML_ASSERT( nb0 == sizeof(float));
GGML_ASSERT(nb00 == sizeof(float));
if (nb10 == sizeof(float)) {
const int j0 = (n/nth)*ith;
const int j1 = ith == nth - 1 ? n : (n/nth)*(ith + 1);
for (int j = j0; j < j1; j++) {
ggml_vec_add_f32(nc,
(float *) ((char *) dst->data + j*nb1),
(float *) ((char *) src0->data + j*nb01),
(float *) ((char *) src1->data + j*nb11));
}
} else {
// src1 is not contiguous
for (int j = ith; j < n; j += nth) {
float * dst_ptr = (float *) ((char *) dst->data + j*nb1);
float * src0_ptr = (float *) ((char *) src0->data + j*nb01);
for (int i = 0; i < nc; i++) {
float * src1_ptr = (float *) ((char *) src1->data + j*nb11 + i*nb10);
dst_ptr[i] = src0_ptr[i] + *src1_ptr;
}
}
}
}
static void ggml_compute_forward_add(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_F32:
{
ggml_compute_forward_add_f32(params, src0, src1, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_F16:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
// ggml_compute_forward_sub
static void ggml_compute_forward_sub_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int n = ggml_nrows(src0);
const int nc = src0->ne[0];
assert( dst->nb[0] == sizeof(float));
assert(src0->nb[0] == sizeof(float));
assert(src1->nb[0] == sizeof(float));
for (int i = 0; i < n; i++) {
ggml_vec_sub_f32(nc,
(float *) ((char *) dst->data + i*( dst->nb[1])),
(float *) ((char *) src0->data + i*(src0->nb[1])),
(float *) ((char *) src1->data + i*(src1->nb[1])));
}
}
static void ggml_compute_forward_sub(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_F32:
{
ggml_compute_forward_sub_f32(params, src0, src1, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_F16:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
// ggml_compute_forward_mul
static void ggml_compute_forward_mul_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int n = ggml_nrows(src0);
const int nc = src0->ne[0];
assert( dst->nb[0] == sizeof(float));
assert(src0->nb[0] == sizeof(float));
assert(src1->nb[0] == sizeof(float));
for (int i = 0; i < n; i++) {
ggml_vec_mul_f32(nc,
(float *) ((char *) dst->data + i*( dst->nb[1])),
(float *) ((char *) src0->data + i*(src0->nb[1])),
(float *) ((char *) src1->data + i*(src1->nb[1])));
}
}
static void ggml_compute_forward_mul(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_F32:
{
ggml_compute_forward_mul_f32(params, src0, src1, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_F16:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
// ggml_compute_forward_div
static void ggml_compute_forward_div_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(ggml_are_same_shape(src0, src1) && ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int n = ggml_nrows(src0);
const int nc = src0->ne[0];
assert( dst->nb[0] == sizeof(float));
assert(src0->nb[0] == sizeof(float));
assert(src1->nb[0] == sizeof(float));
for (int i = 0; i < n; i++) {
ggml_vec_div_f32(nc,
(float *) ((char *) dst->data + i*( dst->nb[1])),
(float *) ((char *) src0->data + i*(src0->nb[1])),
(float *) ((char *) src1->data + i*(src1->nb[1])));
}
}
static void ggml_compute_forward_div(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_F32:
{
ggml_compute_forward_div_f32(params, src0, src1, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_F16:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
// ggml_compute_forward_sqr
static void ggml_compute_forward_sqr_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int n = ggml_nrows(src0);
const int nc = src0->ne[0];
assert( dst->nb[0] == sizeof(float));
assert(src0->nb[0] == sizeof(float));
for (int i = 0; i < n; i++) {
ggml_vec_sqr_f32(nc,
(float *) ((char *) dst->data + i*( dst->nb[1])),
(float *) ((char *) src0->data + i*(src0->nb[1])));
}
}
static void ggml_compute_forward_sqr(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_F32:
{
ggml_compute_forward_sqr_f32(params, src0, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_F16:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
// ggml_compute_forward_sqrt
static void ggml_compute_forward_sqrt_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int n = ggml_nrows(src0);
const int nc = src0->ne[0];
assert( dst->nb[0] == sizeof(float));
assert(src0->nb[0] == sizeof(float));
for (int i = 0; i < n; i++) {
ggml_vec_sqrt_f32(nc,
(float *) ((char *) dst->data + i*( dst->nb[1])),
(float *) ((char *) src0->data + i*(src0->nb[1])));
}
}
static void ggml_compute_forward_sqrt(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_F32:
{
ggml_compute_forward_sqrt_f32(params, src0, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_F16:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
// ggml_compute_forward_sum
static void ggml_compute_forward_sum_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(ggml_is_scalar(dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
assert(ggml_is_scalar(dst));
assert(src0->nb[0] == sizeof(float));
const int ne00 = src0->ne[0];
const int ne01 = src0->ne[1];
const int ne02 = src0->ne[2];
const int ne03 = src0->ne[3];
const size_t nb01 = src0->nb[1];
const size_t nb02 = src0->nb[2];
const size_t nb03 = src0->nb[3];
for (int i03 = 0; i03 < ne03; i03++) {
for (int i02 = 0; i02 < ne02; i02++) {
for (int i01 = 0; i01 < ne01; i01++) {
ggml_vec_sum_f32(ne00,
(float *) (dst->data),
(float *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03));
}
}
}
}
static void ggml_compute_forward_sum(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_F32:
{
ggml_compute_forward_sum_f32(params, src0, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_F16:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
// ggml_compute_forward_mean
static void ggml_compute_forward_mean_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
assert(params->ith == 0);
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
assert(src0->nb[0] == sizeof(float));
const int ne00 = src0->ne[0];
const int ne01 = src0->ne[1];
const int ne02 = src0->ne[2];
const int ne03 = src0->ne[3];
const size_t nb01 = src0->nb[1];
const size_t nb02 = src0->nb[2];
const size_t nb03 = src0->nb[3];
const int ne0 = dst->ne[0];
const int ne1 = dst->ne[1];
const int ne2 = dst->ne[2];
const int ne3 = dst->ne[3];
assert(ne0 == 1);
assert(ne1 == ne01);
assert(ne2 == ne02);
assert(ne3 == ne03);
UNUSED(ne0);
UNUSED(ne1);
UNUSED(ne2);
UNUSED(ne3);
const size_t nb1 = dst->nb[1];
const size_t nb2 = dst->nb[2];
const size_t nb3 = dst->nb[3];
for (int i03 = 0; i03 < ne03; i03++) {
for (int i02 = 0; i02 < ne02; i02++) {
for (int i01 = 0; i01 < ne01; i01++) {
ggml_vec_sum_f32(ne00,
(float *) ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3),
(float *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03));
*(float *) ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3) /= (float) ne00;
}
}
}
}
static void ggml_compute_forward_mean(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_F32:
{
ggml_compute_forward_mean_f32(params, src0, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_F16:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
// ggml_compute_forward_repeat
static void ggml_compute_forward_repeat_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(ggml_can_repeat(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
// TODO: implement support for rank > 2 tensors
assert(src0->ne[2] == 1);
assert(src0->ne[3] == 1);
assert( dst->ne[2] == 1);
assert( dst->ne[3] == 1);
const int nc = dst->ne[0];
const int nr = dst->ne[1];
const int nc0 = src0->ne[0];
const int nr0 = src0->ne[1];
const int ncr = nc/nc0; // guaranteed to be an integer due to the check in ggml_can_repeat
const int nrr = nr/nr0; // guaranteed to be an integer due to the check in ggml_can_repeat
// TODO: support for transposed / permuted tensors
assert( dst->nb[0] == sizeof(float));
assert(src0->nb[0] == sizeof(float));
// TODO: maybe this is not optimal?
for (int i = 0; i < nrr; i++) {
for (int j = 0; j < ncr; j++) {
for (int k = 0; k < nr0; k++) {
ggml_vec_cpy_f32(nc0,
(float *) ((char *) dst->data + (i*nr0 + k)*( dst->nb[1]) + j*nc0*( dst->nb[0])),
(float *) ((char *) src0->data + ( k)*(src0->nb[1])));
}
}
}
}
static void ggml_compute_forward_repeat(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_F32:
{
ggml_compute_forward_repeat_f32(params, src0, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_F16:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
// ggml_compute_forward_abs
static void ggml_compute_forward_abs_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int n = ggml_nrows(src0);
const int nc = src0->ne[0];
assert(dst->nb[0] == sizeof(float));
assert(src0->nb[0] == sizeof(float));
for (int i = 0; i < n; i++) {
ggml_vec_abs_f32(nc,
(float *) ((char *) dst->data + i*( dst->nb[1])),
(float *) ((char *) src0->data + i*(src0->nb[1])));
}
}
static void ggml_compute_forward_abs(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_F32:
{
ggml_compute_forward_abs_f32(params, src0, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_F16:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
// ggml_compute_forward_sgn
static void ggml_compute_forward_sgn_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int n = ggml_nrows(src0);
const int nc = src0->ne[0];
assert(dst->nb[0] == sizeof(float));
assert(src0->nb[0] == sizeof(float));
for (int i = 0; i < n; i++) {
ggml_vec_sgn_f32(nc,
(float *) ((char *) dst->data + i*( dst->nb[1])),
(float *) ((char *) src0->data + i*(src0->nb[1])));
}
}
static void ggml_compute_forward_sgn(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_F32:
{
ggml_compute_forward_sgn_f32(params, src0, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_F16:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
// ggml_compute_forward_neg
static void ggml_compute_forward_neg_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int n = ggml_nrows(src0);
const int nc = src0->ne[0];
assert(dst->nb[0] == sizeof(float));
assert(src0->nb[0] == sizeof(float));
for (int i = 0; i < n; i++) {
ggml_vec_neg_f32(nc,
(float *) ((char *) dst->data + i*( dst->nb[1])),
(float *) ((char *) src0->data + i*(src0->nb[1])));
}
}
static void ggml_compute_forward_neg(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_F32:
{
ggml_compute_forward_neg_f32(params, src0, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_F16:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
// ggml_compute_forward_step
static void ggml_compute_forward_step_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int n = ggml_nrows(src0);
const int nc = src0->ne[0];
assert(dst->nb[0] == sizeof(float));
assert(src0->nb[0] == sizeof(float));
for (int i = 0; i < n; i++) {
ggml_vec_step_f32(nc,
(float *) ((char *) dst->data + i*( dst->nb[1])),
(float *) ((char *) src0->data + i*(src0->nb[1])));
}
}
static void ggml_compute_forward_step(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_F32:
{
ggml_compute_forward_step_f32(params, src0, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_F16:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
// ggml_compute_forward_relu
static void ggml_compute_forward_relu_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int n = ggml_nrows(src0);
const int nc = src0->ne[0];
assert(dst->nb[0] == sizeof(float));
assert(src0->nb[0] == sizeof(float));
for (int i = 0; i < n; i++) {
ggml_vec_relu_f32(nc,
(float *) ((char *) dst->data + i*( dst->nb[1])),
(float *) ((char *) src0->data + i*(src0->nb[1])));
}
}
static void ggml_compute_forward_relu(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_F32:
{
ggml_compute_forward_relu_f32(params, src0, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_F16:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
// ggml_compute_forward_gelu
static void ggml_compute_forward_gelu_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
GGML_ASSERT(ggml_is_contiguous(src0));
GGML_ASSERT(ggml_is_contiguous(dst));
GGML_ASSERT(ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int ith = params->ith;
const int nth = params->nth;
const int nc = src0->ne[0];
const int nr = ggml_nrows(src0);
// rows per thread
const int dr = (nr + nth - 1)/nth;
// row range for this thread
const int ir0 = dr*ith;
const int ir1 = MIN(ir0 + dr, nr);
for (int i1 = ir0; i1 < ir1; i1++) {
ggml_vec_gelu_f32(nc,
(float *) ((char *) dst->data + i1*( dst->nb[1])),
(float *) ((char *) src0->data + i1*(src0->nb[1])));
#ifndef NDEBUG
for (int k = 0; k < nc; k++) {
const float x = ((float *) ((char *) dst->data + i1*( dst->nb[1])))[k];
UNUSED(x);
assert(!isnan(x));
assert(!isinf(x));
}
#endif
}
}
static void ggml_compute_forward_gelu(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_F32:
{
ggml_compute_forward_gelu_f32(params, src0, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_F16:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
//printf("XXXXXXXX gelu\n");
}
// ggml_compute_forward_silu
static void ggml_compute_forward_silu_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
GGML_ASSERT(ggml_is_contiguous(src0));
GGML_ASSERT(ggml_is_contiguous(dst));
GGML_ASSERT(ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int ith = params->ith;
const int nth = params->nth;
const int nc = src0->ne[0];
const int nr = ggml_nrows(src0);
// rows per thread
const int dr = (nr + nth - 1)/nth;
// row range for this thread
const int ir0 = dr*ith;
const int ir1 = MIN(ir0 + dr, nr);
for (int i1 = ir0; i1 < ir1; i1++) {
ggml_vec_silu_f32(nc,
(float *) ((char *) dst->data + i1*( dst->nb[1])),
(float *) ((char *) src0->data + i1*(src0->nb[1])));
#ifndef NDEBUG
for (int k = 0; k < nc; k++) {
const float x = ((float *) ((char *) dst->data + i1*( dst->nb[1])))[k];
UNUSED(x);
assert(!isnan(x));
assert(!isinf(x));
}
#endif
}
}
static void ggml_compute_forward_silu(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_F32:
{
ggml_compute_forward_silu_f32(params, src0, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_F16:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
// ggml_compute_forward_norm
static void ggml_compute_forward_norm_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
GGML_ASSERT(ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
GGML_ASSERT(src0->nb[0] == sizeof(float));
const int ith = params->ith;
const int nth = params->nth;
const int ne00 = src0->ne[0];
const int ne01 = src0->ne[1];
const int ne02 = src0->ne[2];
const int ne03 = src0->ne[3];
const size_t nb01 = src0->nb[1];
const size_t nb02 = src0->nb[2];
const size_t nb03 = src0->nb[3];
const size_t nb1 = dst->nb[1];
const size_t nb2 = dst->nb[2];
const size_t nb3 = dst->nb[3];
const float eps = 1e-5f; // TODO: make this a parameter
// TODO: optimize
for (int i03 = 0; i03 < ne03; i03++) {
for (int i02 = 0; i02 < ne02; i02++) {
for (int i01 = ith; i01 < ne01; i01 += nth) {
const float * x = (float *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03);
ggml_float sum = 0.0;
for (int i00 = 0; i00 < ne00; i00++) {
sum += (ggml_float)x[i00];
}
float mean = sum/ne00;
float * y = (float *) ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3);
ggml_float sum2 = 0.0;
for (int i00 = 0; i00 < ne00; i00++) {
float v = x[i00] - mean;
y[i00] = v;
sum2 += (ggml_float)(v*v);
}
float variance = sum2/ne00;
const float scale = 1.0f/sqrtf(variance + eps);
ggml_vec_scale_f32(ne00, y, scale);
}
}
}
}
static void ggml_compute_forward_norm(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_F32:
{
ggml_compute_forward_norm_f32(params, src0, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_F16:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
static void ggml_compute_forward_rms_norm_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
GGML_ASSERT(ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
GGML_ASSERT(src0->nb[0] == sizeof(float));
const int ith = params->ith;
const int nth = params->nth;
const int ne00 = src0->ne[0];
const int ne01 = src0->ne[1];
const int ne02 = src0->ne[2];
const int ne03 = src0->ne[3];
const size_t nb01 = src0->nb[1];
const size_t nb02 = src0->nb[2];
const size_t nb03 = src0->nb[3];
const size_t nb1 = dst->nb[1];
const size_t nb2 = dst->nb[2];
const size_t nb3 = dst->nb[3];
const float eps = 1e-6f; // TODO: make this a parameter
// TODO: optimize
for (int i03 = 0; i03 < ne03; i03++) {
for (int i02 = 0; i02 < ne02; i02++) {
for (int i01 = ith; i01 < ne01; i01 += nth) {
const float * x = (float *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03);
ggml_float sum = 0.0;
for (int i00 = 0; i00 < ne00; i00++) {
sum += (ggml_float)(x[i00] * x[i00]);
}
float mean = sum/ne00;
float * y = (float *) ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3);
memcpy(y, x, ne00 * sizeof(float));
// for (int i00 = 0; i00 < ne00; i00++) {
// y[i00] = x[i00];
// }
const float scale = 1.0f/sqrtf(mean + eps);
ggml_vec_scale_f32(ne00, y, scale);
}
}
}
}
static void ggml_compute_forward_rms_norm(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_F32:
{
ggml_compute_forward_rms_norm_f32(params, src0, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_F16:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
// ggml_compute_forward_mul_mat
#if defined(GGML_USE_ACCELERATE) || defined(GGML_USE_OPENBLAS)
// helper function to determine if it is better to use BLAS or not
// for large matrices, BLAS is faster
static bool ggml_compute_forward_mul_mat_use_blas(
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
//const int ne00 = src0->ne[0];
//const int ne01 = src0->ne[1];
const int ne10 = src1->ne[0];
const int ne0 = dst->ne[0];
const int ne1 = dst->ne[1];
// TODO: find the optimal values for these
if (ggml_is_contiguous(src0) &&
ggml_is_contiguous(src1) && ((ne0 >= 32 && ne1 >= 32 && ne10 >= 32))) {
/*printf("BLAS: %d %d %d %d %d\n", ne0, ne1, ne10, ne00, ne01);*/
return true;
}
return false;
}
#endif
static void ggml_compute_forward_mul_mat_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
int64_t t0 = ggml_perf_time_us();
UNUSED(t0);
const int ne00 = src0->ne[0];
const int ne01 = src0->ne[1];
const int ne02 = src0->ne[2];
const int ne03 = src0->ne[3];
#if defined(GGML_USE_ACCELERATE) || defined(GGML_USE_OPENBLAS)
const int ne10 = src1->ne[0];
#endif
const int ne11 = src1->ne[1];
#ifndef NDEBUG
const int ne12 = src1->ne[2];
const int ne13 = src1->ne[3];
const int ne0 = dst->ne[0];
const int ne1 = dst->ne[1];
const int ne2 = dst->ne[2];
const int ne3 = dst->ne[3];
const int nb00 = src0->nb[0];
#endif
const int nb01 = src0->nb[1];
const int nb02 = src0->nb[2];
const int nb03 = src0->nb[3];
#ifndef NDEBUG
const int nb10 = src1->nb[0];
#endif
const int nb11 = src1->nb[1];
const int nb12 = src1->nb[2];
const int nb13 = src1->nb[3];
const int nb0 = dst->nb[0];
const int nb1 = dst->nb[1];
const int nb2 = dst->nb[2];
const int nb3 = dst->nb[3];
const int ith = params->ith;
const int nth = params->nth;
assert(ne02 == ne12);
assert(ne03 == ne13);
assert(ne2 == ne12);
assert(ne3 == ne13);
// we don't support permuted src0 or src1
assert(nb00 == sizeof(float));
assert(nb10 == sizeof(float));
// dst cannot be transposed or permuted
assert(nb0 == sizeof(float));
assert(nb0 <= nb1);
assert(nb1 <= nb2);
assert(nb2 <= nb3);
assert(ne0 == ne01);
assert(ne1 == ne11);
assert(ne2 == ne02);
assert(ne3 == ne03);
// nb01 >= nb00 - src0 is not transposed
// compute by src0 rows
#if defined(GGML_USE_ACCELERATE) || defined(GGML_USE_OPENBLAS)
if (ggml_compute_forward_mul_mat_use_blas(src0, src1, dst)) {
if (params->ith != 0) {
return;
}
if (params->type == GGML_TASK_INIT) {
return;
}
if (params->type == GGML_TASK_FINALIZE) {
return;
}
for (int i03 = 0; i03 < ne03; i03++) {
for (int i02 = 0; i02 < ne02; i02++) {
const float * x = (float *) ((char *) src0->data + i02*nb02 + i03*nb03);
const float * y = (float *) ((char *) src1->data + i02*nb12 + i03*nb13);
float * d = (float *) ((char *) dst->data + i02*nb2 + i03*nb3);
// zT = y * xT
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans,
ne11, ne01, ne10,
1.0f, y, ne10,
x, ne10,
0.0f, d, ne01);
}
}
//printf("CBLAS F32 = %f ms, %d x %d x %d x %d\n", (ggml_perf_time_us() - t0)/1000.0, ne0, ne1, ne2, ne3);
return;
}
#endif
if (params->type == GGML_TASK_INIT) {
return;
}
if (params->type == GGML_TASK_FINALIZE) {
return;
}
// parallelize by src0 rows using ggml_vec_dot_f32
// total rows in src0
const int nr = ne01*ne02*ne03;
// rows per thread
const int dr = (nr + nth - 1)/nth;
// row range for this thread
const int ir0 = dr*ith;
const int ir1 = MIN(ir0 + dr, nr);
for (int ir = ir0; ir < ir1; ++ir) {
// src0 indices
const int i03 = ir/(ne02*ne01);
const int i02 = (ir - i03*ne02*ne01)/ne01;
const int i01 = (ir - i03*ne02*ne01 - i02*ne01);
for (int ic = 0; ic < ne11; ++ic) {
// src1 indices
const int i13 = i03;
const int i12 = i02;
const int i11 = ic;
// dst indices
const int i0 = i01;
const int i1 = i11;
const int i2 = i02;
const int i3 = i03;
ggml_vec_dot_f32(ne00,
(float *) ((char *) dst->data + (i0*nb0 + i1*nb1 + i2*nb2 + i3*nb3)),
(float *) ((char *) src0->data + (i01*nb01 + i02*nb02 + i03*nb03)),
(float *) ((char *) src1->data + (i11*nb11 + i12*nb12 + i13*nb13)));
}
}
//int64_t t1 = ggml_perf_time_us();
//static int64_t acc = 0;
//acc += t1 - t0;
//if (t1 - t0 > 10) {
// printf("\n");
// printf("ne00 = %5d, ne01 = %5d, ne02 = %5d, ne03 = %5d\n", ne00, ne01, ne02, ne03);
// printf("nb00 = %5d, nb01 = %5d, nb02 = %5d, nb03 = %5d\n", nb00, nb01, nb02, nb03);
// printf("ne10 = %5d, ne11 = %5d, ne12 = %5d, ne13 = %5d\n", ne10, ne11, ne12, ne13);
// printf("nb10 = %5d, nb11 = %5d, nb12 = %5d, nb13 = %5d\n", nb10, nb11, nb12, nb13);
// printf("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX task %d/%d: %d us, acc = %d\n", ith, nth, (int) (t1 - t0), (int) acc);
//}
}
static void ggml_compute_forward_mul_mat_f16_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
int64_t t0 = ggml_perf_time_us();
UNUSED(t0);
const int ne00 = src0->ne[0];
const int ne01 = src0->ne[1];
const int ne02 = src0->ne[2];
const int ne03 = src0->ne[3];
const int ne10 = src1->ne[0];
const int ne11 = src1->ne[1];
const int ne12 = src1->ne[2];
const int ne13 = src1->ne[3];
const int ne0 = dst->ne[0];
const int ne1 = dst->ne[1];
const int ne2 = dst->ne[2];
const int ne3 = dst->ne[3];
//const int ne = ne0*ne1*ne2*ne3;
const int nb00 = src0->nb[0];
const int nb01 = src0->nb[1];
const int nb02 = src0->nb[2];
const int nb03 = src0->nb[3];
const int nb10 = src1->nb[0];
const int nb11 = src1->nb[1];
const int nb12 = src1->nb[2];
const int nb13 = src1->nb[3];
const int nb0 = dst->nb[0];
const int nb1 = dst->nb[1];
const int nb2 = dst->nb[2];
const int nb3 = dst->nb[3];
const int ith = params->ith;
const int nth = params->nth;
GGML_ASSERT(ne02 == ne12);
GGML_ASSERT(ne03 == ne13);
GGML_ASSERT(ne2 == ne12);
GGML_ASSERT(ne3 == ne13);
// TODO: we don't support permuted src0
GGML_ASSERT(nb00 == sizeof(ggml_fp16_t));
// dst cannot be transposed or permuted
GGML_ASSERT(nb0 == sizeof(float));
GGML_ASSERT(nb0 <= nb1);
GGML_ASSERT(nb1 <= nb2);
GGML_ASSERT(nb2 <= nb3);
GGML_ASSERT(ne0 == ne01);
GGML_ASSERT(ne1 == ne11);
GGML_ASSERT(ne2 == ne02);
GGML_ASSERT(ne3 == ne03);
// nb01 >= nb00 - src0 is not transposed
// compute by src0 rows
#if defined(GGML_USE_ACCELERATE) || defined(GGML_USE_OPENBLAS)
if (ggml_compute_forward_mul_mat_use_blas(src0, src1, dst)) {
GGML_ASSERT(nb10 == sizeof(float));
if (params->ith != 0) {
return;
}
if (params->type == GGML_TASK_INIT) {
return;
}
if (params->type == GGML_TASK_FINALIZE) {
return;
}
float * const wdata = params->wdata;
for (int i03 = 0; i03 < ne03; i03++) {
for (int i02 = 0; i02 < ne02; i02++) {
{
size_t id = 0;
for (int i01 = 0; i01 < ne01; ++i01) {
for (int i00 = 0; i00 < ne00; ++i00) {
wdata[id++] = GGML_FP16_TO_FP32(*(ggml_fp16_t *) ((char *) src0->data + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00));
}
}
}
const float * x = wdata;
const float * y = (float *) ((char *) src1->data + i02*nb12 + i03*nb13);
float * d = (float *) ((char *) dst->data + i02*nb2 + i03*nb3);
// zT = y * xT
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans,
ne11, ne01, ne10,
1.0f, y, ne10,
x, ne10,
0.0f, d, ne01);
}
}
/*printf("CBLAS F16 = %f ms, %d x %d x %d x %d\n", (ggml_perf_time_us() - t0)/1000.0, ne0, ne1, ne2, ne3);*/
return;
}
#endif
if (params->type == GGML_TASK_INIT) {
ggml_fp16_t * const wdata = params->wdata;
size_t id = 0;
for (int i13 = 0; i13 < ne13; ++i13) {
for (int i12 = 0; i12 < ne12; ++i12) {
for (int i11 = 0; i11 < ne11; ++i11) {
for (int i10 = 0; i10 < ne10; ++i10) {
wdata[id++] = GGML_FP32_TO_FP16(*(float *)((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + i10*nb10));
}
}
}
}
GGML_ASSERT(id*sizeof(ggml_fp16_t) <= params->wsize);
return;
}
if (params->type == GGML_TASK_FINALIZE) {
return;
}
// fp16 -> half the size, so divide by 2
// TODO: do not support transposed src1
assert(nb10/2 == sizeof(ggml_fp16_t));
// parallelize by src0 rows using ggml_vec_dot_f16
// total rows in src0
const int nr = ne01*ne02*ne03;
// rows per thread
const int dr = (nr + nth - 1)/nth;
// row range for this thread
const int ir0 = dr*ith;
const int ir1 = MIN(ir0 + dr, nr);
ggml_fp16_t * wdata = params->wdata;
for (int ir = ir0; ir < ir1; ++ir) {
// src0 indices
const int i03 = ir/(ne02*ne01);
const int i02 = (ir - i03*ne02*ne01)/ne01;
const int i01 = (ir - i03*ne02*ne01 - i02*ne01);
const int i13 = i03;
const int i12 = i02;
const int i0 = i01;
const int i2 = i02;
const int i3 = i03;
ggml_fp16_t * src0_row = (ggml_fp16_t *) ((char *) src0->data + (i01*nb01 + i02*nb02 + i03*nb03));
ggml_fp16_t * src1_col = wdata + ( 0 + i12*ne11 + i13*ne12*ne11)*ne00;
float * dst_col = (float *) ((char *) dst->data + (i0*nb0 + 0*nb1 + i2*nb2 + i3*nb3));
for (int ic = 0; ic < ne11; ++ic) {
ggml_vec_dot_f16(ne00, &dst_col[ic*ne0], src0_row, src1_col + ic*ne00);
}
}
//int64_t t1 = ggml_time_us();
//static int64_t acc = 0;
//acc += t1 - t0;
//if (t1 - t0 > 10) {
// printf("\n");
// printf("ne00 = %5d, ne01 = %5d, ne02 = %5d, ne03 = %5d\n", ne00, ne01, ne02, ne03);
// printf("nb00 = %5d, nb01 = %5d, nb02 = %5d, nb03 = %5d\n", nb00, nb01, nb02, nb03);
// printf("ne10 = %5d, ne11 = %5d, ne12 = %5d, ne13 = %5d\n", ne10, ne11, ne12, ne13);
// printf("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX task %d/%d: %d us, acc = %d\n", ith, nth, (int) (t1 - t0), (int) acc);
//}
}
typedef void (*dequantize_row_q_t)(const void * restrict x, float * restrict y, int k);
typedef void (*quantize_row_q_t)(const float * restrict x, void * restrict y, int k);
typedef void (*vec_dot_q_t)(const int n, float * restrict s, const void * restrict x, const void * restrict y);
typedef struct {
dequantize_row_q_t dequantize_row_q;
quantize_row_q_t quantize_row_q;
vec_dot_q_t vec_dot_q;
} quantize_fns_t;
static const quantize_fns_t quantize_fns[GGML_TYPE_COUNT] = {
[GGML_TYPE_Q4_0] = {
.dequantize_row_q = dequantize_row_q4_0,
.quantize_row_q = quantize_row_q4_0,
.vec_dot_q = ggml_vec_dot_q4_0,
},
[GGML_TYPE_Q4_1] = {
.dequantize_row_q = dequantize_row_q4_1,
.quantize_row_q = quantize_row_q4_1,
.vec_dot_q = ggml_vec_dot_q4_1,
},
};
static void ggml_compute_forward_mul_mat_q_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
int64_t t0 = ggml_perf_time_us();
UNUSED(t0);
const int ne00 = src0->ne[0];
const int ne01 = src0->ne[1];
const int ne02 = src0->ne[2];
const int ne03 = src0->ne[3];
const int ne10 = src1->ne[0];
const int ne11 = src1->ne[1];
const int ne12 = src1->ne[2];
const int ne13 = src1->ne[3];
const int ne0 = dst->ne[0];
const int ne1 = dst->ne[1];
const int ne2 = dst->ne[2];
const int ne3 = dst->ne[3];
const int nb00 = src0->nb[0];
const int nb01 = src0->nb[1];
const int nb02 = src0->nb[2];
const int nb03 = src0->nb[3];
const int nb10 = src1->nb[0];
const int nb11 = src1->nb[1];
const int nb12 = src1->nb[2];
const int nb13 = src1->nb[3];
const int nb0 = dst->nb[0];
const int nb1 = dst->nb[1];
const int nb2 = dst->nb[2];
const int nb3 = dst->nb[3];
const int ith = params->ith;
const int nth = params->nth;
GGML_ASSERT(ne02 == ne12);
GGML_ASSERT(ne03 == ne13);
GGML_ASSERT(ne2 == ne12);
GGML_ASSERT(ne3 == ne13);
const enum ggml_type type = src0->type;
quantize_row_q_t const quantize_row_q = quantize_fns[type].quantize_row_q;
vec_dot_q_t const vec_dot_q = quantize_fns[type].vec_dot_q;
// we don't support permuted src0 or src1
GGML_ASSERT(nb00 == (int) GGML_TYPE_SIZE[type]);
GGML_ASSERT(nb10 == sizeof(float));
// dst cannot be transposed or permuted
GGML_ASSERT(nb0 == sizeof(float));
GGML_ASSERT(nb0 <= nb1);
GGML_ASSERT(nb1 <= nb2);
GGML_ASSERT(nb2 <= nb3);
GGML_ASSERT(ne0 == ne01);
GGML_ASSERT(ne1 == ne11);
GGML_ASSERT(ne2 == ne02);
GGML_ASSERT(ne3 == ne03);
// nb01 >= nb00 - src0 is not transposed
// compute by src0 rows
#if defined(GGML_USE_ACCELERATE) || defined(GGML_USE_OPENBLAS)
if (ggml_compute_forward_mul_mat_use_blas(src0, src1, dst)) {
if (params->ith != 0) {
return;
}
if (params->type == GGML_TASK_INIT) {
return;
}
if (params->type == GGML_TASK_FINALIZE) {
return;
}
float * const wdata = params->wdata;
dequantize_row_q_t const dequantize_row_q = quantize_fns[type].dequantize_row_q;
for (int i03 = 0; i03 < ne03; i03++) {
for (int i02 = 0; i02 < ne02; i02++) {
{
size_t id = 0;
for (int i01 = 0; i01 < ne01; ++i01) {
dequantize_row_q((char *) src0->data + i03*nb03 + i02*nb02 + i01*nb01, wdata + id, ne00);
id += ne00;
}
}
const float * x = wdata;
const float * y = (float *) ((char *) src1->data + i02*nb12 + i03*nb13);
float * d = (float *) ((char *) dst->data + i02*nb2 + i03*nb3);
// zT = y * xT
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans,
ne11, ne01, ne10,
1.0f, y, ne10,
x, ne10,
0.0f, d, ne01);
}
}
//printf("CBLAS = %f ms, %d x %d x %d x %d\n", (ggml_perf_time_us() - t0)/1000.0, ne0, ne1, ne2, ne3);
return;
}
#endif
if (params->type == GGML_TASK_INIT) {
char * wdata = params->wdata;
const size_t row_size = ne10*GGML_TYPE_SIZE[type]/GGML_BLCK_SIZE[type];
for (int i13 = 0; i13 < ne13; ++i13) {
for (int i12 = 0; i12 < ne12; ++i12) {
for (int i11 = 0; i11 < ne11; ++i11) {
quantize_row_q((float *)((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11), (void *) wdata, ne10);
wdata += row_size;
}
}
}
return;
}
if (params->type == GGML_TASK_FINALIZE) {
return;
}
// parallelize by src0 rows using ggml_vec_dot_q
// total rows in src0
const int nr = ne01*ne02*ne03;
// rows per thread
const int dr = (nr + nth - 1)/nth;
// row range for this thread
const int ir0 = dr*ith;
const int ir1 = MIN(ir0 + dr, nr);
void * wdata = params->wdata;
const size_t row_size = ne00*GGML_TYPE_SIZE[type]/GGML_BLCK_SIZE[type];
for (int ir = ir0; ir < ir1; ++ir) {
// src0 indices
const int i03 = ir/(ne02*ne01);
const int i02 = (ir - i03*ne02*ne01)/ne01;
const int i01 = (ir - i03*ne02*ne01 - i02*ne01);
const int i13 = i03;
const int i12 = i02;
const int i0 = i01;
const int i2 = i02;
const int i3 = i03;
void * src0_row = (void *) ((char *) src0->data + (i01*nb01 + i02*nb02 + i03*nb03));
char * src1_col = ((char *) wdata + ( (0 + i12*ne11 + i13*ne12*ne11)*row_size));
float * dst_col = (float *) ((char *) dst->data + (i0*nb0 + 0*nb1 + i2*nb2 + i3*nb3));
assert(ne00 % 32 == 0);
for (int ic = 0; ic < ne11; ++ic) {
vec_dot_q(ne00, &dst_col[ic*ne0], src0_row, (void *) (src1_col + ic*row_size));
}
}
//int64_t t1 = ggml_time_us();
//static int64_t acc = 0;
//acc += t1 - t0;
//if (t1 - t0 > 10) {
// printf("\n");
// printf("ne00 = %5d, ne01 = %5d, ne02 = %5d, ne03 = %5d\n", ne00, ne01, ne02, ne03);
// printf("nb00 = %5d, nb01 = %5d, nb02 = %5d, nb03 = %5d\n", nb00, nb01, nb02, nb03);
// printf("ne10 = %5d, ne11 = %5d, ne12 = %5d, ne13 = %5d\n", ne10, ne11, ne12, ne13);
// printf("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX task %d/%d: %d us, acc = %d\n", ith, nth, (int) (t1 - t0), (int) acc);
//}
}
static void ggml_compute_forward_mul_mat(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
{
ggml_compute_forward_mul_mat_q_f32(params, src0, src1, dst);
} break;
case GGML_TYPE_F16:
{
ggml_compute_forward_mul_mat_f16_f32(params, src0, src1, dst);
} break;
case GGML_TYPE_F32:
{
ggml_compute_forward_mul_mat_f32(params, src0, src1, dst);
} break;
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
#if 0
if (src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_Q4_1) {
static int first = 8;
printf("src0: ne0 = %5d, ne1 = %5d, ne2 = %5d\n", src0->ne[0], src0->ne[1], src0->ne[2]);
printf("src1: ne0 = %5d, ne1 = %5d, ne2 = %5d\n", src1->ne[0], src1->ne[1], src1->ne[2]);
printf("dst: ne0 = %5d, ne1 = %5d, ne2 = %5d\n", dst->ne[0], dst->ne[1], dst->ne[2]);
if (first) {
--first;
} else {
for (int k = 0; k < dst->ne[1]; ++k) {
for (int j = 0; j < dst->ne[0]/16; ++j) {
for (int i = 0; i < 16; ++i) {
printf("%8.4f ", ((float *) dst->data)[k*dst->ne[0] + j*16 + i]);
}
printf("\n");
}
printf("\n");
}
printf("\n");
exit(0);
}
} else {
printf("aaaa src0: ne0 = %5d, ne1 = %5d, ne2 = %5d\n", src0->ne[0], src0->ne[1], src0->ne[2]);
printf("aaaa src1: ne0 = %5d, ne1 = %5d, ne2 = %5d\n", src1->ne[0], src1->ne[1], src1->ne[2]);
printf("aaaa dst: ne0 = %5d, ne1 = %5d, ne2 = %5d\n", dst->ne[0], dst->ne[1], dst->ne[2]);
}
#endif
}
// ggml_compute_forward_scale
static void ggml_compute_forward_scale_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
GGML_ASSERT(ggml_is_contiguous(src0));
GGML_ASSERT(ggml_is_contiguous(dst));
GGML_ASSERT(ggml_are_same_shape(src0, dst));
GGML_ASSERT(ggml_is_scalar(src1));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
// scale factor
const float v = *(float *) src1->data;
const int ith = params->ith;
const int nth = params->nth;
const int nc = src0->ne[0];
const int nr = ggml_nrows(src0);
// rows per thread
const int dr = (nr + nth - 1)/nth;
// row range for this thread
const int ir0 = dr*ith;
const int ir1 = MIN(ir0 + dr, nr);
for (int i1 = ir0; i1 < ir1; i1++) {
ggml_vec_scale_f32(nc, (float *) ((char *) dst->data + i1*(dst->nb[1])), v);
}
}
static void ggml_compute_forward_scale(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_F32:
{
ggml_compute_forward_scale_f32(params, src0, src1, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_F16:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
// ggml_compute_forward_cpy
static void ggml_compute_forward_cpy(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
ggml_compute_forward_dup(params, src0, dst);
}
// ggml_compute_forward_reshape
static void ggml_compute_forward_reshape(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
// NOP
UNUSED(params);
UNUSED(src0);
UNUSED(dst);
}
// ggml_compute_forward_view
static void ggml_compute_forward_view(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0) {
// NOP
UNUSED(params);
UNUSED(src0);
}
// ggml_compute_forward_permute
static void ggml_compute_forward_permute(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0) {
// NOP
UNUSED(params);
UNUSED(src0);
}
// ggml_compute_forward_transpose
static void ggml_compute_forward_transpose(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0) {
// NOP
UNUSED(params);
UNUSED(src0);
}
// ggml_compute_forward_get_rows
static void ggml_compute_forward_get_rows_q(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
assert(params->ith == 0);
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int nc = src0->ne[0];
const int nr = ggml_nelements(src1);
const enum ggml_type type = src0->type;
dequantize_row_q_t const dequantize_row_q = quantize_fns[type].dequantize_row_q;
assert( dst->ne[0] == nc);
assert( dst->ne[1] == nr);
assert(src0->nb[0] == GGML_TYPE_SIZE[type]);
for (int i = 0; i < nr; ++i) {
const int r = ((int32_t *) src1->data)[i];
dequantize_row_q(
(const void *) ((char *) src0->data + r*src0->nb[1]),
(float *) ((char *) dst->data + i*dst->nb[1]), nc);
}
}
static void ggml_compute_forward_get_rows_f16(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
assert(params->ith == 0);
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int nc = src0->ne[0];
const int nr = ggml_nelements(src1);
assert( dst->ne[0] == nc);
assert( dst->ne[1] == nr);
assert(src0->nb[0] == sizeof(ggml_fp16_t));
for (int i = 0; i < nr; ++i) {
const int r = ((int32_t *) src1->data)[i];
for (int j = 0; j < nc; ++j) {
ggml_fp16_t v = ((ggml_fp16_t *) ((char *) src0->data + r*src0->nb[1]))[j];
((float *) ((char *) dst->data + i*dst->nb[1]))[j] = GGML_FP16_TO_FP32(v);
}
}
}
static void ggml_compute_forward_get_rows_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
assert(params->ith == 0);
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int nc = src0->ne[0];
const int nr = ggml_nelements(src1);
assert( dst->ne[0] == nc);
assert( dst->ne[1] == nr);
assert(src0->nb[0] == sizeof(float));
for (int i = 0; i < nr; ++i) {
const int r = ((int32_t *) src1->data)[i];
ggml_vec_cpy_f32(nc,
(float *) ((char *) dst->data + i*dst->nb[1]),
(float *) ((char *) src0->data + r*src0->nb[1]));
}
}
static void ggml_compute_forward_get_rows(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
{
ggml_compute_forward_get_rows_q(params, src0, src1, dst);
} break;
case GGML_TYPE_F16:
{
ggml_compute_forward_get_rows_f16(params, src0, src1, dst);
} break;
case GGML_TYPE_F32:
{
ggml_compute_forward_get_rows_f32(params, src0, src1, dst);
} break;
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
//static bool first = true;
//printf("ne0 = %d, ne1 = %d, ne2 = %d\n", dst->ne[0], dst->ne[1], dst->ne[2]);
//if (first) {
// first = false;
//} else {
// for (int k = 0; k < dst->ne[1]; ++k) {
// for (int j = 0; j < dst->ne[0]/16; ++j) {
// for (int i = 0; i < 16; ++i) {
// printf("%8.4f ", ((float *) dst->data)[k*dst->ne[0] + j*16 + i]);
// }
// printf("\n");
// }
// printf("\n");
// }
// printf("\n");
// exit(0);
//}
}
// ggml_compute_forward_diag_mask_inf
static void ggml_compute_forward_diag_mask_inf_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(src1->type == GGML_TYPE_I32);
assert(ggml_nelements(src1) == 1);
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int n_past = ((int32_t *) src1->data)[0];
// TODO: handle transposed/permuted matrices
const int n = ggml_nrows(src0);
const int nc = src0->ne[0];
const int nr = src0->ne[1];
const int nz = n/nr;
assert( dst->nb[0] == sizeof(float));
assert(src0->nb[0] == sizeof(float));
for (int k = 0; k < nz; k++) {
for (int j = 0; j < nr; j++) {
for (int i = n_past; i < nc; i++) {
if (i > n_past + j) {
*(float *)((char *) dst->data + k*dst->nb[2] + j*dst->nb[1] + i*dst->nb[0]) = -INFINITY;
}
}
}
}
}
static void ggml_compute_forward_diag_mask_inf(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_F32:
{
ggml_compute_forward_diag_mask_inf_f32(params, src0, src1, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_F16:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
// ggml_compute_forward_soft_max
static void ggml_compute_forward_soft_max_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
GGML_ASSERT(ggml_is_contiguous(src0));
GGML_ASSERT(ggml_is_contiguous(dst));
GGML_ASSERT(ggml_are_same_shape(src0, dst));
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
// TODO: handle transposed/permuted matrices
const int ith = params->ith;
const int nth = params->nth;
const int nc = src0->ne[0];
const int nr = ggml_nrows(src0);
// rows per thread
const int dr = (nr + nth - 1)/nth;
// row range for this thread
const int ir0 = dr*ith;
const int ir1 = MIN(ir0 + dr, nr);
for (int i1 = ir0; i1 < ir1; i1++) {
float *p = (float *)((char *) dst->data + i1*dst->nb[1]);
#ifndef NDEBUG
for (int i = 0; i < nc; ++i) {
//printf("p[%d] = %f\n", i, p[i]);
assert(!isnan(p[i]));
}
#endif
float max = -INFINITY;
ggml_vec_max_f32(nc, &max, p);
ggml_float sum = 0.0;
uint16_t scvt;
for (int i = 0; i < nc; i++) {
if (p[i] == -INFINITY) {
p[i] = 0.0f;
} else {
//const float val = (p[i] == -INFINITY) ? 0.0 : exp(p[i] - max);
ggml_fp16_t s = GGML_FP32_TO_FP16(p[i] - max);
memcpy(&scvt, &s, sizeof(scvt));
const float val = GGML_FP16_TO_FP32(table_exp_f16[scvt]);
sum += (ggml_float)val;
p[i] = val;
}
}
assert(sum > 0.0);
sum = 1.0/sum;
ggml_vec_scale_f32(nc, p, sum);
#ifndef NDEBUG
for (int i = 0; i < nc; ++i) {
assert(!isnan(p[i]));
assert(!isinf(p[i]));
}
#endif
}
}
static void ggml_compute_forward_soft_max(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_F32:
{
ggml_compute_forward_soft_max_f32(params, src0, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_F16:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
// ggml_compute_forward_rope
static void ggml_compute_forward_rope_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(src1->type == GGML_TYPE_I32);
assert(ggml_nelements(src1) == 3);
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int n_past = ((int32_t *) src1->data)[0];
const int n_dims = ((int32_t *) src1->data)[1];
const int mode = ((int32_t *) src1->data)[2];
//const int ne0 = src0->ne[0];
const int ne1 = src0->ne[1];
const int ne2 = src0->ne[2];
const int ne3 = src0->ne[3];
const int nb0 = src0->nb[0];
const int nb1 = src0->nb[1];
const int nb2 = src0->nb[2];
const int nb3 = src0->nb[3];
//printf("ne0: %d, ne1: %d, ne2: %d, ne3: %d\n", ne0, ne1, ne2, ne3);
//printf("n_past = %d, ne2 = %d\n", n_past, ne2);
assert(nb0 == sizeof(float));
// TODO: optimize
for (int i3 = 0; i3 < ne3; i3++) {
for (int i2 = (mode == 0 ? 0 : n_past); i2 < ne2; i2++) {
const int p = (mode == 0 ? n_past + i2 : i2);
for (int i1 = 0; i1 < ne1; i1++) {
for (int i0 = 0; i0 < n_dims; i0 += 2) {
const float theta = powf(10000.0, ((float)-i0)/n_dims);
const float cos_theta = cosf(p*theta);
const float sin_theta = sinf(p*theta);
const float * const src = (float *)((char *) src0->data + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
float * dst_data = (float *)((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
const float x0 = src[0];
const float x1 = src[1];
dst_data[0] = x0*cos_theta - x1*sin_theta;
dst_data[1] = x0*sin_theta + x1*cos_theta;
}
}
}
}
}
static void ggml_compute_forward_rope_f16(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
assert(params->ith == 0);
assert(src1->type == GGML_TYPE_I32);
assert(ggml_nelements(src1) == 3);
if (params->type == GGML_TASK_INIT || params->type == GGML_TASK_FINALIZE) {
return;
}
const int n_past = ((int32_t *) src1->data)[0];
const int n_dims = ((int32_t *) src1->data)[1];
const int mode = ((int32_t *) src1->data)[2];
//const int ne0 = src0->ne[0];
const int ne1 = src0->ne[1];
const int ne2 = src0->ne[2];
const int ne3 = src0->ne[3];
const int nb0 = src0->nb[0];
const int nb1 = src0->nb[1];
const int nb2 = src0->nb[2];
const int nb3 = src0->nb[3];
//printf("ne0: %d, ne1: %d, ne2: %d, ne3: %d\n", ne0, ne1, ne2, ne3);
//printf("n_past = %d, ne2 = %d\n", n_past, ne2);
assert(nb0 == sizeof(ggml_fp16_t));
for (int i3 = 0; i3 < ne3; i3++) {
for (int i2 = (mode == 0 ? 0 : n_past); i2 < ne2; i2++) {
const int p = (mode == 0 ? n_past + i2 : i2);
for (int i1 = 0; i1 < ne1; i1++) {
for (int i0 = 0; i0 < n_dims; i0 += 2) {
const float theta = powf(10000.0, ((float)-i0)/n_dims);
const float cos_theta = cosf(p*theta);
const float sin_theta = sinf(p*theta);
const ggml_fp16_t * const src = (ggml_fp16_t *)((char *) src0->data + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
ggml_fp16_t * dst_data = (ggml_fp16_t *)((char *) dst->data + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
const float x0 = ggml_fp16_to_fp32(src[0]);
const float x1 = ggml_fp16_to_fp32(src[1]);
dst_data[0] = ggml_fp32_to_fp16(x0*cos_theta - x1*sin_theta);
dst_data[1] = ggml_fp32_to_fp16(x0*sin_theta + x1*cos_theta);
}
}
}
}
}
static void ggml_compute_forward_rope(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_F16:
{
ggml_compute_forward_rope_f16(params, src0, src1, dst);
} break;
case GGML_TYPE_F32:
{
ggml_compute_forward_rope_f32(params, src0, src1, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
// ggml_compute_forward_conv_1d_1s
static void ggml_compute_forward_conv_1d_1s_f16_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
GGML_ASSERT(src0->type == GGML_TYPE_F16);
GGML_ASSERT(src1->type == GGML_TYPE_F32);
GGML_ASSERT( dst->type == GGML_TYPE_F32);
int64_t t0 = ggml_perf_time_us();
UNUSED(t0);
const int ne00 = src0->ne[0];
const int ne01 = src0->ne[1];
const int ne02 = src0->ne[2];
//const int ne03 = src0->ne[3];
const int ne10 = src1->ne[0];
const int ne11 = src1->ne[1];
//const int ne12 = src1->ne[2];
//const int ne13 = src1->ne[3];
//const int ne0 = dst->ne[0];
//const int ne1 = dst->ne[1];
//const int ne2 = dst->ne[2];
//const int ne3 = dst->ne[3];
//const int ne = ne0*ne1*ne2*ne3;
const int nb00 = src0->nb[0];
const int nb01 = src0->nb[1];
const int nb02 = src0->nb[2];
//const int nb03 = src0->nb[3];
const int nb10 = src1->nb[0];
const int nb11 = src1->nb[1];
//const int nb12 = src1->nb[2];
//const int nb13 = src1->nb[3];
//const int nb0 = dst->nb[0];
const int nb1 = dst->nb[1];
//const int nb2 = dst->nb[2];
//const int nb3 = dst->nb[3];
const int ith = params->ith;
const int nth = params->nth;
const int nk = ne00;
const int nh = nk/2;
const int ew0 = ggml_up32(ne01);
GGML_ASSERT(ne00 % 2 == 1); // TODO: support even kernel sizes
GGML_ASSERT(nb00 == sizeof(ggml_fp16_t));
GGML_ASSERT(nb10 == sizeof(float));
if (params->type == GGML_TASK_INIT) {
// TODO: fix this memset (wsize is overestimated)
memset(params->wdata, 0, params->wsize);
// prepare kernel data (src0)
{
ggml_fp16_t * const wdata = (ggml_fp16_t *) params->wdata + 0;
for (int i02 = 0; i02 < ne02; i02++) {
for (int i01 = 0; i01 < ne01; i01++) {
const ggml_fp16_t * const src = (ggml_fp16_t *)((char *) src0->data + i02*nb02 + i01*nb01);
ggml_fp16_t * dst_data = wdata + i02*ew0*ne00;
for (int i00 = 0; i00 < ne00; i00++) {
dst_data[i00*ew0 + i01] = src[i00];
}
}
}
}
// prepare source data (src1)
{
ggml_fp16_t * const wdata = (ggml_fp16_t *) params->wdata + ne02*ew0*ne00;
for (int i11 = 0; i11 < ne11; i11++) {
const float * const src = (float *)((char *) src1->data + i11*nb11);
ggml_fp16_t * dst_data = wdata;
for (int i10 = 0; i10 < ne10; i10++) {
dst_data[(i10 + nh)*ew0 + i11] = GGML_FP32_TO_FP16(src[i10]);
}
}
}
return;
}
if (params->type == GGML_TASK_FINALIZE) {
return;
}
// total rows in dst
const int nr = ne02;
// rows per thread
const int dr = (nr + nth - 1)/nth;
// row range for this thread
const int ir0 = dr*ith;
const int ir1 = MIN(ir0 + dr, nr);
for (int i1 = ir0; i1 < ir1; i1++) {
float * dst_data = (float *)((char *) dst->data + i1*nb1);
for (int i0 = 0; i0 < ne10; ++i0) {
dst_data[i0] = 0;
for (int k = -nh; k <= nh; k++) {
float v = 0.0f;
ggml_vec_dot_f16(ew0, &v,
(ggml_fp16_t *) params->wdata + i1*ew0*ne00 + (nh + k)*ew0,
(ggml_fp16_t *) params->wdata + ne02*ew0*ne00 + (i0 + nh + k)*ew0);
dst_data[i0] += v;
}
}
}
}
static void ggml_compute_forward_conv_1d_1s_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
GGML_ASSERT(src0->type == GGML_TYPE_F32);
GGML_ASSERT(src1->type == GGML_TYPE_F32);
GGML_ASSERT( dst->type == GGML_TYPE_F32);
int64_t t0 = ggml_perf_time_us();
UNUSED(t0);
const int ne00 = src0->ne[0];
const int ne01 = src0->ne[1];
const int ne02 = src0->ne[2];
//const int ne03 = src0->ne[3];
const int ne10 = src1->ne[0];
const int ne11 = src1->ne[1];
//const int ne12 = src1->ne[2];
//const int ne13 = src1->ne[3];
//const int ne0 = dst->ne[0];
//const int ne1 = dst->ne[1];
//const int ne2 = dst->ne[2];
//const int ne3 = dst->ne[3];
//const int ne = ne0*ne1*ne2*ne3;
const int nb00 = src0->nb[0];
const int nb01 = src0->nb[1];
const int nb02 = src0->nb[2];
//const int nb03 = src0->nb[3];
const int nb10 = src1->nb[0];
const int nb11 = src1->nb[1];
//const int nb12 = src1->nb[2];
//const int nb13 = src1->nb[3];
//const int nb0 = dst->nb[0];
const int nb1 = dst->nb[1];
//const int nb2 = dst->nb[2];
//const int nb3 = dst->nb[3];
const int ith = params->ith;
const int nth = params->nth;
const int nk = ne00;
const int nh = nk/2;
const int ew0 = ggml_up32(ne01);
GGML_ASSERT(ne00 % 2 == 1); // TODO: support even kernel sizes
GGML_ASSERT(nb00 == sizeof(float));
GGML_ASSERT(nb10 == sizeof(float));
if (params->type == GGML_TASK_INIT) {
// TODO: fix this memset (wsize is overestimated)
memset(params->wdata, 0, params->wsize);
// prepare kernel data (src0)
{
float * const wdata = (float *) params->wdata + 0;
for (int i02 = 0; i02 < ne02; i02++) {
for (int i01 = 0; i01 < ne01; i01++) {
const float * const src = (float *)((char *) src0->data + i02*nb02 + i01*nb01);
float * dst_data = wdata + i02*ew0*ne00;
for (int i00 = 0; i00 < ne00; i00++) {
dst_data[i00*ew0 + i01] = src[i00];
}
}
}
}
// prepare source data (src1)
{
float * const wdata = (float *) params->wdata + ne02*ew0*ne00;
for (int i11 = 0; i11 < ne11; i11++) {
const float * const src = (float *)((char *) src1->data + i11*nb11);
float * dst_data = wdata;
for (int i10 = 0; i10 < ne10; i10++) {
dst_data[(i10 + nh)*ew0 + i11] = src[i10];
}
}
}
return;
}
if (params->type == GGML_TASK_FINALIZE) {
return;
}
// total rows in dst
const int nr = ne02;
// rows per thread
const int dr = (nr + nth - 1)/nth;
// row range for this thread
const int ir0 = dr*ith;
const int ir1 = MIN(ir0 + dr, nr);
for (int i1 = ir0; i1 < ir1; i1++) {
float * dst_data = (float *)((char *) dst->data + i1*nb1);
for (int i0 = 0; i0 < ne10; ++i0) {
dst_data[i0] = 0;
for (int k = -nh; k <= nh; k++) {
float v = 0.0f;
ggml_vec_dot_f32(ew0, &v,
(float *) params->wdata + i1*ew0*ne00 + (nh + k)*ew0,
(float *) params->wdata + ne02*ew0*ne00 + (i0 + nh + k)*ew0);
dst_data[i0] += v;
}
}
}
}
static void ggml_compute_forward_conv_1d_1s(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_F16:
{
ggml_compute_forward_conv_1d_1s_f16_f32(params, src0, src1, dst);
} break;
case GGML_TYPE_F32:
{
ggml_compute_forward_conv_1d_1s_f32(params, src0, src1, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
// ggml_compute_forward_conv_1d_2s
static void ggml_compute_forward_conv_1d_2s_f16_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
GGML_ASSERT(src0->type == GGML_TYPE_F16);
GGML_ASSERT(src1->type == GGML_TYPE_F32);
GGML_ASSERT( dst->type == GGML_TYPE_F32);
int64_t t0 = ggml_perf_time_us();
UNUSED(t0);
const int ne00 = src0->ne[0];
const int ne01 = src0->ne[1];
const int ne02 = src0->ne[2];
//const int ne03 = src0->ne[3];
const int ne10 = src1->ne[0];
const int ne11 = src1->ne[1];
//const int ne12 = src1->ne[2];
//const int ne13 = src1->ne[3];
//const int ne0 = dst->ne[0];
//const int ne1 = dst->ne[1];
//const int ne2 = dst->ne[2];
//const int ne3 = dst->ne[3];
//const int ne = ne0*ne1*ne2*ne3;
const int nb00 = src0->nb[0];
const int nb01 = src0->nb[1];
const int nb02 = src0->nb[2];
//const int nb03 = src0->nb[3];
const int nb10 = src1->nb[0];
const int nb11 = src1->nb[1];
//const int nb12 = src1->nb[2];
//const int nb13 = src1->nb[3];
//const int nb0 = dst->nb[0];
const int nb1 = dst->nb[1];
//const int nb2 = dst->nb[2];
//const int nb3 = dst->nb[3];
const int ith = params->ith;
const int nth = params->nth;
const int nk = ne00;
const int nh = nk/2;
const int ew0 = ggml_up32(ne01);
GGML_ASSERT(ne00 % 2 == 1); // TODO: support even kernel sizes
GGML_ASSERT(nb00 == sizeof(ggml_fp16_t));
GGML_ASSERT(nb10 == sizeof(float));
if (params->type == GGML_TASK_INIT) {
// TODO: fix this memset (wsize is overestimated)
memset(params->wdata, 0, params->wsize);
// prepare kernel data (src0)
{
ggml_fp16_t * const wdata = (ggml_fp16_t *) params->wdata + 0;
for (int i02 = 0; i02 < ne02; i02++) {
for (int i01 = 0; i01 < ne01; i01++) {
const ggml_fp16_t * const src = (ggml_fp16_t *)((char *) src0->data + i02*nb02 + i01*nb01);
ggml_fp16_t * dst_data = wdata + i02*ew0*ne00;
for (int i00 = 0; i00 < ne00; i00++) {
dst_data[i00*ew0 + i01] = src[i00];
}
}
}
}
// prepare source data (src1)
{
ggml_fp16_t * const wdata = (ggml_fp16_t *) params->wdata + ne02*ew0*ne00;
for (int i11 = 0; i11 < ne11; i11++) {
const float * const src = (float *)((char *) src1->data + i11*nb11);
ggml_fp16_t * dst_data = wdata;
for (int i10 = 0; i10 < ne10; i10++) {
dst_data[(i10 + nh)*ew0 + i11] = GGML_FP32_TO_FP16(src[i10]);
}
}
}
return;
}
if (params->type == GGML_TASK_FINALIZE) {
return;
}
// total rows in dst
const int nr = ne02;
// rows per thread
const int dr = (nr + nth - 1)/nth;
// row range for this thread
const int ir0 = dr*ith;
const int ir1 = MIN(ir0 + dr, nr);
for (int i1 = ir0; i1 < ir1; i1++) {
float * dst_data = (float *)((char *) dst->data + i1*nb1);
for (int i0 = 0; i0 < ne10; i0 += 2) {
dst_data[i0/2] = 0;
for (int k = -nh; k <= nh; k++) {
float v = 0.0f;
ggml_vec_dot_f16(ew0, &v,
(ggml_fp16_t *) params->wdata + i1*ew0*ne00 + (nh + k)*ew0,
(ggml_fp16_t *) params->wdata + ne02*ew0*ne00 + (i0 + nh + k)*ew0);
dst_data[i0/2] += v;
}
}
}
}
static void ggml_compute_forward_conv_1d_2s_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
GGML_ASSERT(src0->type == GGML_TYPE_F32);
GGML_ASSERT(src1->type == GGML_TYPE_F32);
GGML_ASSERT( dst->type == GGML_TYPE_F32);
int64_t t0 = ggml_perf_time_us();
UNUSED(t0);
const int ne00 = src0->ne[0];
const int ne01 = src0->ne[1];
const int ne02 = src0->ne[2];
//const int ne03 = src0->ne[3];
const int ne10 = src1->ne[0];
const int ne11 = src1->ne[1];
//const int ne12 = src1->ne[2];
//const int ne13 = src1->ne[3];
//const int ne0 = dst->ne[0];
//const int ne1 = dst->ne[1];
//const int ne2 = dst->ne[2];
//const int ne3 = dst->ne[3];
//const int ne = ne0*ne1*ne2*ne3;
const int nb00 = src0->nb[0];
const int nb01 = src0->nb[1];
const int nb02 = src0->nb[2];
//const int nb03 = src0->nb[3];
const int nb10 = src1->nb[0];
const int nb11 = src1->nb[1];
//const int nb12 = src1->nb[2];
//const int nb13 = src1->nb[3];
//const int nb0 = dst->nb[0];
const int nb1 = dst->nb[1];
//const int nb2 = dst->nb[2];
//const int nb3 = dst->nb[3];
const int ith = params->ith;
const int nth = params->nth;
const int nk = ne00;
const int nh = nk/2;
const int ew0 = ggml_up32(ne01);
GGML_ASSERT(ne00 % 2 == 1); // TODO: support even kernel sizes
GGML_ASSERT(nb00 == sizeof(float));
GGML_ASSERT(nb10 == sizeof(float));
if (params->type == GGML_TASK_INIT) {
// TODO: fix this memset (wsize is overestimated)
memset(params->wdata, 0, params->wsize);
// prepare kernel data (src0)
{
float * const wdata = (float *) params->wdata + 0;
for (int i02 = 0; i02 < ne02; i02++) {
for (int i01 = 0; i01 < ne01; i01++) {
const float * const src = (float *)((char *) src0->data + i02*nb02 + i01*nb01);
float * dst_data = wdata + i02*ew0*ne00;
for (int i00 = 0; i00 < ne00; i00++) {
dst_data[i00*ew0 + i01] = src[i00];
}
}
}
}
// prepare source data (src1)
{
float * const wdata = (float *) params->wdata + ne02*ew0*ne00;
for (int i11 = 0; i11 < ne11; i11++) {
const float * const src = (float *)((char *) src1->data + i11*nb11);
float * dst_data = wdata;
for (int i10 = 0; i10 < ne10; i10++) {
dst_data[(i10 + nh)*ew0 + i11] = src[i10];
}
}
}
return;
}
if (params->type == GGML_TASK_FINALIZE) {
return;
}
// total rows in dst
const int nr = ne02;
// rows per thread
const int dr = (nr + nth - 1)/nth;
// row range for this thread
const int ir0 = dr*ith;
const int ir1 = MIN(ir0 + dr, nr);
for (int i1 = ir0; i1 < ir1; i1++) {
float * dst_data = (float *)((char *) dst->data + i1*nb1);
for (int i0 = 0; i0 < ne10; i0 += 2) {
dst_data[i0/2] = 0;
for (int k = -nh; k <= nh; k++) {
float v = 0.0f;
ggml_vec_dot_f32(ew0, &v,
(float *) params->wdata + i1*ew0*ne00 + (nh + k)*ew0,
(float *) params->wdata + ne02*ew0*ne00 + (i0 + nh + k)*ew0);
dst_data[i0/2] += v;
}
}
}
}
static void ggml_compute_forward_conv_1d_2s(
const struct ggml_compute_params * params,
const struct ggml_tensor * src0,
const struct ggml_tensor * src1,
struct ggml_tensor * dst) {
switch (src0->type) {
case GGML_TYPE_F16:
{
ggml_compute_forward_conv_1d_2s_f16_f32(params, src0, src1, dst);
} break;
case GGML_TYPE_F32:
{
ggml_compute_forward_conv_1d_2s_f32(params, src0, src1, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
// ggml_compute_forward_flash_attn
static void ggml_compute_forward_flash_attn_f32(
const struct ggml_compute_params * params,
const struct ggml_tensor * q,
const struct ggml_tensor * k,
const struct ggml_tensor * v,
const bool masked,
struct ggml_tensor * dst) {
int64_t t0 = ggml_perf_time_us();
UNUSED(t0);
const int neq0 = q->ne[0];
const int neq1 = q->ne[1];
const int neq2 = q->ne[2];
const int neq3 = q->ne[3];
const int nek0 = k->ne[0];
const int nek1 = k->ne[1];
//const int nek2 = k->ne[2];
//const int nek3 = k->ne[3];
//const int nev0 = v->ne[0];
const int nev1 = v->ne[1];
//const int nev2 = v->ne[2];
//const int nev3 = v->ne[3];
const int ne0 = dst->ne[0];
const int ne1 = dst->ne[1];
//const int ne2 = dst->ne[2];
//const int ne3 = dst->ne[3];
const int nbk0 = k->nb[0];
const int nbk1 = k->nb[1];
const int nbk2 = k->nb[2];
const int nbk3 = k->nb[3];
const int nbq0 = q->nb[0];
const int nbq1 = q->nb[1];
const int nbq2 = q->nb[2];
const int nbq3 = q->nb[3];
const int nbv0 = v->nb[0];
const int nbv1 = v->nb[1];
const int nbv2 = v->nb[2];
const int nbv3 = v->nb[3];
const int nb0 = dst->nb[0];
const int nb1 = dst->nb[1];
const int nb2 = dst->nb[2];
const int nb3 = dst->nb[3];
const int ith = params->ith;
const int nth = params->nth;
const int D = neq0;
const int N = neq1;
const int P = nek1 - N;
const int M = P + N;
const int Mup = ggml_up(M, GGML_SOFT_MAX_UNROLL);
GGML_ASSERT(ne0 == D);
GGML_ASSERT(ne1 == N);
GGML_ASSERT(P >= 0);
GGML_ASSERT(nbq0 == sizeof(float));
GGML_ASSERT(nbk0 == sizeof(float));
GGML_ASSERT(nbv0 == sizeof(float));
GGML_ASSERT(neq0 == D);
GGML_ASSERT(nek0 == D);
GGML_ASSERT(nev1 == D);
GGML_ASSERT(neq1 == N);
GGML_ASSERT(nek1 == N + P);
GGML_ASSERT(nev1 == D);
// dst cannot be transposed or permuted
GGML_ASSERT(nb0 == sizeof(float));
GGML_ASSERT(nb0 <= nb1);
GGML_ASSERT(nb1 <= nb2);
GGML_ASSERT(nb2 <= nb3);
if (params->type == GGML_TASK_INIT) {
return;
}
if (params->type == GGML_TASK_FINALIZE) {
return;
}
// parallelize by q rows using ggml_vec_dot_f32
// total rows in q
const int nr = neq1*neq2*neq3;
// rows per thread
const int dr = (nr + nth - 1)/nth;
// row range for this thread
const int ir0 = dr*ith;
const int ir1 = MIN(ir0 + dr, nr);
const float scale = 1.0f/sqrtf(D);
//printf("P=%d N=%d D=%d ir0=%d ir1=%d scale = %f\n", P, N, D, ir0, ir1, scale);
for (int ir = ir0; ir < ir1; ++ir) {
// q indices
const int iq3 = ir/(neq2*neq1);
const int iq2 = (ir - iq3*neq2*neq1)/neq1;
const int iq1 = (ir - iq3*neq2*neq1 - iq2*neq1);
float * S = (float *) params->wdata + ith*(Mup + CACHE_LINE_SIZE_F32);
for (int i = M; i < Mup; ++i) {
S[i] = -INFINITY;
}
for (int ic = 0; ic < nek1; ++ic) {
// k indices
const int ik3 = iq3;
const int ik2 = iq2;
const int ik1 = ic;
// S indices
const int i1 = ik1;
ggml_vec_dot_f32(neq0,
S + i1,
(float *) ((char *) k->data + (ik1*nbk1 + ik2*nbk2 + ik3*nbk3)),
(float *) ((char *) q->data + (iq1*nbq1 + iq2*nbq2 + iq3*nbq3)));
}
// scale
ggml_vec_scale_f32(nek1, S, scale);
if (masked) {
for (int i = P; i < M; i++) {
if (i > P + iq1) {
S[i] = -INFINITY;
}
}
}
// softmax
{
float max = -INFINITY;
ggml_vec_max_f32(M, &max, S);
ggml_float sum = 0.0;
{
#ifdef GGML_SOFT_MAX_ACCELERATE
max = -max;
vDSP_vsadd(S, 1, &max, S, 1, Mup);
vvexpf(S, S, &Mup);
ggml_vec_sum_f32(Mup, &sum, S);
#else
uint16_t scvt[GGML_SOFT_MAX_UNROLL];
ggml_float sump[GGML_SOFT_MAX_UNROLL] = { 0.0 };
for (int i = 0; i < Mup; i += GGML_SOFT_MAX_UNROLL) {
float * SS = S + i;
for (int j = 0; j < GGML_SOFT_MAX_UNROLL; ++j) {
if (SS[j] == -INFINITY) {
SS[j] = 0.0f;
} else {
ggml_fp16_t s = GGML_FP32_TO_FP16(SS[j] - max);
memcpy(&scvt[j], &s, sizeof(uint16_t));
const float val = GGML_FP16_TO_FP32(table_exp_f16[scvt[j]]);
sump[j] += (ggml_float)val;
SS[j] = val;
}
}
}
for (int i = 0; i < GGML_SOFT_MAX_UNROLL; i++) {
sum += sump[i];
}
#endif
}
assert(sum > 0.0);
sum = 1.0/sum;
ggml_vec_scale_f32(M, S, sum);
#ifndef NDEBUG
for (int i = 0; i < M; ++i) {
assert(!isnan(S[i]));
assert(!isinf(S[i]));
}
#endif
}
for (int ic = 0; ic < nev1; ++ic) {
// dst indices
const int i1 = iq1;
const int i2 = iq2;
const int i3 = iq3;
ggml_vec_dot_f32(nek1,
(float *) ((char *) dst->data + (ic*nb0 + i1*nb1 + i2*nb2 + i3*nb3)),
(float *) ((char *) v->data + ( ic*nbv1 + i2*nbv2 + i3*nbv3)),
S);
}
}
}
static void ggml_compute_forward_flash_attn_f16(
const struct ggml_compute_params * params,
const struct ggml_tensor * q,
const struct ggml_tensor * k,
const struct ggml_tensor * v,
const bool masked,
struct ggml_tensor * dst) {
int64_t t0 = ggml_perf_time_us();
UNUSED(t0);
const int neq0 = q->ne[0];
const int neq1 = q->ne[1];
const int neq2 = q->ne[2];
const int neq3 = q->ne[3];
const int nek0 = k->ne[0];
const int nek1 = k->ne[1];
//const int nek2 = k->ne[2];
//const int nek3 = k->ne[3];
//const int nev0 = v->ne[0];
const int nev1 = v->ne[1];
//const int nev2 = v->ne[2];
//const int nev3 = v->ne[3];
const int ne0 = dst->ne[0];
const int ne1 = dst->ne[1];
//const int ne2 = dst->ne[2];
//const int ne3 = dst->ne[3];
const int nbk0 = k->nb[0];
const int nbk1 = k->nb[1];
const int nbk2 = k->nb[2];
const int nbk3 = k->nb[3];
const int nbq0 = q->nb[0];
const int nbq1 = q->nb[1];
const int nbq2 = q->nb[2];
const int nbq3 = q->nb[3];
const int nbv0 = v->nb[0];
const int nbv1 = v->nb[1];
const int nbv2 = v->nb[2];
const int nbv3 = v->nb[3];
const int nb0 = dst->nb[0];
const int nb1 = dst->nb[1];
const int nb2 = dst->nb[2];
const int nb3 = dst->nb[3];
const int ith = params->ith;
const int nth = params->nth;
const int D = neq0;
const int N = neq1;
const int P = nek1 - N;
const int M = P + N;
const int Mup = ggml_up(M, GGML_SOFT_MAX_UNROLL);
GGML_ASSERT(ne0 == D);
GGML_ASSERT(ne1 == N);
GGML_ASSERT(P >= 0);
GGML_ASSERT(nbq0 == sizeof(ggml_fp16_t));
GGML_ASSERT(nbk0 == sizeof(ggml_fp16_t));
GGML_ASSERT(nbv0 == sizeof(ggml_fp16_t));
GGML_ASSERT(neq0 == D);
GGML_ASSERT(nek0 == D);
GGML_ASSERT(nev1 == D);
GGML_ASSERT(neq1 == N);
GGML_ASSERT(nek1 == N + P);
GGML_ASSERT(nev1 == D);
// dst cannot be transposed or permuted
GGML_ASSERT(nb0 == sizeof(float));
GGML_ASSERT(nb0 <= nb1);
GGML_ASSERT(nb1 <= nb2);
GGML_ASSERT(nb2 <= nb3);
if (params->type == GGML_TASK_INIT) {
return;
}
if (params->type == GGML_TASK_FINALIZE) {
return;
}
// parallelize by q rows using ggml_vec_dot_f32
// total rows in q
const int nr = neq1*neq2*neq3;
// rows per thread
const int dr = (nr + nth - 1)/nth;
// row range for this thread
const int ir0 = dr*ith;
const int ir1 = MIN(ir0 + dr, nr);
const float scale = 1.0f/sqrtf(D);
//printf("P=%d N=%d D=%d ir0=%d ir1=%d scale = %f\n", P, N, D, ir0, ir1, scale);
for (int ir = ir0; ir < ir1; ++ir) {
// q indices
const int iq3 = ir/(neq2*neq1);
const int iq2 = (ir - iq3*neq2*neq1)/neq1;
const int iq1 = (ir - iq3*neq2*neq1 - iq2*neq1);
float * S = (float *) params->wdata + ith*(2*Mup + CACHE_LINE_SIZE_F32);
for (int i = M; i < Mup; ++i) {
S[i] = -INFINITY;
}
if (GGML_VEC_DOT_UNROLL > 2 || nek1 % GGML_VEC_DOT_UNROLL != 0) {
for (int ic = 0; ic < nek1; ++ic) {
// k indices
const int ik3 = iq3;
const int ik2 = iq2;
const int ik1 = ic;
// S indices
const int i1 = ik1;
ggml_vec_dot_f16(neq0,
S + i1,
(ggml_fp16_t *) ((char *) k->data + (ik1*nbk1 + ik2*nbk2 + ik3*nbk3)),
(ggml_fp16_t *) ((char *) q->data + (iq1*nbq1 + iq2*nbq2 + iq3*nbq3)));
}
} else {
for (int ic = 0; ic < nek1; ic += GGML_VEC_DOT_UNROLL) {
// k indices
const int ik3 = iq3;
const int ik2 = iq2;
const int ik1 = ic;
// S indices
const int i1 = ik1;
ggml_vec_dot_f16_unroll(neq0, nbk1,
S + i1,
((char *) k->data + (ik1*nbk1 + ik2*nbk2 + ik3*nbk3)),
(ggml_fp16_t *) ((char *) q->data + (iq1*nbq1 + iq2*nbq2 + iq3*nbq3)));
}
}
// scale
ggml_vec_scale_f32(nek1, S, scale);
if (masked) {
for (int i = P; i < M; i++) {
if (i > P + iq1) {
S[i] = -INFINITY;
}
}
}
// softmax
{
float max = -INFINITY;
ggml_vec_max_f32(M, &max, S);
ggml_float sum = 0.0;
{
#ifdef GGML_SOFT_MAX_ACCELERATE
max = -max;
vDSP_vsadd(S, 1, &max, S, 1, Mup);
vvexpf(S, S, &Mup);
ggml_vec_sum_f32(Mup, &sum, S);
#else
uint16_t scvt[GGML_SOFT_MAX_UNROLL];
ggml_float sump[GGML_SOFT_MAX_UNROLL] = { 0.0 };
for (int i = 0; i < Mup; i += GGML_SOFT_MAX_UNROLL) {
float * SS = S + i;
for (int j = 0; j < GGML_SOFT_MAX_UNROLL; ++j) {
if (SS[j] == -INFINITY) {
SS[j] = 0.0f;
} else {
ggml_fp16_t s = GGML_FP32_TO_FP16(SS[j] - max);
memcpy(&scvt[j], &s, sizeof(uint16_t));
const float val = GGML_FP16_TO_FP32(table_exp_f16[scvt[j]]);
sump[j] += (ggml_float)val;
SS[j] = val;
}
}
}
for (int i = 0; i < GGML_SOFT_MAX_UNROLL; i++) {
sum += sump[i];
}
#endif
}
assert(sum > 0.0);
sum = 1.0/sum;
ggml_vec_scale_f32(M, S, sum);
#ifndef NDEBUG
for (int i = 0; i < M; ++i) {
assert(!isnan(S[i]));
assert(!isinf(S[i]));
}
#endif
}
ggml_fp16_t * S16 = (ggml_fp16_t *) ((float *) params->wdata + ith*(2*Mup + CACHE_LINE_SIZE_F32) + Mup);
for (int i = 0; i < M; i++) {
S16[i] = GGML_FP32_TO_FP16(S[i]);
}
if (GGML_VEC_DOT_UNROLL == 1 || (nev1 % GGML_VEC_DOT_UNROLL != 0)) {
for (int ic = 0; ic < nev1; ++ic) {
// dst indices
const int i1 = iq1;
const int i2 = iq2;
const int i3 = iq3;
ggml_vec_dot_f16(nek1,
(float *) ((char *) dst->data + (ic*nb0 + i1*nb1 + i2*nb2 + i3*nb3)),
(ggml_fp16_t *) ((char *) v->data + ( ic*nbv1 + i2*nbv2 + i3*nbv3)),
S16);
}
} else {
for (int ic = 0; ic < nev1; ic += GGML_VEC_DOT_UNROLL) {
// dst indices
const int i1 = iq1;
const int i2 = iq2;
const int i3 = iq3;
ggml_vec_dot_f16_unroll(nek1, nbv1,
(float *) ((char *) dst->data + (ic*nb0 + i1*nb1 + i2*nb2 + i3*nb3)),
((char *) v->data + ( ic*nbv1 + i2*nbv2 + i3*nbv3)),
S16);
}
}
}
}
static void ggml_compute_forward_flash_attn(
const struct ggml_compute_params * params,
const struct ggml_tensor * q,
const struct ggml_tensor * k,
const struct ggml_tensor * v,
const bool masked,
struct ggml_tensor * dst) {
switch (q->type) {
case GGML_TYPE_F16:
{
ggml_compute_forward_flash_attn_f16(params, q, k, v, masked, dst);
} break;
case GGML_TYPE_F32:
{
ggml_compute_forward_flash_attn_f32(params, q, k, v, masked, dst);
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
// ggml_compute_forward_flash_ff
static void ggml_compute_forward_flash_ff_f16(
const struct ggml_compute_params * params,
const struct ggml_tensor * a, // F16
const struct ggml_tensor * b0, // F16 fc_w
const struct ggml_tensor * b1, // F32 fc_b
const struct ggml_tensor * c0, // F16 proj_w
const struct ggml_tensor * c1, // F32 proj_b
struct ggml_tensor * dst) {
int64_t t0 = ggml_perf_time_us();
UNUSED(t0);
const int nea0 = a->ne[0];
const int nea1 = a->ne[1];
const int nea2 = a->ne[2];
const int nea3 = a->ne[3];
const int neb00 = b0->ne[0];
const int neb01 = b0->ne[1];
//const int neb02 = b0->ne[2];
//const int neb03 = b0->ne[3];
const int neb10 = b1->ne[0];
const int neb11 = b1->ne[1];
//const int neb12 = b1->ne[2];
//const int neb13 = b1->ne[3];
const int nec00 = c0->ne[0];
const int nec01 = c0->ne[1];
//const int nec02 = c0->ne[2];
//const int nec03 = c0->ne[3];
const int nec10 = c1->ne[0];
const int nec11 = c1->ne[1];
//const int nec12 = c1->ne[2];
//const int nec13 = c1->ne[3];
const int ne0 = dst->ne[0];
const int ne1 = dst->ne[1];
const int ne2 = dst->ne[2];
//const int ne3 = dst->ne[3];
const int nba0 = a->nb[0];
const int nba1 = a->nb[1];
const int nba2 = a->nb[2];
const int nba3 = a->nb[3];
const int nbb00 = b0->nb[0];
const int nbb01 = b0->nb[1];
const int nbb02 = b0->nb[2];
const int nbb03 = b0->nb[3];
const int nbb10 = b1->nb[0];
//const int nbb11 = b1->nb[1];
//const int nbb12 = b1->nb[2];
//const int nbb13 = b1->nb[3];
const int nbc00 = c0->nb[0];
const int nbc01 = c0->nb[1];
const int nbc02 = c0->nb[2];
const int nbc03 = c0->nb[3];
const int nbc10 = c1->nb[0];
//const int nbc11 = c1->nb[1];
//const int nbc12 = c1->nb[2];
//const int nbc13 = c1->nb[3];
const int nb0 = dst->nb[0];
const int nb1 = dst->nb[1];
const int nb2 = dst->nb[2];
const int nb3 = dst->nb[3];
const int ith = params->ith;
const int nth = params->nth;
const int D = nea0;
//const int N = nea1;
const int M = neb01;
GGML_ASSERT(ne0 == nea0);
GGML_ASSERT(ne1 == nea1);
GGML_ASSERT(ne2 == nea2);
GGML_ASSERT(nba0 == sizeof(ggml_fp16_t));
GGML_ASSERT(nbb00 == sizeof(ggml_fp16_t));
GGML_ASSERT(nbb10 == sizeof(float));
GGML_ASSERT(nbc00 == sizeof(ggml_fp16_t));
GGML_ASSERT(nbc10 == sizeof(float));
GGML_ASSERT(neb00 == D);
GGML_ASSERT(neb01 == M);
GGML_ASSERT(neb10 == M);
GGML_ASSERT(neb11 == 1);
GGML_ASSERT(nec00 == M);
GGML_ASSERT(nec01 == D);
GGML_ASSERT(nec10 == D);
GGML_ASSERT(nec11 == 1);
// dst cannot be transposed or permuted
GGML_ASSERT(nb0 == sizeof(float));
GGML_ASSERT(nb0 <= nb1);
GGML_ASSERT(nb1 <= nb2);
GGML_ASSERT(nb2 <= nb3);
if (params->type == GGML_TASK_INIT) {
return;
}
if (params->type == GGML_TASK_FINALIZE) {
return;
}
// parallelize by a rows using ggml_vec_dot_f32
// total rows in a
const int nr = nea1*nea2*nea3;
// rows per thread
const int dr = (nr + nth - 1)/nth;
// row range for this thread
const int ir0 = dr*ith;
const int ir1 = MIN(ir0 + dr, nr);
for (int ir = ir0; ir < ir1; ++ir) {
// a indices
const int ia3 = ir/(nea2*nea1);
const int ia2 = (ir - ia3*nea2*nea1)/nea1;
const int ia1 = (ir - ia3*nea2*nea1 - ia2*nea1);
float * S = (float *) params->wdata + ith*(2*M + CACHE_LINE_SIZE_F32);
for (int ic = 0; ic < neb01; ++ic) {
// b0 indices
const int ib03 = ia3;
const int ib02 = ia2;
const int ib01 = ic;
// S indices
const int i1 = ib01;
ggml_vec_dot_f16(nea0,
S + i1,
(ggml_fp16_t *) ((char *) b0->data + (ib01*nbb01 + ib02*nbb02 + ib03*nbb03)),
(ggml_fp16_t *) ((char *) a->data + ( ia1*nba1 + ia2*nba2 + ia3*nba3)));
}
ggml_vec_add_f32(neb01, S, S, (float *) b1->data);
//ggml_vec_gelu_f32(neb01, S, S);
ggml_fp16_t * S16 = (ggml_fp16_t *) ((float *) params->wdata + ith*(2*M + CACHE_LINE_SIZE_F32) + M);
for (int i = 0; i < M; i++) {
S16[i] = GGML_FP32_TO_FP16(S[i]);
}
ggml_vec_gelu_f16(neb01, S16, S16);
{
// dst indices
const int i1 = ia1;
const int i2 = ia2;
const int i3 = ia3;
for (int ic = 0; ic < nec01; ++ic) {
ggml_vec_dot_f16(neb01,
(float *) ((char *) dst->data + (ic*nb0 + i1*nb1 + i2*nb2 + i3*nb3)),
(ggml_fp16_t *) ((char *) c0->data + ( ic*nbc01 + i2*nbc02 + i3*nbc03)),
S16);
}
ggml_vec_add_f32(nec01,
(float *) ((char *) dst->data + (i1*nb1 + i2*nb2 + i3*nb3)),
(float *) ((char *) dst->data + (i1*nb1 + i2*nb2 + i3*nb3)),
(float *) c1->data);
}
}
}
static void ggml_compute_forward_flash_ff(
const struct ggml_compute_params * params,
const struct ggml_tensor * a,
const struct ggml_tensor * b0,
const struct ggml_tensor * b1,
const struct ggml_tensor * c0,
const struct ggml_tensor * c1,
struct ggml_tensor * dst) {
switch (b0->type) {
case GGML_TYPE_F16:
{
ggml_compute_forward_flash_ff_f16(params, a, b0, b1, c0, c1, dst);
} break;
case GGML_TYPE_F32:
{
GGML_ASSERT(false); // TODO
} break;
case GGML_TYPE_Q4_0:
case GGML_TYPE_Q4_1:
case GGML_TYPE_I8:
case GGML_TYPE_I16:
case GGML_TYPE_I32:
case GGML_TYPE_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
/////////////////////////////////
static void ggml_compute_forward(struct ggml_compute_params * params, struct ggml_tensor * tensor) {
GGML_ASSERT(params);
switch (tensor->op) {
case GGML_OP_DUP:
{
ggml_compute_forward_dup(params, tensor->src0, tensor);
} break;
case GGML_OP_ADD:
{
ggml_compute_forward_add(params, tensor->src0, tensor->src1, tensor);
} break;
case GGML_OP_SUB:
{
ggml_compute_forward_sub(params, tensor->src0, tensor->src1, tensor);
} break;
case GGML_OP_MUL:
{
ggml_compute_forward_mul(params, tensor->src0, tensor->src1, tensor);
} break;
case GGML_OP_DIV:
{
ggml_compute_forward_div(params, tensor->src0, tensor->src1, tensor);
} break;
case GGML_OP_SQR:
{
ggml_compute_forward_sqr(params, tensor->src0, tensor);
} break;
case GGML_OP_SQRT:
{
ggml_compute_forward_sqrt(params, tensor->src0, tensor);
} break;
case GGML_OP_SUM:
{
ggml_compute_forward_sum(params, tensor->src0, tensor);
} break;
case GGML_OP_MEAN:
{
ggml_compute_forward_mean(params, tensor->src0, tensor);
} break;
case GGML_OP_REPEAT:
{
ggml_compute_forward_repeat(params, tensor->src0, tensor);
} break;
case GGML_OP_ABS:
{
ggml_compute_forward_abs(params, tensor->src0, tensor);
} break;
case GGML_OP_SGN:
{
ggml_compute_forward_sgn(params, tensor->src0, tensor);
} break;
case GGML_OP_NEG:
{
ggml_compute_forward_neg(params, tensor->src0, tensor);
} break;
case GGML_OP_STEP:
{
ggml_compute_forward_step(params, tensor->src0, tensor);
} break;
case GGML_OP_RELU:
{
ggml_compute_forward_relu(params, tensor->src0, tensor);
} break;
case GGML_OP_GELU:
{
ggml_compute_forward_gelu(params, tensor->src0, tensor);
} break;
case GGML_OP_SILU:
{
ggml_compute_forward_silu(params, tensor->src0, tensor);
} break;
case GGML_OP_NORM:
{
ggml_compute_forward_norm(params, tensor->src0, tensor);
} break;
case GGML_OP_RMS_NORM:
{
ggml_compute_forward_rms_norm(params, tensor->src0, tensor);
} break;
case GGML_OP_MUL_MAT:
{
ggml_compute_forward_mul_mat(params, tensor->src0, tensor->src1, tensor);
} break;
case GGML_OP_SCALE:
{
ggml_compute_forward_scale(params, tensor->src0, tensor->src1, tensor);
} break;
case GGML_OP_CPY:
{
ggml_compute_forward_cpy(params, tensor->src0, tensor);
} break;
case GGML_OP_RESHAPE:
{
ggml_compute_forward_reshape(params, tensor->src0, tensor);
} break;
case GGML_OP_VIEW:
{
ggml_compute_forward_view(params, tensor->src0);
} break;
case GGML_OP_PERMUTE:
{
ggml_compute_forward_permute(params, tensor->src0);
} break;
case GGML_OP_TRANSPOSE:
{
ggml_compute_forward_transpose(params, tensor->src0);
} break;
case GGML_OP_GET_ROWS:
{
ggml_compute_forward_get_rows(params, tensor->src0, tensor->src1, tensor);
} break;
case GGML_OP_DIAG_MASK_INF:
{
ggml_compute_forward_diag_mask_inf(params, tensor->src0, tensor->src1, tensor);
} break;
case GGML_OP_SOFT_MAX:
{
ggml_compute_forward_soft_max(params, tensor->src0, tensor);
} break;
case GGML_OP_ROPE:
{
ggml_compute_forward_rope(params, tensor->src0, tensor->src1, tensor);
} break;
case GGML_OP_CONV_1D_1S:
{
ggml_compute_forward_conv_1d_1s(params, tensor->src0, tensor->src1, tensor);
} break;
case GGML_OP_CONV_1D_2S:
{
ggml_compute_forward_conv_1d_2s(params, tensor->src0, tensor->src1, tensor);
} break;
case GGML_OP_FLASH_ATTN:
{
int32_t t = ggml_get_i32_1d(tensor->opt[1], 0);
GGML_ASSERT(t == 0 || t == 1);
bool masked = t != 0;
ggml_compute_forward_flash_attn(params, tensor->src0, tensor->src1, tensor->opt[0], masked, tensor);
} break;
case GGML_OP_FLASH_FF:
{
ggml_compute_forward_flash_ff(params, tensor->src0, tensor->src1, tensor->opt[0], tensor->opt[1], tensor->opt[2], tensor);
} break;
case GGML_OP_NONE:
{
// nop
} break;
case GGML_OP_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
////////////////////////////////////////////////////////////////////////////////
static void ggml_compute_backward(struct ggml_context * ctx, struct ggml_tensor * tensor, bool inplace) {
struct ggml_tensor * src0 = tensor->src0;
struct ggml_tensor * src1 = tensor->src1;
switch (tensor->op) {
case GGML_OP_DUP:
{
if (src0->grad) {
src0->grad = ggml_add_impl(ctx, src0->grad, tensor->grad, inplace);
}
} break;
case GGML_OP_ADD:
{
if (src0->grad) {
src0->grad = ggml_add_impl(ctx, src0->grad, tensor->grad, inplace);
}
if (src1->grad) {
src1->grad = ggml_add_impl(ctx, src1->grad, tensor->grad, inplace);
}
} break;
case GGML_OP_SUB:
{
if (src0->grad) {
src0->grad = ggml_add_impl(ctx, src0->grad, tensor->grad, inplace);
}
if (src1->grad) {
src1->grad = ggml_sub_impl(ctx, src1->grad, tensor->grad, inplace);
}
} break;
case GGML_OP_MUL:
{
if (src0->grad) {
src0->grad =
ggml_add_impl(ctx,
src0->grad,
ggml_mul(ctx, src1, tensor->grad),
inplace);
}
if (src1->grad) {
src1->grad =
ggml_add_impl(ctx,
src1->grad,
ggml_mul(ctx, src0, tensor->grad),
inplace);
}
} break;
case GGML_OP_DIV:
{
if (src0->grad) {
src0->grad =
ggml_add_impl(ctx,
src0->grad,
ggml_div(ctx, tensor->grad, src1),
inplace);
}
if (src1->grad) {
src1->grad =
ggml_sub_impl(ctx,
src1->grad,
ggml_mul(ctx,
tensor->grad,
ggml_div(ctx, tensor, src1)),
inplace);
}
} break;
case GGML_OP_SQR:
{
if (src0->grad) {
src0->grad =
ggml_add_impl(ctx,
src0->grad,
ggml_mul(ctx,
ggml_mul(ctx, src0, tensor->grad),
ggml_repeat(ctx, ggml_new_f32(ctx, 2.0f), src0)),
inplace);
}
} break;
case GGML_OP_SQRT:
{
if (src0->grad) {
src0->grad =
ggml_add_impl(ctx,
src0->grad,
ggml_div(ctx,
ggml_repeat(ctx, ggml_new_f32(ctx, 0.5f), tensor),
tensor),
inplace);
}
} break;
case GGML_OP_SUM:
{
if (src0->grad) {
src0->grad =
ggml_add_impl(ctx,
src0->grad,
ggml_repeat(ctx, tensor->grad, src0->grad),
inplace);
}
} break;
case GGML_OP_MEAN:
{
GGML_ASSERT(false); // TODO: implement
} break;
case GGML_OP_REPEAT:
{
if (src0->grad) {
src0->grad =
ggml_add_impl(ctx,
src0->grad,
ggml_sum(ctx, tensor->grad),
inplace);
}
} break;
case GGML_OP_ABS:
{
if (src0->grad) {
src0->grad =
ggml_add_impl(ctx,
src0->grad,
ggml_mul(ctx,
ggml_sgn(ctx, src0),
tensor->grad),
inplace);
}
} break;
case GGML_OP_SGN:
{
if (src0->grad) {
// noop
}
} break;
case GGML_OP_NEG:
{
if (src0->grad) {
src0->grad = ggml_sub_impl(ctx, src0->grad, tensor->grad, inplace);
}
} break;
case GGML_OP_STEP:
{
if (src0->grad) {
// noop
}
} break;
case GGML_OP_RELU:
{
if (src0->grad) {
src0->grad = ggml_sub_impl(ctx,
src0->grad,
ggml_mul(ctx,
ggml_step(ctx, src0),
tensor->grad),
inplace);
}
} break;
case GGML_OP_GELU:
{
GGML_ASSERT(false); // TODO: not implemented
} break;
case GGML_OP_SILU:
{
GGML_ASSERT(false); // TODO: not implemented
} break;
case GGML_OP_NORM:
{
GGML_ASSERT(false); // TODO: not implemented
} break;
case GGML_OP_RMS_NORM:
{
GGML_ASSERT(false); // TODO: not implemented
} break;
case GGML_OP_MUL_MAT:
{
if (src0->grad) {
// TODO: this requires outer product - ggml_out_prod(ctx, src1, tensor->grad);
GGML_ASSERT(false);
}
if (src1->grad) {
src1->grad =
ggml_add_impl(ctx,
src1->grad,
// TODO: fix transpose, the node will break the graph connections
ggml_mul_mat(ctx, ggml_transpose(ctx, src0), tensor->grad),
inplace);
}
} break;
case GGML_OP_SCALE:
{
GGML_ASSERT(false); // TODO: not implemented
} break;
case GGML_OP_CPY:
{
GGML_ASSERT(false); // TODO: not implemented
} break;
case GGML_OP_RESHAPE:
{
GGML_ASSERT(false); // TODO: not implemented
} break;
case GGML_OP_VIEW:
{
GGML_ASSERT(false); // not supported
} break;
case GGML_OP_PERMUTE:
{
GGML_ASSERT(false); // TODO: not implemented
} break;
case GGML_OP_TRANSPOSE:
{
GGML_ASSERT(false); // TODO: not implemented
} break;
case GGML_OP_GET_ROWS:
{
GGML_ASSERT(false); // TODO: not implemented
} break;
case GGML_OP_DIAG_MASK_INF:
{
GGML_ASSERT(false); // TODO: not implemented
} break;
case GGML_OP_SOFT_MAX:
{
GGML_ASSERT(false); // TODO: not implemented
} break;
case GGML_OP_ROPE:
{
GGML_ASSERT(false); // TODO: not implemented
} break;
case GGML_OP_CONV_1D_1S:
{
GGML_ASSERT(false); // TODO: not implemented
} break;
case GGML_OP_CONV_1D_2S:
{
GGML_ASSERT(false); // TODO: not implemented
} break;
case GGML_OP_FLASH_ATTN:
{
GGML_ASSERT(false); // not supported
} break;
case GGML_OP_FLASH_FF:
{
GGML_ASSERT(false); // not supported
} break;
case GGML_OP_NONE:
{
// nop
} break;
case GGML_OP_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
static void ggml_visit_parents(struct ggml_cgraph * cgraph, struct ggml_tensor * node) {
if (node->grad == NULL) {
// this usually happens when we generate intermediate nodes from constants in the backward pass
// it can also happen during forward pass, if the user performs computations with constants
if (node->op != GGML_OP_NONE) {
//GGML_PRINT_DEBUG("%s: warning: node %p has no grad, but op %d\n", __func__, (void *) node, node->op);
}
}
// check if already visited
for (int i = 0; i < cgraph->n_nodes; i++) {
if (cgraph->nodes[i] == node) {
return;
}
}
for (int i = 0; i < cgraph->n_leafs; i++) {
if (cgraph->leafs[i] == node) {
return;
}
}
if (node->src0) {
ggml_visit_parents(cgraph, node->src0);
}
if (node->src1) {
ggml_visit_parents(cgraph, node->src1);
}
for (int i = 0; i < GGML_MAX_OPT; ++i) {
if (node->opt[i]) {
ggml_visit_parents(cgraph, node->opt[i]);
}
}
if (node->op == GGML_OP_NONE && node->grad == NULL) {
// reached a leaf node, not part of the gradient graph (e.g. a constant)
GGML_ASSERT(cgraph->n_leafs < GGML_MAX_NODES);
cgraph->leafs[cgraph->n_leafs] = node;
cgraph->n_leafs++;
} else {
GGML_ASSERT(cgraph->n_nodes < GGML_MAX_NODES);
cgraph->nodes[cgraph->n_nodes] = node;
cgraph->grads[cgraph->n_nodes] = node->grad;
cgraph->n_nodes++;
}
}
static void ggml_build_forward_impl(struct ggml_cgraph * cgraph, struct ggml_tensor * tensor, bool expand) {
if (!expand) {
cgraph->n_nodes = 0;
cgraph->n_leafs = 0;
}
const int n0 = cgraph->n_nodes;
UNUSED(n0);
ggml_visit_parents(cgraph, tensor);
const int n_new = cgraph->n_nodes - n0;
GGML_PRINT_DEBUG("%s: visited %d new nodes\n", __func__, n_new);
if (n_new > 0) {
// the last added node should always be starting point
GGML_ASSERT(cgraph->nodes[cgraph->n_nodes - 1] == tensor);
}
}
void ggml_build_forward_expand(struct ggml_cgraph * cgraph, struct ggml_tensor * tensor) {
ggml_build_forward_impl(cgraph, tensor, true);
}
struct ggml_cgraph ggml_build_forward(struct ggml_tensor * tensor) {
struct ggml_cgraph result = {
/*.n_nodes =*/ 0,
/*.n_leafs =*/ 0,
/*.n_threads =*/ 0,
/*.work_size =*/ 0,
/*.work =*/ NULL,
/*.nodes =*/ { NULL },
/*.grads =*/ { NULL },
/*.leafs =*/ { NULL },
/*.perf_runs =*/ 0,
/*.perf_cycles =*/ 0,
/*.perf_time_us =*/ 0,
};
ggml_build_forward_impl(&result, tensor, false);
return result;
}
struct ggml_cgraph ggml_build_backward(struct ggml_context * ctx, struct ggml_cgraph * gf, bool keep) {
struct ggml_cgraph result = *gf;
GGML_ASSERT(gf->n_nodes > 0);
// if we are keeping the gradient graph, we have to detach the gradient nodes from the original graph
if (keep) {
for (int i = 0; i < gf->n_nodes; i++) {
struct ggml_tensor * node = gf->nodes[i];
if (node->grad) {
node->grad = ggml_dup_tensor(ctx, node);
gf->grads[i] = node->grad;
}
}
}
for (int i = gf->n_nodes - 1; i >= 0; i--) {
struct ggml_tensor * node = gf->nodes[i];
// because we detached the grad nodes from the original graph, we can afford inplace operations
if (node->grad) {
ggml_compute_backward(ctx, node, keep);
}
}
for (int i = gf->n_nodes - 1; i >= 0; i--) {
struct ggml_tensor * node = gf->nodes[i];
if (node->is_param) {
GGML_PRINT_DEBUG("%s: found root node %p\n", __func__, (void *) node);
ggml_build_forward_impl(&result, node->grad, true);
}
}
return result;
}
//
// thread data
//
// synchronization is done via busy loops
// I tried using spin locks, but not sure how to use them correctly - the things I tried were slower than busy loops
//
#ifdef __APPLE__
//#include <os/lock.h>
//
//typedef os_unfair_lock ggml_lock_t;
//
//#define ggml_lock_init(x) UNUSED(x)
//#define ggml_lock_destroy(x) UNUSED(x)
//#define ggml_lock_lock os_unfair_lock_lock
//#define ggml_lock_unlock os_unfair_lock_unlock
//
//#define GGML_LOCK_INITIALIZER OS_UNFAIR_LOCK_INIT
typedef int ggml_lock_t;
#define ggml_lock_init(x) UNUSED(x)
#define ggml_lock_destroy(x) UNUSED(x)
#define ggml_lock_lock(x) UNUSED(x)
#define ggml_lock_unlock(x) UNUSED(x)
#define GGML_LOCK_INITIALIZER 0
typedef pthread_t ggml_thread_t;
#define ggml_thread_create pthread_create
#define ggml_thread_join pthread_join
#else
//typedef pthread_spinlock_t ggml_lock_t;
//#define ggml_lock_init(x) pthread_spin_init(x, PTHREAD_PROCESS_PRIVATE)
//#define ggml_lock_destroy pthread_spin_destroy
//#define ggml_lock_lock pthread_spin_lock
//#define ggml_lock_unlock pthread_spin_unlock
typedef int ggml_lock_t;
#define ggml_lock_init(x) UNUSED(x)
#define ggml_lock_destroy(x) UNUSED(x)
#define ggml_lock_lock(x) UNUSED(x)
#define ggml_lock_unlock(x) UNUSED(x)
#define GGML_LOCK_INITIALIZER 0
typedef pthread_t ggml_thread_t;
#define ggml_thread_create pthread_create
#define ggml_thread_join pthread_join
#endif
struct ggml_compute_state_shared {
ggml_lock_t spin;
int n_threads;
// synchronization primitives
atomic_int n_ready;
atomic_bool has_work;
atomic_bool stop; // stop all threads
};
struct ggml_compute_state {
ggml_thread_t thrd;
struct ggml_compute_params params;
struct ggml_tensor * node;
struct ggml_compute_state_shared * shared;
};
static thread_ret_t ggml_graph_compute_thread(void * data) {
struct ggml_compute_state * state = (struct ggml_compute_state *) data;
const int n_threads = state->shared->n_threads;
while (true) {
if (atomic_fetch_add(&state->shared->n_ready, 1) == n_threads - 1) {
atomic_store(&state->shared->has_work, false);
} else {
while (atomic_load(&state->shared->has_work)) {
if (atomic_load(&state->shared->stop)) {
return 0;
}
ggml_lock_lock (&state->shared->spin);
ggml_lock_unlock(&state->shared->spin);
}
}
atomic_fetch_sub(&state->shared->n_ready, 1);
// wait for work
while (!atomic_load(&state->shared->has_work)) {
if (atomic_load(&state->shared->stop)) {
return 0;
}
ggml_lock_lock (&state->shared->spin);
ggml_lock_unlock(&state->shared->spin);
}
// check if we should stop
if (atomic_load(&state->shared->stop)) {
break;
}
if (state->node) {
if (state->params.ith < state->params.nth) {
ggml_compute_forward(&state->params, state->node);
}
state->node = NULL;
} else {
break;
}
}
return 0;
}
void ggml_graph_compute(struct ggml_context * ctx, struct ggml_cgraph * cgraph) {
const int n_threads = cgraph->n_threads;
struct ggml_compute_state_shared state_shared = {
/*.spin =*/ GGML_LOCK_INITIALIZER,
/*.n_threads =*/ n_threads,
/*.n_ready =*/ 0,
/*.has_work =*/ false,
/*.stop =*/ false,
};
struct ggml_compute_state * workers = n_threads > 1 ? alloca(sizeof(struct ggml_compute_state)*(n_threads - 1)) : NULL;
// create thread pool
if (n_threads > 1) {
ggml_lock_init(&state_shared.spin);
atomic_store(&state_shared.has_work, true);
for (int j = 0; j < n_threads - 1; j++) {
workers[j] = (struct ggml_compute_state) {
.thrd = 0,
.params = {
.type = GGML_TASK_COMPUTE,
.ith = j + 1,
.nth = n_threads,
.wsize = cgraph->work ? ggml_nbytes(cgraph->work) : 0,
.wdata = cgraph->work ? cgraph->work->data : NULL,
},
.node = NULL,
.shared = &state_shared,
};
int rc = ggml_thread_create(&workers[j].thrd, NULL, ggml_graph_compute_thread, &workers[j]);
GGML_ASSERT(rc == 0);
UNUSED(rc);
}
}
// initialize tasks + work buffer
{
size_t work_size = 0;
// thread scheduling for the different operations
for (int i = 0; i < cgraph->n_nodes; i++) {
struct ggml_tensor * node = cgraph->nodes[i];
switch (node->op) {
case GGML_OP_DUP:
{
node->n_tasks = 1;
} break;
case GGML_OP_ADD:
{
node->n_tasks = n_threads;
} break;
case GGML_OP_SUB:
case GGML_OP_MUL:
case GGML_OP_DIV:
case GGML_OP_SQR:
case GGML_OP_SQRT:
case GGML_OP_SUM:
case GGML_OP_MEAN:
case GGML_OP_REPEAT:
case GGML_OP_ABS:
case GGML_OP_SGN:
case GGML_OP_NEG:
case GGML_OP_STEP:
case GGML_OP_RELU:
{
node->n_tasks = 1;
} break;
case GGML_OP_GELU:
{
node->n_tasks = n_threads;
} break;
case GGML_OP_SILU:
{
node->n_tasks = n_threads;
} break;
case GGML_OP_NORM:
case GGML_OP_RMS_NORM:
{
node->n_tasks = n_threads;
} break;
case GGML_OP_MUL_MAT:
{
node->n_tasks = n_threads;
// TODO: use different scheduling for different matrix sizes
//const int nr0 = ggml_nrows(node->src0);
//const int nr1 = ggml_nrows(node->src1);
//node->n_tasks = MIN(n_threads, MAX(1, nr0/128));
//printf("nr0 = %8d, nr1 = %8d, nr0*nr1 = %8d, n_tasks = %d\n", nr0, nr1, nr0*nr1, node->n_tasks);
size_t cur = 0;
if (node->src0->type == GGML_TYPE_F16 && node->src1->type == GGML_TYPE_F32) {
#if defined(GGML_USE_ACCELERATE) || defined(GGML_USE_OPENBLAS)
if (ggml_compute_forward_mul_mat_use_blas(node->src0, node->src1, node)) {
node->n_tasks = 1; // TODO: this actually is doing nothing
// the threads are still spinning
cur = GGML_TYPE_SIZE[GGML_TYPE_F32]*(node->src0->ne[0]*node->src0->ne[1]);
//printf("src0: ne0 = %d, ne1 = %d, ne = %d\n", node->src0->ne[0], node->src0->ne[1], node->src0->ne[0]*node->src0->ne[1]);
//printf("src1: ne0 = %d, ne1 = %d, ne = %d\n", node->src1->ne[0], node->src1->ne[1], node->src1->ne[0]*node->src1->ne[1]);
//printf("cur = %zu\n", cur);
} else {
cur = GGML_TYPE_SIZE[GGML_TYPE_F16]*ggml_nelements(node->src1);
}
#else
cur = GGML_TYPE_SIZE[GGML_TYPE_F16]*ggml_nelements(node->src1);
#endif
} else if (node->src0->type == GGML_TYPE_F32 && node->src1->type == GGML_TYPE_F32) {
cur = 0;
} else if (quantize_fns[node->src0->type].vec_dot_q && node->src1->type == GGML_TYPE_F32) {
#if defined(GGML_USE_ACCELERATE) || defined(GGML_USE_OPENBLAS)
if (ggml_compute_forward_mul_mat_use_blas(node->src0, node->src1, node)) {
node->n_tasks = 1;
cur = GGML_TYPE_SIZE[GGML_TYPE_F32]*(node->src0->ne[0]*node->src0->ne[1]);
} else
#endif
{
cur = GGML_TYPE_SIZE[node->src0->type]*ggml_nelements(node->src1)/GGML_BLCK_SIZE[node->src0->type];
}
} else {
GGML_ASSERT(false);
}
work_size = MAX(work_size, cur);
} break;
case GGML_OP_SCALE:
{
node->n_tasks = n_threads;
} break;
case GGML_OP_CPY:
case GGML_OP_RESHAPE:
case GGML_OP_VIEW:
case GGML_OP_PERMUTE:
case GGML_OP_TRANSPOSE:
case GGML_OP_GET_ROWS:
case GGML_OP_DIAG_MASK_INF:
{
node->n_tasks = 1;
} break;
case GGML_OP_SOFT_MAX:
{
node->n_tasks = n_threads;
} break;
case GGML_OP_ROPE:
{
node->n_tasks = 1;
} break;
case GGML_OP_CONV_1D_1S:
case GGML_OP_CONV_1D_2S:
{
node->n_tasks = n_threads;
GGML_ASSERT(node->src0->ne[3] == 1);
GGML_ASSERT(node->src1->ne[2] == 1);
GGML_ASSERT(node->src1->ne[3] == 1);
size_t cur = 0;
const int nk = node->src0->ne[0];
if (node->src0->type == GGML_TYPE_F16 &&
node->src1->type == GGML_TYPE_F32) {
cur = sizeof(ggml_fp16_t)*(
nk*ggml_up32(node->src0->ne[1])*node->src0->ne[2] +
( 2*(nk/2) + node->src1->ne[0])*node->src1->ne[1]
);
} else if (node->src0->type == GGML_TYPE_F32 &&
node->src1->type == GGML_TYPE_F32) {
cur = sizeof(float)*(
nk*ggml_up32(node->src0->ne[1])*node->src0->ne[2] +
( 2*(nk/2) + node->src1->ne[0])*node->src1->ne[1]
);
} else {
GGML_ASSERT(false);
}
work_size = MAX(work_size, cur);
} break;
case GGML_OP_FLASH_ATTN:
{
node->n_tasks = n_threads;
size_t cur = 0;
const int ne11 = ggml_up(node->src1->ne[1], GGML_SOFT_MAX_UNROLL);
if (node->src1->type == GGML_TYPE_F32) {
cur = sizeof(float)*ne11*node->n_tasks; // TODO: this can become (n_tasks-1)
cur += sizeof(float)*ne11*node->n_tasks; // this is overestimated by x2
}
if (node->src1->type == GGML_TYPE_F16) {
cur = sizeof(float)*ne11*node->n_tasks; // TODO: this can become (n_tasks-1)
cur += sizeof(float)*ne11*node->n_tasks; // this is overestimated by x2
}
work_size = MAX(work_size, cur);
} break;
case GGML_OP_FLASH_FF:
{
node->n_tasks = n_threads;
size_t cur = 0;
if (node->src1->type == GGML_TYPE_F32) {
cur = sizeof(float)*node->src1->ne[1]*node->n_tasks; // TODO: this can become (n_tasks-1)
cur += sizeof(float)*node->src1->ne[1]*node->n_tasks; // this is overestimated by x2
}
if (node->src1->type == GGML_TYPE_F16) {
cur = sizeof(float)*node->src1->ne[1]*node->n_tasks; // TODO: this can become (n_tasks-1)
cur += sizeof(float)*node->src1->ne[1]*node->n_tasks; // this is overestimated by x2
}
work_size = MAX(work_size, cur);
} break;
case GGML_OP_NONE:
{
node->n_tasks = 1;
} break;
case GGML_OP_COUNT:
{
GGML_ASSERT(false);
} break;
}
}
if (cgraph->work != NULL && work_size > cgraph->work_size) {
GGML_ASSERT(false); // TODO: better handling
}
if (work_size > 0 && cgraph->work == NULL) {
cgraph->work_size = work_size + CACHE_LINE_SIZE*(n_threads - 1);
GGML_PRINT_DEBUG("%s: allocating work buffer for graph (%zu bytes)\n", __func__, cgraph->work_size);
cgraph->work = ggml_new_tensor_1d(ctx, GGML_TYPE_I8, cgraph->work_size);
}
}
const int64_t perf_start_cycles = ggml_perf_cycles();
const int64_t perf_start_time_us = ggml_perf_time_us();
for (int i = 0; i < cgraph->n_nodes; i++) {
GGML_PRINT_DEBUG_5("%s: %d/%d\n", __func__, i, cgraph->n_nodes);
struct ggml_tensor * node = cgraph->nodes[i];
// TODO: this could be used to avoid unnecessary computations, but it needs to be improved
//if (node->grad == NULL && node->perf_runs > 0) {
// continue;
//}
const int64_t perf_node_start_cycles = ggml_perf_cycles();
const int64_t perf_node_start_time_us = ggml_perf_time_us();
// INIT
struct ggml_compute_params params = {
/*.type =*/ GGML_TASK_INIT,
/*.ith =*/ 0,
/*.nth =*/ node->n_tasks,
/*.wsize =*/ cgraph->work ? ggml_nbytes(cgraph->work) : 0,
/*.wdata =*/ cgraph->work ? cgraph->work->data : NULL,
};
ggml_compute_forward(¶ms, node);
// COMPUTE
if (node->n_tasks > 1) {
if (atomic_fetch_add(&state_shared.n_ready, 1) == n_threads - 1) {
atomic_store(&state_shared.has_work, false);
}
while (atomic_load(&state_shared.has_work)) {
ggml_lock_lock (&state_shared.spin);
ggml_lock_unlock(&state_shared.spin);
}
// launch thread pool
for (int j = 0; j < n_threads - 1; j++) {
workers[j].params = (struct ggml_compute_params) {
.type = GGML_TASK_COMPUTE,
.ith = j + 1,
.nth = node->n_tasks,
.wsize = cgraph->work ? ggml_nbytes(cgraph->work) : 0,
.wdata = cgraph->work ? cgraph->work->data : NULL,
};
workers[j].node = node;
}
atomic_fetch_sub(&state_shared.n_ready, 1);
while (atomic_load(&state_shared.n_ready) > 0) {
ggml_lock_lock (&state_shared.spin);
ggml_lock_unlock(&state_shared.spin);
}
atomic_store(&state_shared.has_work, true);
}
params.type = GGML_TASK_COMPUTE;
ggml_compute_forward(¶ms, node);
// wait for thread pool
if (node->n_tasks > 1) {
if (atomic_fetch_add(&state_shared.n_ready, 1) == n_threads - 1) {
atomic_store(&state_shared.has_work, false);
}
while (atomic_load(&state_shared.has_work)) {
ggml_lock_lock (&state_shared.spin);
ggml_lock_unlock(&state_shared.spin);
}
atomic_fetch_sub(&state_shared.n_ready, 1);
while (atomic_load(&state_shared.n_ready) != 0) {
ggml_lock_lock (&state_shared.spin);
ggml_lock_unlock(&state_shared.spin);
}
}
// FINALIZE
if (node->n_tasks > 1) {
if (atomic_fetch_add(&state_shared.n_ready, 1) == n_threads - 1) {
atomic_store(&state_shared.has_work, false);
}
while (atomic_load(&state_shared.has_work)) {
ggml_lock_lock (&state_shared.spin);
ggml_lock_unlock(&state_shared.spin);
}
// launch thread pool
for (int j = 0; j < n_threads - 1; j++) {
workers[j].params = (struct ggml_compute_params) {
.type = GGML_TASK_FINALIZE,
.ith = j + 1,
.nth = node->n_tasks,
.wsize = cgraph->work ? ggml_nbytes(cgraph->work) : 0,
.wdata = cgraph->work ? cgraph->work->data : NULL,
};
workers[j].node = node;
}
atomic_fetch_sub(&state_shared.n_ready, 1);
while (atomic_load(&state_shared.n_ready) > 0) {
ggml_lock_lock (&state_shared.spin);
ggml_lock_unlock(&state_shared.spin);
}
atomic_store(&state_shared.has_work, true);
}
params.type = GGML_TASK_FINALIZE;
ggml_compute_forward(¶ms, node);
// wait for thread pool
if (node->n_tasks > 1) {
if (atomic_fetch_add(&state_shared.n_ready, 1) == n_threads - 1) {
atomic_store(&state_shared.has_work, false);
}
while (atomic_load(&state_shared.has_work)) {
ggml_lock_lock (&state_shared.spin);
ggml_lock_unlock(&state_shared.spin);
}
atomic_fetch_sub(&state_shared.n_ready, 1);
while (atomic_load(&state_shared.n_ready) != 0) {
ggml_lock_lock (&state_shared.spin);
ggml_lock_unlock(&state_shared.spin);
}
}
// performance stats (node)
{
int64_t perf_cycles_cur = ggml_perf_cycles() - perf_node_start_cycles;
int64_t perf_time_us_cur = ggml_perf_time_us() - perf_node_start_time_us;
node->perf_runs++;
node->perf_cycles += perf_cycles_cur;
node->perf_time_us += perf_time_us_cur;
}
}
// join thread pool
if (n_threads > 1) {
atomic_store(&state_shared.stop, true);
atomic_store(&state_shared.has_work, true);
for (int j = 0; j < n_threads - 1; j++) {
int rc = ggml_thread_join(workers[j].thrd, NULL);
GGML_ASSERT(rc == 0);
UNUSED(rc);
}
ggml_lock_destroy(&state_shared.spin);
}
// performance stats (graph)
{
int64_t perf_cycles_cur = ggml_perf_cycles() - perf_start_cycles;
int64_t perf_time_us_cur = ggml_perf_time_us() - perf_start_time_us;
cgraph->perf_runs++;
cgraph->perf_cycles += perf_cycles_cur;
cgraph->perf_time_us += perf_time_us_cur;
GGML_PRINT_DEBUG("%s: perf (%d) - cpu = %.3f / %.3f ms, wall = %.3f / %.3f ms\n",
__func__, cgraph->perf_runs,
(double) perf_cycles_cur / (double) ggml_cycles_per_ms(),
(double) cgraph->perf_cycles / (double) ggml_cycles_per_ms() / (double) cgraph->perf_runs,
(double) perf_time_us_cur / 1000.0,
(double) cgraph->perf_time_us / 1000.0 / cgraph->perf_runs);
}
}
void ggml_graph_reset(struct ggml_cgraph * cgraph) {
for (int i = 0; i < cgraph->n_nodes; i++) {
struct ggml_tensor * grad = cgraph->grads[i];
if (grad) {
ggml_set_zero(grad);
}
}
}
void ggml_graph_print(const struct ggml_cgraph * cgraph) {
int64_t perf_total_per_op_us[GGML_OP_COUNT] = {0};
GGML_PRINT("=== GRAPH ===\n");
GGML_PRINT_DEBUG("n_threads = %d\n", cgraph->n_threads);
GGML_PRINT_DEBUG("total work size = %zu bytes\n",cgraph->work_size);
GGML_PRINT("n_nodes = %d\n", cgraph->n_nodes);
for (int i = 0; i < cgraph->n_nodes; i++) {
struct ggml_tensor * node = cgraph->nodes[i];
perf_total_per_op_us[node->op] += node->perf_time_us;
GGML_PRINT(" - %3d: [ %6d, %6d, %6d] %16s %s (%3d) cpu = %7.3f / %7.3f ms, wall = %7.3f / %7.3f ms\n",
i,
node->ne[0], node->ne[1], node->ne[2],
GGML_OP_LABEL[node->op], node->is_param ? "x" : node->grad ? "g" : " ", node->perf_runs,
(double) node->perf_cycles / (double) ggml_cycles_per_ms(),
(double) node->perf_cycles / (double) ggml_cycles_per_ms() / (double) node->perf_runs,
(double) node->perf_time_us / 1000.0,
(double) node->perf_time_us / 1000.0 / node->perf_runs);
}
GGML_PRINT("n_leafs = %d\n", cgraph->n_leafs);
for (int i = 0; i < cgraph->n_leafs; i++) {
struct ggml_tensor * node = cgraph->leafs[i];
GGML_PRINT(" - %3d: [ %6d, %6d] %8s\n",
i,
node->ne[0], node->ne[1],
GGML_OP_LABEL[node->op]);
}
for (int i = 0; i < GGML_OP_COUNT; i++) {
GGML_PRINT("perf_total_per_op_us[%16s] = %7.3f ms\n", GGML_OP_LABEL[i], (double) perf_total_per_op_us[i] / 1000.0);
}
GGML_PRINT("========================================\n");
}
// check if node is part of the graph
static bool ggml_graph_find(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node) {
if (cgraph == NULL) {
return true;
}
for (int i = 0; i < cgraph->n_nodes; i++) {
if (cgraph->nodes[i] == node) {
return true;
}
}
return false;
}
static struct ggml_tensor * ggml_graph_get_parent(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node) {
for (int i = 0; i < cgraph->n_nodes; i++) {
struct ggml_tensor * parent = cgraph->nodes[i];
if (parent->grad == node) {
return parent;
}
}
return NULL;
}
void ggml_graph_dump_dot(const struct ggml_cgraph * gb, const struct ggml_cgraph * gf, const char * filename) {
char color[16];
FILE * fp = fopen(filename, "w");
GGML_ASSERT(fp);
fprintf(fp, "digraph G {\n");
fprintf(fp, " newrank = true;\n");
fprintf(fp, " rankdir = LR;\n");
for (int i = 0; i < gb->n_nodes; i++) {
struct ggml_tensor * node = gb->nodes[i];
if (ggml_graph_get_parent(gb, node) != NULL) {
continue;
}
if (node->is_param) {
snprintf(color, sizeof(color), "yellow");
} else if (node->grad) {
if (ggml_graph_find(gf, node)) {
snprintf(color, sizeof(color), "green");
} else {
snprintf(color, sizeof(color), "lightblue");
}
} else {
snprintf(color, sizeof(color), "white");
}
fprintf(fp, " \"%p\" [ \
style = filled; fillcolor = %s; shape = record; \
label=\"%d [%d, %d] | <x>%s",
(void *) node, color,
i, node->ne[0], node->ne[1],
GGML_OP_SYMBOL[node->op]);
if (node->grad) {
fprintf(fp, " | <g>%s\"; ]\n", GGML_OP_SYMBOL[node->grad->op]);
} else {
fprintf(fp, "\"; ]\n");
}
}
for (int i = 0; i < gb->n_leafs; i++) {
struct ggml_tensor * node = gb->leafs[i];
snprintf(color, sizeof(color), "pink");
if (ggml_nelements(node) == 1) {
fprintf(fp, " \"%p\" [ \
style = filled; fillcolor = %s; shape = record; \
label=\"<x>%.1e\"; ]\n",
(void *) node, color, (double)ggml_get_f32_1d(node, 0));
} else {
fprintf(fp, " \"%p\" [ \
style = filled; fillcolor = %s; shape = record; \
label=\"<x>CONST %d [%d, %d]\"; ]\n",
(void *) node, color,
i, node->ne[0], node->ne[1]);
}
}
for (int i = 0; i < gb->n_nodes; i++) {
struct ggml_tensor * node = gb->nodes[i];
struct ggml_tensor * parent = ggml_graph_get_parent(gb, node);
if (node->src0) {
struct ggml_tensor * parent0 = ggml_graph_get_parent(gb, node->src0);
fprintf(fp, " \"%p\":%s -> \"%p\":%s [ arrowhead = %s; style = %s; label = \"x\"; ]\n",
parent0 ? (void *) parent0 : (void *) node->src0,
parent0 ? "g" : "x",
parent ? (void *) parent : (void *) node,
parent ? "g" : "x",
parent ? "empty" : "vee",
parent ? "dashed" : "solid");
}
if (node->src1) {
struct ggml_tensor * parent1 = ggml_graph_get_parent(gb, node->src1);
fprintf(fp, " \"%p\":%s -> \"%p\":%s [ arrowhead = %s; style = %s; label = \"y\"; ]\n",
parent1 ? (void *) parent1 : (void *) node->src1,
parent1 ? "g" : "x",
parent ? (void *) parent : (void *) node,
parent ? "g" : "x",
parent ? "empty" : "vee",
parent ? "dashed" : "solid");
}
}
for (int i = 0; i < gb->n_leafs; i++) {
struct ggml_tensor * node = gb->leafs[i];
if (node->src0) {
fprintf(fp, " \"%p\":%s -> \"%p\":%s [ label = \"x\"; ]\n",
(void *) node->src0, "x",
(void *) node, "x");
}
if (node->src1) {
fprintf(fp, " \"%p\":%s -> \"%p\":%s [ label = \"y\"; ]\n",
(void *) node->src1, "x",
(void *) node, "x");
}
}
fprintf(fp, "}\n");
fclose(fp);
GGML_PRINT("%s: dot -Tpng %s -o %s.png && open %s.png\n", __func__, filename, filename, filename);
}
////////////////////////////////////////////////////////////////////////////////
static void ggml_opt_set_params(int np, struct ggml_tensor * const ps[], const float * x) {
int i = 0;
for (int p = 0; p < np; ++p) {
const int ne = ggml_nelements(ps[p]) ;
// TODO: add function to set tensor from array
for (int j = 0; j < ne; ++j) {
ggml_set_f32_1d(ps[p], j, x[i++]);
}
}
}
static void ggml_opt_get_params(int np, struct ggml_tensor * const ps[], float * x) {
int i = 0;
for (int p = 0; p < np; ++p) {
const int ne = ggml_nelements(ps[p]) ;
// TODO: add function to get all elements at once
for (int j = 0; j < ne; ++j) {
x[i++] = ggml_get_f32_1d(ps[p], j);
}
}
}
static void ggml_opt_get_grad(int np, struct ggml_tensor * const ps[], float * g) {
int i = 0;
for (int p = 0; p < np; ++p) {
const int ne = ggml_nelements(ps[p]) ;
// TODO: add function to get all elements at once
for (int j = 0; j < ne; ++j) {
g[i++] = ggml_get_f32_1d(ps[p]->grad, j);
}
}
}
//
// ADAM
//
// ref: https://arxiv.org/pdf/1412.6980.pdf
//
static enum ggml_opt_result ggml_opt_adam(
struct ggml_context * ctx,
struct ggml_opt_params params,
struct ggml_tensor * f,
struct ggml_cgraph * gf,
struct ggml_cgraph * gb) {
GGML_ASSERT(ggml_is_scalar(f));
gf->n_threads = params.n_threads;
gb->n_threads = params.n_threads;
// these will store the parameters we want to optimize
struct ggml_tensor * ps[GGML_MAX_PARAMS];
int np = 0;
int nx = 0;
for (int i = 0; i < gf->n_nodes; ++i) {
if (gf->nodes[i]->is_param) {
GGML_PRINT_DEBUG("found param %d: grad->op = %d\n", np, gf->nodes[i]->grad->op);
GGML_ASSERT(np < GGML_MAX_PARAMS);
ps[np++] = gf->nodes[i];
nx += ggml_nelements(gf->nodes[i]);
}
}
// constants
const float alpha = params.adam.alpha;
const float beta1 = params.adam.beta1;
const float beta2 = params.adam.beta2;
const float eps = params.adam.eps;
float * x = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // view of the parameters
float * g1 = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // gradient
float * g2 = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // gradient squared
float * m = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // first moment
float * v = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // second moment
float * mh = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // first moment hat
float * vh = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // second moment hat
float * pf = params.past > 0 ? ggml_new_tensor_1d(ctx, GGML_TYPE_F32, params.past)->data : NULL; // past function values
// initialize
ggml_vec_set_f32(nx, m, 0.0f);
ggml_vec_set_f32(nx, v, 0.0f);
// update view
ggml_opt_get_params(np, ps, x);
// compute the function value
ggml_graph_reset (gf);
ggml_set_f32 (f->grad, 1.0f);
ggml_graph_compute(ctx, gb);
float fx_prev = ggml_get_f32_1d(f, 0);
if (pf) {
pf[0] = fx_prev;
}
int n_no_improvement = 0;
float fx_best = fx_prev;
// run the optimizer
for (int t = 0; t < params.adam.n_iter; ++t) {
GGML_PRINT_DEBUG ("=== iter %d ===\n", t);
GGML_PRINT_DEBUG ("f = %10.6f\n", ggml_get_f32_1d(f, 0));
GGML_PRINT_DEBUG_5("df/dx0 = %10.6f\n", ggml_get_f32_1d(ps[0]->grad, 0));
GGML_PRINT_DEBUG_5("df/dx1 = %10.6f\n", ggml_get_f32_1d(ps[1]->grad, 0));
for (int i = 0; i < np; ++i) {
GGML_PRINT_DEBUG("param %d: %10.6f, g = %10.6f\n", i,
ggml_get_f32_1d(ps[i], 0), ggml_get_f32_1d(ps[i]->grad, 0));
}
const int64_t t_start_wall = ggml_time_us();
const int64_t t_start_cpu = ggml_cycles();
UNUSED(t_start_wall);
UNUSED(t_start_cpu);
{
// update the gradient
ggml_opt_get_grad(np, ps, g1);
// m_t = beta1*m_t-1 + (1 - beta1)*g_t
ggml_vec_scale_f32(nx, m, beta1);
ggml_vec_mad_f32 (nx, m, g1, 1.0f - beta1);
// g2 = g1^2
ggml_vec_sqr_f32 (nx, g2, g1);
// v_t = beta2*v_t-1 + (1 - beta2)*g_t^2
ggml_vec_scale_f32(nx, v, beta2);
ggml_vec_mad_f32 (nx, v, g2, 1.0f - beta2);
// m^hat = m_t / (1 - beta1^t)
// v^hat = v_t / (1 - beta2^t)
// x_t = x_t-1 - alpha*m^hat/(sqrt(v^hat) + eps)
ggml_vec_cpy_f32 (nx, mh, m);
ggml_vec_cpy_f32 (nx, vh, v);
ggml_vec_scale_f32(nx, mh, alpha/(1.0f - powf(beta1, t + 1)));
ggml_vec_scale_f32(nx, vh, 1.0f/(1.0f - powf(beta2, t + 1)));
ggml_vec_sqrt_f32 (nx, vh, vh);
ggml_vec_acc1_f32 (nx, vh, eps);
ggml_vec_div_f32 (nx, mh, mh, vh);
ggml_vec_sub_f32 (nx, x, x, mh);
// update the parameters
ggml_opt_set_params(np, ps, x);
}
ggml_graph_reset (gf);
ggml_set_f32 (f->grad, 1.0f);
ggml_graph_compute(ctx, gb);
const float fx = ggml_get_f32_1d(f, 0);
// check convergence
if (fabsf(fx - fx_prev)/fx < params.adam.eps_f) {
GGML_PRINT_DEBUG("converged\n");
return GGML_OPT_OK;
}
// delta-based convergence test
if (pf != NULL) {
// need at least params.past iterations to start checking for convergence
if (params.past <= t) {
const float rate = (pf[t%params.past] - fx)/fx;
if (fabsf(rate) < params.delta) {
return GGML_OPT_OK;
}
}
pf[t%params.past] = fx;
}
// check for improvement
if (params.max_no_improvement > 0) {
if (fx_best > fx) {
fx_best = fx;
n_no_improvement = 0;
} else {
++n_no_improvement;
if (n_no_improvement >= params.max_no_improvement) {
return GGML_OPT_OK;
}
}
}
fx_prev = fx;
{
const int64_t t_end_cpu = ggml_cycles();
GGML_PRINT_DEBUG("time iter: %5.3f s\n", ((float)(t_end_cpu - t_start_cpu))/CLOCKS_PER_SEC);
UNUSED(t_end_cpu);
const int64_t t_end_wall = ggml_time_us();
GGML_PRINT_DEBUG("wall time iter: %5.3f s\n", (t_end_wall - t_start_wall)/1e6);
UNUSED(t_end_wall);
}
}
return GGML_OPT_DID_NOT_CONVERGE;
}
//
// L-BFGS
//
// the L-BFGS implementation below is based on the following implementation:
//
// https://github.com/chokkan/liblbfgs
//
struct ggml_lbfgs_iteration_data {
float alpha;
float ys;
float * s;
float * y;
};
static enum ggml_opt_result linesearch_backtracking(
struct ggml_context * ctx,
const struct ggml_opt_params * params,
int nx,
float * x,
float * fx,
float * g,
float * d,
float * step,
const float * xp,
struct ggml_tensor * f,
struct ggml_cgraph * gf,
struct ggml_cgraph * gb,
const int np,
struct ggml_tensor * ps[]) {
int count = 0;
float width = 0.0f;
float dg = 0.0f;
float finit = 0.0f;
float dginit = 0.0f;
float dgtest = 0.0f;
const float dec = 0.5f;
const float inc = 2.1f;
if (*step <= 0.f) {
return GGML_LINESEARCH_INVALID_PARAMETERS;
}
// compute the initial gradient in the search direction
ggml_vec_dot_f32(nx, &dginit, g, d);
// make sure that d points to a descent direction
if (0 < dginit) {
return GGML_LINESEARCH_FAIL;
}
// initialize local variables
finit = *fx;
dgtest = params->lbfgs.ftol*dginit;
while (true) {
ggml_vec_cpy_f32(nx, x, xp);
ggml_vec_mad_f32(nx, x, d, *step);
// evaluate the function and gradient values
{
ggml_opt_set_params(np, ps, x);
ggml_graph_reset (gf);
ggml_set_f32 (f->grad, 1.0f);
ggml_graph_compute(ctx, gb);
ggml_opt_get_grad(np, ps, g);
*fx = ggml_get_f32_1d(f, 0);
}
++count;
if (*fx > finit + (*step)*dgtest) {
width = dec;
} else {
// Armijo condition is satisfied
if (params->lbfgs.linesearch == GGML_LINESEARCH_BACKTRACKING_ARMIJO) {
return count;
}
ggml_vec_dot_f32(nx, &dg, g, d);
// check the Wolfe condition
if (dg < params->lbfgs.wolfe * dginit) {
width = inc;
} else {
if(params->lbfgs.linesearch == GGML_LINESEARCH_BACKTRACKING_WOLFE) {
// regular Wolfe conditions
return count;
}
if(dg > -params->lbfgs.wolfe*dginit) {
width = dec;
} else {
// strong Wolfe condition (GGML_LINESEARCH_BACKTRACKING_STRONG_WOLFE)
return count;
}
return count;
}
}
if (*step < params->lbfgs.min_step) {
return GGML_LINESEARCH_MINIMUM_STEP;
}
if (*step > params->lbfgs.max_step) {
return GGML_LINESEARCH_MAXIMUM_STEP;
}
if (params->lbfgs.max_linesearch <= count) {
return GGML_LINESEARCH_MAXIMUM_ITERATIONS;
}
(*step) *= width;
}
return GGML_LINESEARCH_FAIL;
}
static enum ggml_opt_result ggml_opt_lbfgs(
struct ggml_context * ctx,
struct ggml_opt_params params,
struct ggml_tensor * f,
struct ggml_cgraph * gf,
struct ggml_cgraph * gb) {
if (params.lbfgs.linesearch == GGML_LINESEARCH_BACKTRACKING_WOLFE ||
params.lbfgs.linesearch == GGML_LINESEARCH_BACKTRACKING_STRONG_WOLFE) {
if (params.lbfgs.wolfe <= params.lbfgs.ftol || 1.f <= params.lbfgs.wolfe) {
return GGML_OPT_INVALID_WOLFE;
}
}
gf->n_threads = params.n_threads;
gb->n_threads = params.n_threads;
const int m = params.lbfgs.m;
// these will store the parameters we want to optimize
struct ggml_tensor * ps[GGML_MAX_PARAMS];
int np = 0;
int nx = 0;
for (int i = 0; i < gf->n_nodes; ++i) {
if (gf->nodes[i]->is_param) {
GGML_PRINT_DEBUG("found param %d: grad->op = %d\n", np, gf->nodes[i]->grad->op);
GGML_ASSERT(np < GGML_MAX_PARAMS);
ps[np++] = gf->nodes[i];
nx += ggml_nelements(gf->nodes[i]);
}
}
float * x = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // current parameters
float * xp = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // previous parameters
float * g = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // current gradient
float * gp = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // previous gradient
float * d = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data; // search direction
float * pf = params.past > 0 ? ggml_new_tensor_1d(ctx, GGML_TYPE_F32, params.past)->data : NULL; // past function values
float fx = 0.0f; // cost function value
float xnorm = 0.0f; // ||x||
float gnorm = 0.0f; // ||g||
float step = 0.0f;
// initialize x from the graph nodes
ggml_opt_get_params(np, ps, x);
// the L-BFGS memory
struct ggml_lbfgs_iteration_data * lm = alloca(sizeof(struct ggml_lbfgs_iteration_data)*m);
for (int i = 0; i < m; ++i) {
lm[i].alpha = 0.0f;
lm[i].ys = 0.0f;
lm[i].s = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data;
lm[i].y = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nx)->data;
}
// evaluate the function value and its gradient
{
ggml_opt_set_params(np, ps, x);
ggml_graph_reset (gf);
ggml_set_f32 (f->grad, 1.0f);
ggml_graph_compute(ctx, gb);
ggml_opt_get_grad(np, ps, g);
fx = ggml_get_f32_1d(f, 0);
}
if (pf) {
pf[0] = fx;
}
float fx_best = fx;
// search direction = -gradient
ggml_vec_neg_f32(nx, d, g);
// ||x||, ||g||
ggml_vec_norm_f32(nx, &xnorm, x);
ggml_vec_norm_f32(nx, &gnorm, g);
if (xnorm < 1.0f) {
xnorm = 1.0f;
}
// already optimized
if (gnorm/xnorm <= params.lbfgs.eps) {
return GGML_OPT_OK;
}
// initial step
ggml_vec_norm_inv_f32(nx, &step, d);
int j = 0;
int k = 1;
int ls = 0;
int end = 0;
int bound = 0;
int n_no_improvement = 0;
float ys = 0.0f;
float yy = 0.0f;
float beta = 0.0f;
while (true) {
// store the current position and gradient vectors
ggml_vec_cpy_f32(nx, xp, x);
ggml_vec_cpy_f32(nx, gp, g);
ls = linesearch_backtracking(ctx, ¶ms, nx, x, &fx, g, d, &step, xp, f, gf, gb, np, ps);
if (ls < 0) {
// linesearch failed - go back to the previous point and return
ggml_vec_cpy_f32(nx, x, xp);
ggml_vec_cpy_f32(nx, g, gp);
return ls;
}
ggml_vec_norm_f32(nx, &xnorm, x);
ggml_vec_norm_f32(nx, &gnorm, g);
GGML_PRINT_DEBUG("f = %10.6f\n", ggml_get_f32_1d(f, 0));
if (xnorm < 1.0f) {
xnorm = 1.0f;
}
if (gnorm/xnorm <= params.lbfgs.eps) {
// converged
return GGML_OPT_OK;
}
// delta-based convergence test
if (pf != NULL) {
// need at least params.past iterations to start checking for convergence
if (params.past <= k) {
const float rate = (pf[k%params.past] - fx)/fx;
if (fabsf(rate) < params.delta) {
return GGML_OPT_OK;
}
}
pf[k%params.past] = fx;
}
// check for improvement
if (params.max_no_improvement > 0) {
if (fx < fx_best) {
fx_best = fx;
n_no_improvement = 0;
} else {
n_no_improvement++;
if (n_no_improvement >= params.max_no_improvement) {
return GGML_OPT_OK;
}
}
}
if (params.lbfgs.n_iter != 0 && params.lbfgs.n_iter < k + 1) {
// reached the maximum number of iterations
return GGML_OPT_DID_NOT_CONVERGE;
}
// update vectors s and y:
// s_{k+1} = x_{k+1} - x_{k} = \step * d_{k}.
// y_{k+1} = g_{k+1} - g_{k}.
//
ggml_vec_sub_f32(nx, lm[end].s, x, xp);
ggml_vec_sub_f32(nx, lm[end].y, g, gp);
// compute scalars ys and yy:
// ys = y^t \cdot s -> 1 / \rho.
// yy = y^t \cdot y.
//
ggml_vec_dot_f32(nx, &ys, lm[end].y, lm[end].s);
ggml_vec_dot_f32(nx, &yy, lm[end].y, lm[end].y);
lm[end].ys = ys;
// find new search direction
// ref: https://en.wikipedia.org/wiki/Limited-memory_BFGS
bound = (m <= k) ? m : k;
k++;
end = (end + 1)%m;
// initialize search direction with -g
ggml_vec_neg_f32(nx, d, g);
j = end;
for (int i = 0; i < bound; ++i) {
j = (j + m - 1) % m;
// \alpha_{j} = \rho_{j} s^{t}_{j} \cdot q_{k+1}
ggml_vec_dot_f32(nx, &lm[j].alpha, lm[j].s, d);
lm[j].alpha /= lm[j].ys;
// q_{i} = q_{i+1} - \alpha_{i} y_{i}
ggml_vec_mad_f32(nx, d, lm[j].y, -lm[j].alpha);
}
ggml_vec_scale_f32(nx, d, ys/yy);
for (int i = 0; i < bound; ++i) {
// \beta_{j} = \rho_{j} y^t_{j} \cdot \gamma_{i}
ggml_vec_dot_f32(nx, &beta, lm[j].y, d);
beta /= lm[j].ys;
// \gamma_{i+1} = \gamma_{i} + (\alpha_{j} - \beta_{j}) s_{j}
ggml_vec_mad_f32(nx, d, lm[j].s, lm[j].alpha - beta);
j = (j + 1)%m;
}
step = 1.0;
}
return GGML_OPT_DID_NOT_CONVERGE;
}
struct ggml_opt_params ggml_opt_default_params(enum ggml_opt_type type) {
struct ggml_opt_params result;
switch (type) {
case GGML_OPT_ADAM:
{
result = (struct ggml_opt_params) {
.type = GGML_OPT_ADAM,
.n_threads = 1,
.past = 0,
.delta = 1e-5f,
.max_no_improvement = 100,
.print_forward_graph = true,
.print_backward_graph = true,
.adam = {
.n_iter = 10000,
.alpha = 0.001f,
.beta1 = 0.9f,
.beta2 = 0.999f,
.eps = 1e-8f,
.eps_f = 1e-5f,
.eps_g = 1e-3f,
},
};
} break;
case GGML_OPT_LBFGS:
{
result = (struct ggml_opt_params) {
.type = GGML_OPT_LBFGS,
.n_threads = 1,
.past = 0,
.delta = 1e-5f,
.max_no_improvement = 0,
.print_forward_graph = true,
.print_backward_graph = true,
.lbfgs = {
.m = 6,
.n_iter = 100,
.max_linesearch = 20,
.eps = 1e-5f,
.ftol = 1e-4f,
.wolfe = 0.9f,
.min_step = 1e-20f,
.max_step = 1e+20f,
.linesearch = GGML_LINESEARCH_DEFAULT,
},
};
} break;
}
return result;
}
enum ggml_opt_result ggml_opt(
struct ggml_context * ctx,
struct ggml_opt_params params,
struct ggml_tensor * f) {
bool free_ctx = false;
if (ctx == NULL) {
struct ggml_init_params params_ctx = {
.mem_size = 16*1024*1024,
.mem_buffer = NULL,
};
ctx = ggml_init(params_ctx);
if (ctx == NULL) {
return GGML_OPT_NO_CONTEXT;
}
free_ctx = true;
}
enum ggml_opt_result result = GGML_OPT_OK;
// build forward + backward compute graphs
struct ggml_cgraph gf = ggml_build_forward (f);
struct ggml_cgraph gb = ggml_build_backward(ctx, &gf, false);
switch (params.type) {
case GGML_OPT_ADAM:
{
result = ggml_opt_adam(ctx, params, f, &gf, &gb);
} break;
case GGML_OPT_LBFGS:
{
result = ggml_opt_lbfgs(ctx, params, f, &gf, &gb);
} break;
}
if (params.print_forward_graph) {
ggml_graph_print (&gf);
ggml_graph_dump_dot(&gf, NULL, "opt-forward.dot");
}
if (params.print_backward_graph) {
ggml_graph_print (&gb);
ggml_graph_dump_dot(&gb, &gf, "opt-backward.dot");
}
if (free_ctx) {
ggml_free(ctx);
}
return result;
}
////////////////////////////////////////////////////////////////////////////////
size_t ggml_quantize_q4_0(const float * src, void * dst, int n, int k, int64_t * hist) {
assert(k % QK == 0);
const int nb = k / QK;
for (int j = 0; j < n; j += k) {
block_q4_0 * restrict y = (block_q4_0 *)dst + j/QK;
quantize_row_q4_0_reference(src + j, y, k);
for (int i = 0; i < nb; i++) {
for (int l = 0; l < QK; l += 2) {
const uint8_t vi0 = y[i].qs[l/2] & 0xF;
const uint8_t vi1 = y[i].qs[l/2] >> 4;
hist[vi0]++;
hist[vi1]++;
}
}
}
return (n/QK*sizeof(block_q4_0));
}
size_t ggml_quantize_q4_1(const float * src, void * dst, int n, int k, int64_t * hist) {
assert(k % QK == 0);
const int nb = k / QK;
for (int j = 0; j < n; j += k) {
block_q4_1 * restrict y = (block_q4_1 *)dst + j/QK;
quantize_row_q4_1_reference(src + j, y, k);
for (int i = 0; i < nb; i++) {
for (int l = 0; l < QK; l += 2) {
const uint8_t vi0 = y[i].qs[l/2] & 0xF;
const uint8_t vi1 = y[i].qs[l/2] >> 4;
hist[vi0]++;
hist[vi1]++;
}
}
}
return (n/QK*sizeof(block_q4_1));
}
////////////////////////////////////////////////////////////////////////////////
int ggml_cpu_has_avx(void) {
#if defined(__AVX__)
return 1;
#else
return 0;
#endif
}
int ggml_cpu_has_avx2(void) {
#if defined(__AVX2__)
return 1;
#else
return 0;
#endif
}
int ggml_cpu_has_avx512(void) {
#if defined(__AVX512F__)
return 1;
#else
return 0;
#endif
}
int ggml_cpu_has_fma(void) {
#if defined(__FMA__)
return 1;
#else
return 0;
#endif
}
int ggml_cpu_has_neon(void) {
#if defined(__ARM_NEON)
return 1;
#else
return 0;
#endif
}
int ggml_cpu_has_arm_fma(void) {
#if defined(__ARM_FEATURE_FMA)
return 1;
#else
return 0;
#endif
}
int ggml_cpu_has_f16c(void) {
#if defined(__F16C__)
return 1;
#else
return 0;
#endif
}
int ggml_cpu_has_fp16_va(void) {
#if defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC)
return 1;
#else
return 0;
#endif
}
int ggml_cpu_has_wasm_simd(void) {
#if defined(__wasm_simd128__)
return 1;
#else
return 0;
#endif
}
int ggml_cpu_has_blas(void) {
#if defined(GGML_USE_ACCELERATE) || defined(GGML_USE_OPENBLAS)
return 1;
#else
return 0;
#endif
}
int ggml_cpu_has_sse3(void) {
#if defined(__SSE3__)
return 1;
#else
return 0;
#endif
}
int ggml_cpu_has_vsx(void) {
#if defined(__POWER9_VECTOR__)
return 1;
#else
return 0;
#endif
}
////////////////////////////////////////////////////////////////////////////////
|
0 | repos/gpt4all.zig/src | repos/gpt4all.zig/src/zig-libcurl/libcurl.zig | const std = @import("std");
fn root() []const u8 {
return std.fs.path.dirname(@src().file) orelse ".";
}
const root_path = root() ++ "/";
pub const include_dir = root_path ++ "curl/include";
const package_path = root_path ++ "src/main.zig";
const lib_dir = root_path ++ "curl/lib";
pub const Define = struct {
key: []const u8,
value: ?[]const u8,
};
pub const Options = struct {
import_name: ?[]const u8 = null,
};
pub const Library = struct {
exported_defines: []Define,
step: *std.build.LibExeObjStep,
pub fn link(self: Library, other: *std.build.LibExeObjStep, opts: Options) void {
for (self.exported_defines) |def|
other.defineCMacro(def.key, def.value);
other.addIncludePath(.{ .path = include_dir });
other.linkLibrary(self.step);
if (opts.import_name) |import_name|
other.addAnonymousModule(
import_name,
.{ .source_file = .{ .path = package_path } },
);
}
};
pub fn create(
b: *std.build.Builder,
target: std.zig.CrossTarget,
optimize: std.builtin.OptimizeMode,
) !Library {
const ret = b.addStaticLibrary(.{
.name = "curl",
.target = target,
.optimize = optimize,
});
ret.addCSourceFiles(srcs, &.{});
ret.addIncludePath(.{ .path = include_dir });
ret.addIncludePath(.{ .path = lib_dir });
ret.linkLibC();
var exported_defines = std.ArrayList(Define).init(b.allocator);
defer exported_defines.deinit();
ret.defineCMacro("BUILDING_LIBCURL", null);
// when not building a shared library
ret.defineCMacro("CURL_STATICLIB", "1");
try exported_defines.append(.{ .key = "CURL_STATICLIB", .value = "1" });
// disables LDAP
ret.defineCMacro("CURL_DISABLE_LDAP", "1");
// disables LDAPS
ret.defineCMacro("CURL_DISABLE_LDAPS", "1");
// if mbedTLS is enabled
ret.defineCMacro("USE_MBEDTLS", "1");
// disables alt-svc
// #undef CURL_DISABLE_ALTSVC
// disables cookies support
// #undef CURL_DISABLE_COOKIES
// disables cryptographic authentication
// #undef CURL_DISABLE_CRYPTO_AUTH
// disables DICT
ret.defineCMacro("CURL_DISABLE_DICT", "1");
// disables DNS-over-HTTPS
// #undef CURL_DISABLE_DOH
// disables FILE
ret.defineCMacro("CURL_DISABLE_FILE", "1");
// disables FTP
ret.defineCMacro("CURL_DISABLE_FTP", "1");
// disables GOPHER
ret.defineCMacro("CURL_DISABLE_GOPHER", "1");
// disables HSTS support
// #undef CURL_DISABLE_HSTS
// disables HTTP
// #undef CURL_DISABLE_HTTP
// disables IMAP
ret.defineCMacro("CURL_DISABLE_IMAP", "1");
// disables --libcurl option from the curl tool
// #undef CURL_DISABLE_LIBCURL_OPTION
// disables MIME support
// #undef CURL_DISABLE_MIME
// disables MQTT
ret.defineCMacro("CURL_DISABLE_MQTT", "1");
// disables netrc parser
// #undef CURL_DISABLE_NETRC
// disables NTLM support
// #undef CURL_DISABLE_NTLM
// disables date parsing
// #undef CURL_DISABLE_PARSEDATE
// disables POP3
ret.defineCMacro("CURL_DISABLE_POP3", "1");
// disables built-in progress meter
// #undef CURL_DISABLE_PROGRESS_METER
// disables proxies
// #undef CURL_DISABLE_PROXY
// disables RTSP
ret.defineCMacro("CURL_DISABLE_RTSP", "1");
// disables SMB
ret.defineCMacro("CURL_DISABLE_SMB", "1");
// disables SMTP
ret.defineCMacro("CURL_DISABLE_SMTP", "1");
// disables use of socketpair for curl_multi_poll
// #undef CURL_DISABLE_SOCKETPAIR
// disables TELNET
ret.defineCMacro("CURL_DISABLE_TELNET", "1");
// disables TFTP
ret.defineCMacro("CURL_DISABLE_TFTP", "1");
// disables verbose strings
// #undef CURL_DISABLE_VERBOSE_STRINGS
// Define to 1 if you have the `ssh2' library (-lssh2).
// ret.defineCMacro("HAVE_LIBSSH2", "1");
// Define to 1 if you have the <libssh2.h> header file.
// ret.defineCMacro("HAVE_LIBSSH2_H", "1");
// if zlib is available
ret.defineCMacro("HAVE_LIBZ", "1");
// if you have the zlib.h header file
ret.defineCMacro("HAVE_ZLIB_H", "1");
if (target.isWindows()) {
// Define if you want to enable WIN32 threaded DNS lookup
//ret.defineCMacro("USE_THREADS_WIN32", "1");
return Library{ .step = ret, .exported_defines = try exported_defines.toOwnedSlice() };
}
//ret.defineCMacro("libcurl_EXPORTS", null);
//ret.defineCMacro("STDC_HEADERS", null);
// when building libcurl itself
// #undef BUILDING_LIBCURL
// Location of default ca bundle
// ret.defineCMacro("CURL_CA_BUNDLE", "\"/etc/ssl/certs/ca-certificates.crt\"");
// define "1" to use built-in ca store of TLS backend
// #undef CURL_CA_FALLBACK
// Location of default ca path
// ret.defineCMacro("CURL_CA_PATH", "\"/etc/ssl/certs\"");
// to make a symbol visible
ret.defineCMacro("CURL_EXTERN_SYMBOL", "__attribute__ ((__visibility__ (\"default\"))");
// Ensure using CURL_EXTERN_SYMBOL is possible
//#ifndef CURL_EXTERN_SYMBOL
//ret.defineCMacro("CURL_EXTERN_SYMBOL
//#endif
// Allow SMB to work on Windows
// #undef USE_WIN32_CRYPTO
// Use Windows LDAP implementation
// #undef USE_WIN32_LDAP
// your Entropy Gathering Daemon socket pathname
// #undef EGD_SOCKET
// Define if you want to enable IPv6 support
if (!target.isDarwin())
ret.defineCMacro("ENABLE_IPV6", "1");
// Define to 1 if you have the alarm function.
ret.defineCMacro("HAVE_ALARM", "1");
// Define to 1 if you have the <alloca.h> header file.
ret.defineCMacro("HAVE_ALLOCA_H", "1");
// Define to 1 if you have the <arpa/inet.h> header file.
ret.defineCMacro("HAVE_ARPA_INET_H", "1");
// Define to 1 if you have the <arpa/tftp.h> header file.
ret.defineCMacro("HAVE_ARPA_TFTP_H", "1");
// Define to 1 if you have the <assert.h> header file.
ret.defineCMacro("HAVE_ASSERT_H", "1");
// Define to 1 if you have the `basename' function.
ret.defineCMacro("HAVE_BASENAME", "1");
// Define to 1 if bool is an available type.
ret.defineCMacro("HAVE_BOOL_T", "1");
// Define to 1 if you have the __builtin_available function.
ret.defineCMacro("HAVE_BUILTIN_AVAILABLE", "1");
// Define to 1 if you have the clock_gettime function and monotonic timer.
ret.defineCMacro("HAVE_CLOCK_GETTIME_MONOTONIC", "1");
// Define to 1 if you have the `closesocket' function.
// #undef HAVE_CLOSESOCKET
// Define to 1 if you have the `CRYPTO_cleanup_all_ex_data' function.
// #undef HAVE_CRYPTO_CLEANUP_ALL_EX_DATA
// Define to 1 if you have the <dlfcn.h> header file.
ret.defineCMacro("HAVE_DLFCN_H", "1");
// Define to 1 if you have the <errno.h> header file.
ret.defineCMacro("HAVE_ERRNO_H", "1");
// Define to 1 if you have the fcntl function.
ret.defineCMacro("HAVE_FCNTL", "1");
// Define to 1 if you have the <fcntl.h> header file.
ret.defineCMacro("HAVE_FCNTL_H", "1");
// Define to 1 if you have a working fcntl O_NONBLOCK function.
ret.defineCMacro("HAVE_FCNTL_O_NONBLOCK", "1");
// Define to 1 if you have the freeaddrinfo function.
ret.defineCMacro("HAVE_FREEADDRINFO", "1");
// Define to 1 if you have the ftruncate function.
ret.defineCMacro("HAVE_FTRUNCATE", "1");
// Define to 1 if you have a working getaddrinfo function.
ret.defineCMacro("HAVE_GETADDRINFO", "1");
// Define to 1 if you have the `geteuid' function.
ret.defineCMacro("HAVE_GETEUID", "1");
// Define to 1 if you have the `getppid' function.
ret.defineCMacro("HAVE_GETPPID", "1");
// Define to 1 if you have the gethostbyname function.
ret.defineCMacro("HAVE_GETHOSTBYNAME", "1");
// Define to 1 if you have the gethostbyname_r function.
if (!target.isDarwin())
ret.defineCMacro("HAVE_GETHOSTBYNAME_R", "1");
// gethostbyname_r() takes 3 args
// #undef HAVE_GETHOSTBYNAME_R_3
// gethostbyname_r() takes 5 args
// #undef HAVE_GETHOSTBYNAME_R_5
// gethostbyname_r() takes 6 args
ret.defineCMacro("HAVE_GETHOSTBYNAME_R_6", "1");
// Define to 1 if you have the gethostname function.
ret.defineCMacro("HAVE_GETHOSTNAME", "1");
// Define to 1 if you have a working getifaddrs function.
// #undef HAVE_GETIFADDRS
// Define to 1 if you have the `getpass_r' function.
// #undef HAVE_GETPASS_R
// Define to 1 if you have the `getppid' function.
ret.defineCMacro("HAVE_GETPPID", "1");
// Define to 1 if you have the `getprotobyname' function.
ret.defineCMacro("HAVE_GETPROTOBYNAME", "1");
// Define to 1 if you have the `getpeername' function.
ret.defineCMacro("HAVE_GETPEERNAME", "1");
// Define to 1 if you have the `getsockname' function.
ret.defineCMacro("HAVE_GETSOCKNAME", "1");
// Define to 1 if you have the `if_nametoindex' function.
ret.defineCMacro("HAVE_IF_NAMETOINDEX", "1");
// Define to 1 if you have the `getpwuid' function.
ret.defineCMacro("HAVE_GETPWUID", "1");
// Define to 1 if you have the `getpwuid_r' function.
ret.defineCMacro("HAVE_GETPWUID_R", "1");
// Define to 1 if you have the `getrlimit' function.
ret.defineCMacro("HAVE_GETRLIMIT", "1");
// Define to 1 if you have the `gettimeofday' function.
ret.defineCMacro("HAVE_GETTIMEOFDAY", "1");
// Define to 1 if you have a working glibc-style strerror_r function.
// #undef HAVE_GLIBC_STRERROR_R
// Define to 1 if you have a working gmtime_r function.
ret.defineCMacro("HAVE_GMTIME_R", "1");
// if you have the gssapi libraries
// #undef HAVE_GSSAPI
// Define to 1 if you have the <gssapi/gssapi_generic.h> header file.
// #undef HAVE_GSSAPI_GSSAPI_GENERIC_H
// Define to 1 if you have the <gssapi/gssapi.h> header file.
// #undef HAVE_GSSAPI_GSSAPI_H
// Define to 1 if you have the <gssapi/gssapi_krb5.h> header file.
// #undef HAVE_GSSAPI_GSSAPI_KRB5_H
// if you have the GNU gssapi libraries
// #undef HAVE_GSSGNU
// if you have the Heimdal gssapi libraries
// #undef HAVE_GSSHEIMDAL
// if you have the MIT gssapi libraries
// #undef HAVE_GSSMIT
// Define to 1 if you have the `idna_strerror' function.
// #undef HAVE_IDNA_STRERROR
// Define to 1 if you have the `idn_free' function.
// #undef HAVE_IDN_FREE
// Define to 1 if you have the <idn-free.h> header file.
// #undef HAVE_IDN_FREE_H
// Define to 1 if you have the <ifaddrs.h> header file.
ret.defineCMacro("HAVE_IFADDRS_H", "1");
// Define to 1 if you have the `inet_addr' function.
ret.defineCMacro("HAVE_INET_ADDR", "1");
// Define to 1 if you have a IPv6 capable working inet_ntop function.
// #undef HAVE_INET_NTOP
// Define to 1 if you have a IPv6 capable working inet_pton function.
ret.defineCMacro("HAVE_INET_PTON", "1");
// Define to 1 if symbol `sa_family_t' exists
ret.defineCMacro("HAVE_SA_FAMILY_T", "1");
// Define to 1 if symbol `ADDRESS_FAMILY' exists
// #undef HAVE_ADDRESS_FAMILY
// Define to 1 if you have the <inttypes.h> header file.
ret.defineCMacro("HAVE_INTTYPES_H", "1");
// Define to 1 if you have the ioctl function.
ret.defineCMacro("HAVE_IOCTL", "1");
// Define to 1 if you have the ioctlsocket function.
// #undef HAVE_IOCTLSOCKET
// Define to 1 if you have the IoctlSocket camel case function.
// #undef HAVE_IOCTLSOCKET_CAMEL
// Define to 1 if you have a working IoctlSocket camel case FIONBIO function.
// #undef HAVE_IOCTLSOCKET_CAMEL_FIONBIO
// Define to 1 if you have a working ioctlsocket FIONBIO function.
// #undef HAVE_IOCTLSOCKET_FIONBIO
// Define to 1 if you have a working ioctl FIONBIO function.
ret.defineCMacro("HAVE_IOCTL_FIONBIO", "1");
// Define to 1 if you have a working ioctl SIOCGIFADDR function.
ret.defineCMacro("HAVE_IOCTL_SIOCGIFADDR", "1");
// Define to 1 if you have the <io.h> header file.
// #undef HAVE_IO_H
// if you have the Kerberos4 libraries (including -ldes)
// #undef HAVE_KRB4
// Define to 1 if you have the `krb_get_our_ip_for_realm' function.
// #undef HAVE_KRB_GET_OUR_IP_FOR_REALM
// Define to 1 if you have the <krb.h> header file.
// #undef HAVE_KRB_H
// Define to 1 if you have the lber.h header file.
// #undef HAVE_LBER_H
// Define to 1 if you have the ldapssl.h header file.
// #undef HAVE_LDAPSSL_H
// Define to 1 if you have the ldap.h header file.
// #undef HAVE_LDAP_H
// Use LDAPS implementation
// #undef HAVE_LDAP_SSL
// Define to 1 if you have the ldap_ssl.h header file.
// #undef HAVE_LDAP_SSL_H
// Define to 1 if you have the `ldap_url_parse' function.
ret.defineCMacro("HAVE_LDAP_URL_PARSE", "1");
// Define to 1 if you have the <libgen.h> header file.
ret.defineCMacro("HAVE_LIBGEN_H", "1");
// Define to 1 if you have the `idn2' library (-lidn2).
// #undef HAVE_LIBIDN2
// Define to 1 if you have the idn2.h header file.
ret.defineCMacro("HAVE_IDN2_H", "1");
// Define to 1 if you have the `resolv' library (-lresolv).
// #undef HAVE_LIBRESOLV
// Define to 1 if you have the `resolve' library (-lresolve).
// #undef HAVE_LIBRESOLVE
// Define to 1 if you have the `socket' library (-lsocket).
// #undef HAVE_LIBSOCKET
// if brotli is available
// #undef HAVE_BROTLI
// if zstd is available
// #undef HAVE_ZSTD
// if your compiler supports LL
ret.defineCMacro("HAVE_LL", "1");
// Define to 1 if you have the <locale.h> header file.
ret.defineCMacro("HAVE_LOCALE_H", "1");
// Define to 1 if you have a working localtime_r function.
ret.defineCMacro("HAVE_LOCALTIME_R", "1");
// Define to 1 if the compiler supports the 'long long' data type.
ret.defineCMacro("HAVE_LONGLONG", "1");
// Define to 1 if you have the malloc.h header file.
ret.defineCMacro("HAVE_MALLOC_H", "1");
// Define to 1 if you have the <memory.h> header file.
ret.defineCMacro("HAVE_MEMORY_H", "1");
// Define to 1 if you have the MSG_NOSIGNAL flag.
if (!target.isDarwin())
ret.defineCMacro("HAVE_MSG_NOSIGNAL", "1");
// Define to 1 if you have the <netdb.h> header file.
ret.defineCMacro("HAVE_NETDB_H", "1");
// Define to 1 if you have the <netinet/in.h> header file.
ret.defineCMacro("HAVE_NETINET_IN_H", "1");
// Define to 1 if you have the <netinet/tcp.h> header file.
ret.defineCMacro("HAVE_NETINET_TCP_H", "1");
// Define to 1 if you have the <linux/tcp.h> header file.
if (target.isLinux())
ret.defineCMacro("HAVE_LINUX_TCP_H", "1");
// Define to 1 if you have the <net/if.h> header file.
ret.defineCMacro("HAVE_NET_IF_H", "1");
// Define to 1 if NI_WITHSCOPEID exists and works.
// #undef HAVE_NI_WITHSCOPEID
// if you have an old MIT gssapi library, lacking GSS_C_NT_HOSTBASED_SERVICE
// #undef HAVE_OLD_GSSMIT
// Define to 1 if you have the <pem.h> header file.
// #undef HAVE_PEM_H
// Define to 1 if you have the `pipe' function.
ret.defineCMacro("HAVE_PIPE", "1");
// Define to 1 if you have a working poll function.
ret.defineCMacro("HAVE_POLL", "1");
// If you have a fine poll
ret.defineCMacro("HAVE_POLL_FINE", "1");
// Define to 1 if you have the <poll.h> header file.
ret.defineCMacro("HAVE_POLL_H", "1");
// Define to 1 if you have a working POSIX-style strerror_r function.
ret.defineCMacro("HAVE_POSIX_STRERROR_R", "1");
// Define to 1 if you have the <pthread.h> header file
ret.defineCMacro("HAVE_PTHREAD_H", "1");
// Define to 1 if you have the <pwd.h> header file.
ret.defineCMacro("HAVE_PWD_H", "1");
// Define to 1 if you have the `RAND_egd' function.
// #undef HAVE_RAND_EGD
// Define to 1 if you have the `RAND_screen' function.
// #undef HAVE_RAND_SCREEN
// Define to 1 if you have the `RAND_status' function.
// #undef HAVE_RAND_STATUS
// Define to 1 if you have the recv function.
ret.defineCMacro("HAVE_RECV", "1");
// Define to 1 if you have the recvfrom function.
// #undef HAVE_RECVFROM
// Define to 1 if you have the select function.
ret.defineCMacro("HAVE_SELECT", "1");
// Define to 1 if you have the send function.
ret.defineCMacro("HAVE_SEND", "1");
// Define to 1 if you have the 'fsetxattr' function.
ret.defineCMacro("HAVE_FSETXATTR", "1");
// fsetxattr() takes 5 args
ret.defineCMacro("HAVE_FSETXATTR_5", "1");
// fsetxattr() takes 6 args
// #undef HAVE_FSETXATTR_6
// Define to 1 if you have the <setjmp.h> header file.
ret.defineCMacro("HAVE_SETJMP_H", "1");
// Define to 1 if you have the `setlocale' function.
ret.defineCMacro("HAVE_SETLOCALE", "1");
// Define to 1 if you have the `setmode' function.
// #undef HAVE_SETMODE
// Define to 1 if you have the `setrlimit' function.
ret.defineCMacro("HAVE_SETRLIMIT", "1");
// Define to 1 if you have the setsockopt function.
ret.defineCMacro("HAVE_SETSOCKOPT", "1");
// Define to 1 if you have a working setsockopt SO_NONBLOCK function.
// #undef HAVE_SETSOCKOPT_SO_NONBLOCK
// Define to 1 if you have the sigaction function.
ret.defineCMacro("HAVE_SIGACTION", "1");
// Define to 1 if you have the siginterrupt function.
ret.defineCMacro("HAVE_SIGINTERRUPT", "1");
// Define to 1 if you have the signal function.
ret.defineCMacro("HAVE_SIGNAL", "1");
// Define to 1 if you have the <signal.h> header file.
ret.defineCMacro("HAVE_SIGNAL_H", "1");
// Define to 1 if you have the sigsetjmp function or macro.
ret.defineCMacro("HAVE_SIGSETJMP", "1");
// Define to 1 if struct sockaddr_in6 has the sin6_scope_id member
ret.defineCMacro("HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID", "1");
// Define to 1 if you have the `socket' function.
ret.defineCMacro("HAVE_SOCKET", "1");
// Define to 1 if you have the <stdbool.h> header file.
ret.defineCMacro("HAVE_STDBOOL_H", "1");
// Define to 1 if you have the <stdint.h> header file.
ret.defineCMacro("HAVE_STDINT_H", "1");
// Define to 1 if you have the <stdio.h> header file.
ret.defineCMacro("HAVE_STDIO_H", "1");
// Define to 1 if you have the <stdlib.h> header file.
ret.defineCMacro("HAVE_STDLIB_H", "1");
// Define to 1 if you have the strcasecmp function.
ret.defineCMacro("HAVE_STRCASECMP", "1");
// Define to 1 if you have the strcasestr function.
// #undef HAVE_STRCASESTR
// Define to 1 if you have the strcmpi function.
// #undef HAVE_STRCMPI
// Define to 1 if you have the strdup function.
ret.defineCMacro("HAVE_STRDUP", "1");
// Define to 1 if you have the strerror_r function.
ret.defineCMacro("HAVE_STRERROR_R", "1");
// Define to 1 if you have the stricmp function.
// #undef HAVE_STRICMP
// Define to 1 if you have the <strings.h> header file.
ret.defineCMacro("HAVE_STRINGS_H", "1");
// Define to 1 if you have the <string.h> header file.
ret.defineCMacro("HAVE_STRING_H", "1");
// Define to 1 if you have the strncmpi function.
// #undef HAVE_STRNCMPI
// Define to 1 if you have the strnicmp function.
// #undef HAVE_STRNICMP
// Define to 1 if you have the <stropts.h> header file.
// #undef HAVE_STROPTS_H
// Define to 1 if you have the strstr function.
ret.defineCMacro("HAVE_STRSTR", "1");
// Define to 1 if you have the strtok_r function.
ret.defineCMacro("HAVE_STRTOK_R", "1");
// Define to 1 if you have the strtoll function.
ret.defineCMacro("HAVE_STRTOLL", "1");
// if struct sockaddr_storage is defined
ret.defineCMacro("HAVE_STRUCT_SOCKADDR_STORAGE", "1");
// Define to 1 if you have the timeval struct.
ret.defineCMacro("HAVE_STRUCT_TIMEVAL", "1");
// Define to 1 if you have the <sys/filio.h> header file.
// #undef HAVE_SYS_FILIO_H
// Define to 1 if you have the <sys/ioctl.h> header file.
ret.defineCMacro("HAVE_SYS_IOCTL_H", "1");
// Define to 1 if you have the <sys/param.h> header file.
ret.defineCMacro("HAVE_SYS_PARAM_H", "1");
// Define to 1 if you have the <sys/poll.h> header file.
ret.defineCMacro("HAVE_SYS_POLL_H", "1");
// Define to 1 if you have the <sys/resource.h> header file.
ret.defineCMacro("HAVE_SYS_RESOURCE_H", "1");
// Define to 1 if you have the <sys/select.h> header file.
ret.defineCMacro("HAVE_SYS_SELECT_H", "1");
// Define to 1 if you have the <sys/socket.h> header file.
ret.defineCMacro("HAVE_SYS_SOCKET_H", "1");
// Define to 1 if you have the <sys/sockio.h> header file.
// #undef HAVE_SYS_SOCKIO_H
// Define to 1 if you have the <sys/stat.h> header file.
ret.defineCMacro("HAVE_SYS_STAT_H", "1");
// Define to 1 if you have the <sys/time.h> header file.
ret.defineCMacro("HAVE_SYS_TIME_H", "1");
// Define to 1 if you have the <sys/types.h> header file.
ret.defineCMacro("HAVE_SYS_TYPES_H", "1");
// Define to 1 if you have the <sys/uio.h> header file.
ret.defineCMacro("HAVE_SYS_UIO_H", "1");
// Define to 1 if you have the <sys/un.h> header file.
ret.defineCMacro("HAVE_SYS_UN_H", "1");
// Define to 1 if you have the <sys/utime.h> header file.
// #undef HAVE_SYS_UTIME_H
// Define to 1 if you have the <termios.h> header file.
ret.defineCMacro("HAVE_TERMIOS_H", "1");
// Define to 1 if you have the <termio.h> header file.
ret.defineCMacro("HAVE_TERMIO_H", "1");
// Define to 1 if you have the <time.h> header file.
ret.defineCMacro("HAVE_TIME_H", "1");
// Define to 1 if you have the <tld.h> header file.
// #undef HAVE_TLD_H
// Define to 1 if you have the `tld_strerror' function.
// #undef HAVE_TLD_STRERROR
// Define to 1 if you have the `uname' function.
ret.defineCMacro("HAVE_UNAME", "1");
// Define to 1 if you have the <unistd.h> header file.
ret.defineCMacro("HAVE_UNISTD_H", "1");
// Define to 1 if you have the `utime' function.
ret.defineCMacro("HAVE_UTIME", "1");
// Define to 1 if you have the `utimes' function.
ret.defineCMacro("HAVE_UTIMES", "1");
// Define to 1 if you have the <utime.h> header file.
ret.defineCMacro("HAVE_UTIME_H", "1");
// Define to 1 if compiler supports C99 variadic macro style.
ret.defineCMacro("HAVE_VARIADIC_MACROS_C99", "1");
// Define to 1 if compiler supports old gcc variadic macro style.
ret.defineCMacro("HAVE_VARIADIC_MACROS_GCC", "1");
// Define to 1 if you have the winber.h header file.
// #undef HAVE_WINBER_H
// Define to 1 if you have the windows.h header file.
// #undef HAVE_WINDOWS_H
// Define to 1 if you have the winldap.h header file.
// #undef HAVE_WINLDAP_H
// Define to 1 if you have the winsock2.h header file.
// #undef HAVE_WINSOCK2_H
// Define this symbol if your OS supports changing the contents of argv
// #undef HAVE_WRITABLE_ARGV
// Define to 1 if you have the writev function.
// #undef HAVE_WRITEV
// Define to 1 if you have the ws2tcpip.h header file.
// #undef HAVE_WS2TCPIP_H
// Define to 1 if you have the <x509.h> header file.
// #undef HAVE_X509_H
// Define if you have the <process.h> header file.
// #undef HAVE_PROCESS_H
// Define to the sub-directory in which libtool stores uninstalled libraries.
// #undef LT_OBJDIR
// If you lack a fine basename() prototype
// #undef NEED_BASENAME_PROTO
// Define to 1 if you need the lber.h header file even with ldap.h
// #undef NEED_LBER_H
// Define to 1 if you need the malloc.h header file even with stdlib.h
// #undef NEED_MALLOC_H
// Define to 1 if _REENTRANT preprocessor symbol must be defined.
// #undef NEED_REENTRANT
// cpu-machine-OS
ret.defineCMacro("OS", "\"Linux\"");
// Name of package
// #undef PACKAGE
// Define to the address where bug reports for this package should be sent.
// #undef PACKAGE_BUGREPORT
// Define to the full name of this package.
// #undef PACKAGE_NAME
// Define to the full name and version of this package.
// #undef PACKAGE_STRING
// Define to the one symbol short name of this package.
// #undef PACKAGE_TARNAME
// Define to the version of this package.
// #undef PACKAGE_VERSION
// a suitable file to read random data from
ret.defineCMacro("RANDOM_FILE", "\"/dev/urandom\"");
// Define to the type of arg 1 for recvfrom.
// #undef RECVFROM_TYPE_ARG1
// Define to the type pointed by arg 2 for recvfrom.
// #undef RECVFROM_TYPE_ARG2
// Define to 1 if the type pointed by arg 2 for recvfrom is void.
// #undef RECVFROM_TYPE_ARG2_IS_VOID
// Define to the type of arg 3 for recvfrom.
// #undef RECVFROM_TYPE_ARG3
// Define to the type of arg 4 for recvfrom.
// #undef RECVFROM_TYPE_ARG4
// Define to the type pointed by arg 5 for recvfrom.
// #undef RECVFROM_TYPE_ARG5
// Define to 1 if the type pointed by arg 5 for recvfrom is void.
// #undef RECVFROM_TYPE_ARG5_IS_VOID
// Define to the type pointed by arg 6 for recvfrom.
// #undef RECVFROM_TYPE_ARG6
// Define to 1 if the type pointed by arg 6 for recvfrom is void.
// #undef RECVFROM_TYPE_ARG6_IS_VOID
// Define to the function return type for recvfrom.
// #undef RECVFROM_TYPE_RETV
// Define to the type of arg 1 for recv.
ret.defineCMacro("RECV_TYPE_ARG1", "int");
// Define to the type of arg 2 for recv.
ret.defineCMacro("RECV_TYPE_ARG2", "void *");
// Define to the type of arg 3 for recv.
ret.defineCMacro("RECV_TYPE_ARG3", "size_t");
// Define to the type of arg 4 for recv.
ret.defineCMacro("RECV_TYPE_ARG4", "int");
// Define to the function return type for recv.
ret.defineCMacro("RECV_TYPE_RETV", "ssize_t");
// Define to the type qualifier of arg 5 for select.
// #undef SELECT_QUAL_ARG5
// Define to the type of arg 1 for select.
// #undef SELECT_TYPE_ARG1
// Define to the type of args 2, 3 and 4 for select.
// #undef SELECT_TYPE_ARG234
// Define to the type of arg 5 for select.
// #undef SELECT_TYPE_ARG5
// Define to the function return type for select.
// #undef SELECT_TYPE_RETV
// Define to the type qualifier of arg 2 for send.
ret.defineCMacro("SEND_QUAL_ARG2", "const");
// Define to the type of arg 1 for send.
ret.defineCMacro("SEND_TYPE_ARG1", "int");
// Define to the type of arg 2 for send.
ret.defineCMacro("SEND_TYPE_ARG2", "void *");
// Define to the type of arg 3 for send.
ret.defineCMacro("SEND_TYPE_ARG3", "size_t");
// Define to the type of arg 4 for send.
ret.defineCMacro("SEND_TYPE_ARG4", "int");
// Define to the function return type for send.
ret.defineCMacro("SEND_TYPE_RETV", "ssize_t");
// Note: SIZEOF_* variables are fetched with CMake through check_type_size().
// As per CMake documentation on CheckTypeSize, C preprocessor code is
// generated by CMake into SIZEOF_*_CODE. This is what we use in the
// following statements.
//
// Reference: https://cmake.org/cmake/help/latest/module/CheckTypeSize.html
// The size of `int', as computed by sizeof.
ret.defineCMacro("SIZEOF_INT", "4");
// The size of `short', as computed by sizeof.
ret.defineCMacro("SIZEOF_SHORT", "2");
// The size of `long', as computed by sizeof.
ret.defineCMacro("SIZEOF_LONG", "8");
// The size of `off_t', as computed by sizeof.
ret.defineCMacro("SIZEOF_OFF_T", "8");
// The size of `curl_off_t', as computed by sizeof.
ret.defineCMacro("SIZEOF_CURL_OFF_T", "8");
// The size of `size_t', as computed by sizeof.
ret.defineCMacro("SIZEOF_SIZE_T", "8");
// The size of `time_t', as computed by sizeof.
ret.defineCMacro("SIZEOF_TIME_T", "8");
// Define to 1 if you have the ANSI C header files.
ret.defineCMacro("STDC_HEADERS", "1");
// Define to the type of arg 3 for strerror_r.
// #undef STRERROR_R_TYPE_ARG3
// Define to 1 if you can safely include both <sys/time.h> and <time.h>.
ret.defineCMacro("TIME_WITH_SYS_TIME", "1");
// Define if you want to enable c-ares support
// #undef USE_ARES
// Define if you want to enable POSIX threaded DNS lookup
ret.defineCMacro("USE_THREADS_POSIX", "1");
// if libSSH2 is in use
// ret.defineCMacro("USE_LIBSSH2", "1");
// If you want to build curl with the built-in manual
// #undef USE_MANUAL
// if NSS is enabled
// #undef USE_NSS
// if you have the PK11_CreateManagedGenericObject function
// #undef HAVE_PK11_CREATEMANAGEDGENERICOBJECT
// if you want to use OpenLDAP code instead of legacy ldap implementation
// #undef USE_OPENLDAP
// to enable NGHTTP2
// #undef USE_NGHTTP2
// to enable NGTCP2
// #undef USE_NGTCP2
// to enable NGHTTP3
// #undef USE_NGHTTP3
// to enable quiche
// #undef USE_QUICHE
// Define to 1 if you have the quiche_conn_set_qlog_fd function.
// #undef HAVE_QUICHE_CONN_SET_QLOG_FD
// if Unix domain sockets are enabled
ret.defineCMacro("USE_UNIX_SOCKETS", null);
// Define to 1 if you are building a Windows target with large file support.
// #undef USE_WIN32_LARGE_FILES
// to enable SSPI support
// #undef USE_WINDOWS_SSPI
// to enable Windows SSL
// #undef USE_SCHANNEL
// enable multiple SSL backends
// #undef CURL_WITH_MULTI_SSL
// Define to 1 if using yaSSL in OpenSSL compatibility mode.
// #undef USE_YASSLEMUL
// Version number of package
// #undef VERSION
// Define to 1 if OS is AIX.
//#ifndef _ALL_SOURCE
//# undef _ALL_SOURCE
//#endif
// Number of bits in a file offset, on hosts where this is settable.
ret.defineCMacro("_FILE_OFFSET_BITS", "64");
// Define for large files, on AIX-style hosts.
// #undef _LARGE_FILES
// define this if you need it to compile thread-safe code
// #undef _THREAD_SAFE
// Define to empty if `const' does not conform to ANSI C.
// #undef const
// Type to use in place of in_addr_t when system does not provide it.
// #undef in_addr_t
// Define to `__inline__' or `__inline' if that's what the C compiler
// calls it, or to nothing if 'inline' is not supported under any name.
//#ifndef __cplusplus
//#undef inline
//#endif
// Define to `unsigned int' if <sys/types.h> does not define.
// #undef size_t
// the signed version of size_t
// #undef ssize_t
// Define to 1 if you have the mach_absolute_time function.
// #undef HAVE_MACH_ABSOLUTE_TIME
// to enable Windows IDN
// #undef USE_WIN32_IDN
// to make the compiler know the prototypes of Windows IDN APIs
// #undef WANT_IDN_PROTOTYPES
return Library{ .step = ret, .exported_defines = try exported_defines.toOwnedSlice() };
}
const srcs = &.{
root_path ++ "curl/lib/hostcheck.c",
root_path ++ "curl/lib/curl_gethostname.c",
root_path ++ "curl/lib/strerror.c",
root_path ++ "curl/lib/strdup.c",
root_path ++ "curl/lib/asyn-ares.c",
root_path ++ "curl/lib/pop3.c",
root_path ++ "curl/lib/bufref.c",
root_path ++ "curl/lib/rename.c",
root_path ++ "curl/lib/nwlib.c",
root_path ++ "curl/lib/file.c",
root_path ++ "curl/lib/curl_gssapi.c",
root_path ++ "curl/lib/ldap.c",
root_path ++ "curl/lib/socketpair.c",
root_path ++ "curl/lib/system_win32.c",
root_path ++ "curl/lib/http_aws_sigv4.c",
root_path ++ "curl/lib/content_encoding.c",
root_path ++ "curl/lib/vquic/ngtcp2.c",
root_path ++ "curl/lib/vquic/quiche.c",
root_path ++ "curl/lib/vquic/vquic.c",
root_path ++ "curl/lib/ftp.c",
root_path ++ "curl/lib/curl_ntlm_wb.c",
root_path ++ "curl/lib/curl_ntlm_core.c",
root_path ++ "curl/lib/hostip.c",
root_path ++ "curl/lib/urlapi.c",
root_path ++ "curl/lib/curl_get_line.c",
root_path ++ "curl/lib/vtls/mesalink.c",
root_path ++ "curl/lib/vtls/mbedtls_threadlock.c",
root_path ++ "curl/lib/vtls/nss.c",
root_path ++ "curl/lib/vtls/gskit.c",
root_path ++ "curl/lib/vtls/wolfssl.c",
root_path ++ "curl/lib/vtls/keylog.c",
root_path ++ "curl/lib/vtls/rustls.c",
root_path ++ "curl/lib/vtls/vtls.c",
root_path ++ "curl/lib/vtls/gtls.c",
root_path ++ "curl/lib/vtls/schannel.c",
root_path ++ "curl/lib/vtls/schannel_verify.c",
root_path ++ "curl/lib/vtls/sectransp.c",
root_path ++ "curl/lib/vtls/openssl.c",
root_path ++ "curl/lib/vtls/mbedtls.c",
root_path ++ "curl/lib/vtls/bearssl.c",
root_path ++ "curl/lib/parsedate.c",
root_path ++ "curl/lib/sendf.c",
root_path ++ "curl/lib/altsvc.c",
root_path ++ "curl/lib/krb5.c",
root_path ++ "curl/lib/curl_rtmp.c",
root_path ++ "curl/lib/curl_ctype.c",
root_path ++ "curl/lib/inet_pton.c",
root_path ++ "curl/lib/pingpong.c",
root_path ++ "curl/lib/mime.c",
root_path ++ "curl/lib/vauth/krb5_gssapi.c",
root_path ++ "curl/lib/vauth/krb5_sspi.c",
root_path ++ "curl/lib/vauth/spnego_sspi.c",
root_path ++ "curl/lib/vauth/digest.c",
root_path ++ "curl/lib/vauth/ntlm_sspi.c",
root_path ++ "curl/lib/vauth/vauth.c",
root_path ++ "curl/lib/vauth/gsasl.c",
root_path ++ "curl/lib/vauth/cram.c",
root_path ++ "curl/lib/vauth/oauth2.c",
root_path ++ "curl/lib/vauth/digest_sspi.c",
root_path ++ "curl/lib/vauth/cleartext.c",
root_path ++ "curl/lib/vauth/spnego_gssapi.c",
root_path ++ "curl/lib/vauth/ntlm.c",
root_path ++ "curl/lib/version_win32.c",
root_path ++ "curl/lib/multi.c",
root_path ++ "curl/lib/http_ntlm.c",
root_path ++ "curl/lib/curl_sspi.c",
root_path ++ "curl/lib/md5.c",
root_path ++ "curl/lib/dict.c",
root_path ++ "curl/lib/http.c",
root_path ++ "curl/lib/curl_des.c",
root_path ++ "curl/lib/memdebug.c",
root_path ++ "curl/lib/non-ascii.c",
root_path ++ "curl/lib/transfer.c",
root_path ++ "curl/lib/inet_ntop.c",
root_path ++ "curl/lib/slist.c",
root_path ++ "curl/lib/http_negotiate.c",
root_path ++ "curl/lib/http_digest.c",
root_path ++ "curl/lib/vssh/wolfssh.c",
root_path ++ "curl/lib/vssh/libssh.c",
root_path ++ "curl/lib/vssh/libssh2.c",
root_path ++ "curl/lib/hsts.c",
root_path ++ "curl/lib/escape.c",
root_path ++ "curl/lib/hostsyn.c",
root_path ++ "curl/lib/speedcheck.c",
root_path ++ "curl/lib/asyn-thread.c",
root_path ++ "curl/lib/curl_addrinfo.c",
root_path ++ "curl/lib/nwos.c",
root_path ++ "curl/lib/tftp.c",
root_path ++ "curl/lib/version.c",
root_path ++ "curl/lib/rand.c",
root_path ++ "curl/lib/psl.c",
root_path ++ "curl/lib/imap.c",
root_path ++ "curl/lib/mqtt.c",
root_path ++ "curl/lib/share.c",
root_path ++ "curl/lib/doh.c",
root_path ++ "curl/lib/curl_range.c",
root_path ++ "curl/lib/openldap.c",
root_path ++ "curl/lib/getinfo.c",
root_path ++ "curl/lib/select.c",
root_path ++ "curl/lib/base64.c",
root_path ++ "curl/lib/curl_sasl.c",
root_path ++ "curl/lib/curl_endian.c",
root_path ++ "curl/lib/connect.c",
root_path ++ "curl/lib/fileinfo.c",
root_path ++ "curl/lib/telnet.c",
root_path ++ "curl/lib/x509asn1.c",
root_path ++ "curl/lib/conncache.c",
root_path ++ "curl/lib/strcase.c",
root_path ++ "curl/lib/if2ip.c",
root_path ++ "curl/lib/gopher.c",
root_path ++ "curl/lib/ftplistparser.c",
root_path ++ "curl/lib/setopt.c",
root_path ++ "curl/lib/idn_win32.c",
root_path ++ "curl/lib/strtoofft.c",
root_path ++ "curl/lib/hmac.c",
root_path ++ "curl/lib/getenv.c",
root_path ++ "curl/lib/smb.c",
root_path ++ "curl/lib/dotdot.c",
root_path ++ "curl/lib/curl_threads.c",
root_path ++ "curl/lib/md4.c",
root_path ++ "curl/lib/easygetopt.c",
root_path ++ "curl/lib/curl_fnmatch.c",
root_path ++ "curl/lib/sha256.c",
root_path ++ "curl/lib/cookie.c",
root_path ++ "curl/lib/amigaos.c",
root_path ++ "curl/lib/progress.c",
root_path ++ "curl/lib/nonblock.c",
root_path ++ "curl/lib/llist.c",
root_path ++ "curl/lib/hostip6.c",
root_path ++ "curl/lib/dynbuf.c",
root_path ++ "curl/lib/warnless.c",
root_path ++ "curl/lib/hostasyn.c",
root_path ++ "curl/lib/http_chunks.c",
root_path ++ "curl/lib/wildcard.c",
root_path ++ "curl/lib/strtok.c",
root_path ++ "curl/lib/curl_memrchr.c",
root_path ++ "curl/lib/rtsp.c",
root_path ++ "curl/lib/http2.c",
root_path ++ "curl/lib/socks.c",
root_path ++ "curl/lib/curl_path.c",
root_path ++ "curl/lib/curl_multibyte.c",
root_path ++ "curl/lib/http_proxy.c",
root_path ++ "curl/lib/formdata.c",
root_path ++ "curl/lib/netrc.c",
root_path ++ "curl/lib/socks_sspi.c",
root_path ++ "curl/lib/mprintf.c",
root_path ++ "curl/lib/easyoptions.c",
root_path ++ "curl/lib/easy.c",
root_path ++ "curl/lib/c-hyper.c",
root_path ++ "curl/lib/hostip4.c",
root_path ++ "curl/lib/timeval.c",
root_path ++ "curl/lib/smtp.c",
root_path ++ "curl/lib/splay.c",
root_path ++ "curl/lib/socks_gssapi.c",
root_path ++ "curl/lib/url.c",
root_path ++ "curl/lib/hash.c",
};
|
0 | repos/gpt4all.zig/src | repos/gpt4all.zig/src/zig-libcurl/README.md | # libcurl build package
[](https://github.com/mattnite/zig-libcurl/actions/workflows/ci.yml)
## Like this project?
If you like this project or other works of mine, please consider [donating to or sponsoring me](https://github.com/sponsors/mattnite) on Github [:heart:](https://github.com/sponsors/mattnite)
## How to use
This repo contains code for your `build.zig` that can statically compile libcurl, as well as some idiomatic Zig bindings for libcurl that you can use in your application. In either case below you will be able to include libcurls header with:
```zig
const c = @cImport({
@cInclude("curl/curl.h");
});
```
### Link and add bindings to your application
In order to statically link libcurl into your application and access the bindings with a configurable import string:
```zig
const libcurl = @import("path/to/libcurl.zig");
pub fn build(b: *std.build.Builder) void {
// ...
const lib = libcurl.create(b, target, optimize);
const exe = b.addExecutable(.{
.name = "my-program",
.root_source_file = .{ .path = "src/main.zig" },
.target = target,
.optimize = optimize,
});
const exe = b.addExecutable("my-program", "src/main.zig");
lib.link(exe, .{ .import_name = "curl" });
}
```
Now code that is part of the `my-program` executable can import the libcurl bindings with `@import("curl")`.
### Only link to your application
In order to just link to the application, all you need to do is omit the `.import_name = "curl"` argument to libcurl's link options:
```zig
lib.link(exe, .{});
```
|
0 | repos/gpt4all.zig/src | repos/gpt4all.zig/src/zig-libcurl/build.zig | const std = @import("std");
const libcurl = @import("libcurl.zig");
const mbedtls = @import("zig-mbedtls/mbedtls.zig");
const zlib = @import("zig-zlib/zlib.zig");
const libssh2 = @import("zig-libssh2/libssh2.zig");
pub fn build(b: *std.build.Builder) !void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const z = zlib.create(b, target, optimize);
const tls = mbedtls.create(b, target, optimize);
const ssh2 = libssh2.create(b, target, optimize);
tls.link(ssh2.step);
const curl = try libcurl.create(b, target, optimize);
ssh2.link(curl.step);
tls.link(curl.step);
z.link(curl.step, .{});
curl.step.install();
const tests = b.addTest(.{
.root_source_file = .{ .path = "src/main.zig" },
.target = target,
.optimize = optimize,
});
curl.link(tests, .{});
z.link(tests, .{});
tls.link(tests);
ssh2.link(tests);
const test_step = b.step("test", "Run tests");
test_step.dependOn(&tests.step);
const exe = b.addExecutable(.{
.name = "my-program",
.root_source_file = .{ .path = "src/main.zig" },
.target = target,
.optimize = optimize,
});
curl.link(exe, .{});
exe.install();
}
|
0 | repos/gpt4all.zig/src/zig-libcurl | repos/gpt4all.zig/src/zig-libcurl/curl/libcurl.pc.in | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
# This should most probably benefit from getting a "Requires:" field added
# dynamically by configure.
#
prefix=@prefix@
exec_prefix=@exec_prefix@
libdir=@libdir@
includedir=@includedir@
supported_protocols="@SUPPORT_PROTOCOLS@"
supported_features="@SUPPORT_FEATURES@"
Name: libcurl
URL: https://curl.se/
Description: Library to transfer files with ftp, http, etc.
Version: @CURLVERSION@
Libs: -L${libdir} -lcurl @LIBCURL_NO_SHARED@
Libs.private: @LIBCURL_LIBS@
Cflags: -I${includedir} @CPPFLAG_CURL_STATICLIB@
|
0 | repos/gpt4all.zig/src/zig-libcurl | repos/gpt4all.zig/src/zig-libcurl/curl/SECURITY.md | # Security Policy
See [docs/SECURITY-PROCESS.md](docs/SECURITY-PROCESS.md) for full details.
## Reporting a Vulnerability
If you have found or just suspect a security problem somewhere in curl or libcurl,
report it on [https://hackerone.com/curl](https://hackerone.com/curl).
We treat security issues with confidentiality until controlled and disclosed responsibly.
|
0 | repos/gpt4all.zig/src/zig-libcurl | repos/gpt4all.zig/src/zig-libcurl/curl/.azure-pipelines.yml | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
# Starter pipeline
# Start with a minimal pipeline that you can customize to build and deploy your code.
# Add steps that build, run tests, deploy, and more:
# https://aka.ms/yaml
trigger:
branches:
include:
- 'master'
- '*/ci'
pr:
branches:
include:
- 'master'
stages:
##########################################
### Linux jobs first
##########################################
- stage: linux
dependsOn: []
jobs:
- job: ubuntu
# define defaults to make sure variables are always expanded/replaced
variables:
install: ''
configure: ''
tests: '!433'
timeoutInMinutes: 60
pool:
vmImage: 'ubuntu-latest'
strategy:
matrix:
default:
name: default
install: jsonlint
configure: --enable-debug --with-openssl
disable_ipv6:
name: w/o IPv6
configure: --disable-ipv6 --with-openssl
disable_http_smtp_imap:
name: w/o HTTP/SMTP/IMAP
configure: --disable-http --disable-smtp --disable-imap --without-openssl
disable_thredres:
name: sync resolver
configure: --disable-threaded-resolver --with-openssl
https_only:
name: HTTPS only
configure: --disable-dict --disable-file --disable-ftp --disable-gopher --disable-imap --disable-ldap --disable-pop3 --disable-rtmp --disable-rtsp --disable-scp --disable-sftp --disable-smb --disable-smtp --disable-telnet --disable-tftp --with-openssl
torture:
name: torture
install: libnghttp2-dev
configure: --enable-debug --disable-shared --disable-threaded-resolver --with-openssl
tests: -n -t --shallow=40 !FTP
steps:
- script: sudo apt-get update && sudo apt-get install -y stunnel4 python3-impacket libzstd-dev libbrotli-dev $(install)
displayName: 'apt install'
- script: ./buildconf && ./configure --enable-warnings --enable-werror $(configure)
displayName: 'configure $(name)'
- script: make V=1 && cd tests && make V=1
displayName: 'compile'
env:
MAKEFLAGS: "-j 2"
- script: make V=1 test-ci
displayName: 'test'
env:
AZURE_ACCESS_TOKEN: "$(System.AccessToken)"
TFLAGS: "-r $(tests)"
##########################################
### Windows jobs below
##########################################
- stage: windows
dependsOn: []
variables:
agent.preferPowerShellOnContainers: true
jobs:
- job: windows
# define defaults to make sure variables are always expanded/replaced
variables:
container_img: ''
container_cmd: ''
configure: ''
tests: ''
timeoutInMinutes: 120
pool:
vmImage: 'windows-2019'
strategy:
matrix:
msys2_mingw32_debug_openssl:
name: 32-bit OpenSSL/libssh2
container_img: ghcr.io/mback2k/curl-docker-winbuildenv/msys2-mingw32:ltsc2019
container_cmd: C:\msys64\usr\bin\sh
prepare: pacman -S --needed --noconfirm --noprogressbar libssh2-devel mingw-w64-i686-libssh2
configure: --host=i686-w64-mingw32 --build=i686-w64-mingw32 --prefix=/mingw32 --enable-debug --enable-werror --with-libssh2 --with-openssl
tests: "~571"
msys2_mingw64_debug_openssl:
name: 64-bit OpenSSL/libssh2
container_img: ghcr.io/mback2k/curl-docker-winbuildenv/msys2-mingw64:ltsc2019
container_cmd: C:\msys64\usr\bin\sh
prepare: pacman -S --needed --noconfirm --noprogressbar libssh2-devel mingw-w64-x86_64-libssh2
configure: --host=x86_64-w64-mingw32 --build=x86_64-w64-mingw32 --prefix=/mingw64 --enable-debug --enable-werror --with-libssh2 --with-openssl
tests: "~571"
msys1_mingw_debug:
name: 32-bit (legacy)
container_img: ghcr.io/mback2k/curl-docker-winbuildenv/msys1-mingw:ltsc2019
container_cmd: C:\MinGW\msys\1.0\bin\sh
configure: --host=i686-pc-mingw32 --build=i686-pc-mingw32 --prefix=/mingw --enable-debug --without-ssl
tests: "!203 !1143"
msys1_mingw32_debug:
name: 32-bit w/o zlib
container_img: ghcr.io/mback2k/curl-docker-winbuildenv/msys1-mingw32:ltsc2019
container_cmd: C:\MinGW\msys\1.0\bin\sh
configure: --host=i686-w64-mingw32 --build=i686-w64-mingw32 --prefix=/mingw32 --enable-debug --enable-werror --without-zlib --without-ssl
tests: "!203 !1143"
msys1_mingw64_debug:
name: 64-bit w/o zlib
container_img: ghcr.io/mback2k/curl-docker-winbuildenv/msys1-mingw64:ltsc2019
container_cmd: C:\MinGW\msys\1.0\bin\sh
configure: --host=x86_64-w64-mingw32 --build=x86_64-w64-mingw32 --prefix=/mingw64 --enable-debug --enable-werror --without-zlib --without-ssl
tests: "!203 !1143"
msys2_mingw32_debug_schannel:
name: 32-bit Schannel/SSPI/WinIDN/libssh2
container_img: ghcr.io/mback2k/curl-docker-winbuildenv/msys2-mingw32:ltsc2019
container_cmd: C:\msys64\usr\bin\sh
prepare: pacman -S --needed --noconfirm --noprogressbar libssh2-devel mingw-w64-i686-libssh2
configure: --host=i686-w64-mingw32 --build=i686-w64-mingw32 --prefix=/mingw32 --enable-debug --enable-werror --enable-sspi --with-schannel --with-winidn --with-libssh2
tests: "~571"
msys2_mingw64_debug_schannel:
name: 64-bit Schannel/SSPI/WinIDN/libssh2
container_img: ghcr.io/mback2k/curl-docker-winbuildenv/msys2-mingw64:ltsc2019
container_cmd: C:\msys64\usr\bin\sh
prepare: pacman -S --needed --noconfirm --noprogressbar libssh2-devel mingw-w64-x86_64-libssh2
configure: --host=x86_64-w64-mingw32 --build=x86_64-w64-mingw32 --prefix=/mingw64 --enable-debug --enable-werror --enable-sspi --with-schannel --with-winidn --with-libssh2
tests: "~571"
msys1_mingw_debug_schannel:
name: 32-bit Schannel/SSPI/WinIDN (legacy)
container_img: ghcr.io/mback2k/curl-docker-winbuildenv/msys1-mingw:ltsc2019
container_cmd: C:\MinGW\msys\1.0\bin\sh
configure: --host=i686-pc-mingw32 --build=i686-pc-mingw32 --prefix=/mingw --enable-debug --enable-sspi --with-schannel --with-winidn
tests: "!203 !305 !311 !312 !313 !404 !1143 !2033 !2035 !2038 !2041 !2042 !2048 !2070 !2079 !2087 !3023 !3024"
msys1_mingw32_debug_schannel:
name: 32-bit Schannel/SSPI/WinIDN w/o zlib
container_img: ghcr.io/mback2k/curl-docker-winbuildenv/msys1-mingw32:ltsc2019
container_cmd: C:\MinGW\msys\1.0\bin\sh
configure: --host=i686-w64-mingw32 --build=i686-w64-mingw32 --prefix=/mingw32 --enable-debug --enable-werror --enable-sspi --with-schannel --with-winidn --without-zlib
tests: "!203 !1143"
msys1_mingw64_debug_schannel:
name: 64-bit Schannel/SSPI/WinIDN w/o zlib
container_img: ghcr.io/mback2k/curl-docker-winbuildenv/msys1-mingw64:ltsc2019
container_cmd: C:\MinGW\msys\1.0\bin\sh
configure: --host=x86_64-w64-mingw32 --build=x86_64-w64-mingw32 --prefix=/mingw64 --enable-debug --enable-werror --enable-sspi --with-schannel --with-winidn --without-zlib
tests: "!203 !1143"
container:
image: $(container_img)
env:
MSYS2_PATH_TYPE: inherit
steps:
- script: $(container_cmd) -l -c "cd $(echo '%cd%') && $(prepare)"
displayName: 'prepare'
condition: variables.prepare
- script: $(container_cmd) -l -c "cd $(echo '%cd%') && ./buildconf && ./configure $(configure)"
displayName: 'configure $(name)'
- script: $(container_cmd) -l -c "cd $(echo '%cd%') && make V=1 && cd tests && make V=1"
displayName: 'compile'
env:
MAKEFLAGS: "-j 2"
- script: $(container_cmd) -l -c "cd $(echo '%cd%') && make V=1 install && PATH=/usr/bin:/bin find . -type f -path '*/.libs/*.exe' -print -execdir mv -t .. {} \;"
displayName: 'install'
- script: $(container_cmd) -l -c "cd $(echo '%cd%') && make V=1 test-ci"
displayName: 'test'
env:
AZURE_ACCESS_TOKEN: "$(System.AccessToken)"
TFLAGS: "!IDN !SCP ~612 ~1056 $(tests)"
|
0 | repos/gpt4all.zig/src/zig-libcurl | repos/gpt4all.zig/src/zig-libcurl/curl/curl-config.in | #! /bin/sh
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 2001 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
prefix=@prefix@
exec_prefix=@exec_prefix@
includedir=@includedir@
cppflag_curl_staticlib=@CPPFLAG_CURL_STATICLIB@
usage()
{
cat <<EOF
Usage: curl-config [OPTION]
Available values for OPTION include:
--built-shared says 'yes' if libcurl was built shared
--ca ca bundle install path
--cc compiler
--cflags pre-processor and compiler flags
--checkfor [version] check for (lib)curl of the specified version
--configure the arguments given to configure when building curl
--features newline separated list of enabled features
--help display this help and exit
--libs library linking information
--prefix curl install prefix
--protocols newline separated list of enabled protocols
--ssl-backends output the SSL backends libcurl was built to support
--static-libs static libcurl library linking information
--version output version information
--vernum output the version information as a number (hexadecimal)
EOF
exit $1
}
if test $# -eq 0; then
usage 1
fi
while test $# -gt 0; do
case "$1" in
# this deals with options in the style
# --option=value and extracts the value part
# [not currently used]
-*=*) value=`echo "$1" | sed 's/[-_a-zA-Z0-9]*=//'` ;;
*) value= ;;
esac
case "$1" in
--built-shared)
echo @ENABLE_SHARED@
;;
--ca)
echo @CURL_CA_BUNDLE@
;;
--cc)
echo "@CC@"
;;
--prefix)
echo "$prefix"
;;
--feature|--features)
for feature in @SUPPORT_FEATURES@ ""; do
test -n "$feature" && echo "$feature"
done
;;
--protocols)
for protocol in @SUPPORT_PROTOCOLS@; do
echo "$protocol"
done
;;
--version)
echo libcurl @CURLVERSION@
exit 0
;;
--checkfor)
checkfor=$2
cmajor=`echo $checkfor | cut -d. -f1`
cminor=`echo $checkfor | cut -d. -f2`
# when extracting the patch part we strip off everything after a
# dash as that's used for things like version 1.2.3-CVS
cpatch=`echo $checkfor | cut -d. -f3 | cut -d- -f1`
vmajor=`echo @CURLVERSION@ | cut -d. -f1`
vminor=`echo @CURLVERSION@ | cut -d. -f2`
# when extracting the patch part we strip off everything after a
# dash as that's used for things like version 1.2.3-CVS
vpatch=`echo @CURLVERSION@ | cut -d. -f3 | cut -d- -f1`
if test "$vmajor" -gt "$cmajor"; then
exit 0;
fi
if test "$vmajor" -eq "$cmajor"; then
if test "$vminor" -gt "$cminor"; then
exit 0
fi
if test "$vminor" -eq "$cminor"; then
if test "$cpatch" -le "$vpatch"; then
exit 0
fi
fi
fi
echo "requested version $checkfor is newer than existing @CURLVERSION@"
exit 1
;;
--vernum)
echo @VERSIONNUM@
exit 0
;;
--help)
usage 0
;;
--cflags)
if test "X$cppflag_curl_staticlib" = "X-DCURL_STATICLIB"; then
CPPFLAG_CURL_STATICLIB="-DCURL_STATICLIB "
else
CPPFLAG_CURL_STATICLIB=""
fi
if test "X@includedir@" = "X/usr/include"; then
echo "$CPPFLAG_CURL_STATICLIB"
else
echo "${CPPFLAG_CURL_STATICLIB}-I@includedir@"
fi
;;
--libs)
if test "X@libdir@" != "X/usr/lib" -a "X@libdir@" != "X/usr/lib64"; then
CURLLIBDIR="-L@libdir@ "
else
CURLLIBDIR=""
fi
if test "X@ENABLE_SHARED@" = "Xno"; then
echo ${CURLLIBDIR}-lcurl @LIBCURL_LIBS@
else
echo ${CURLLIBDIR}-lcurl
fi
;;
--ssl-backends)
echo "@SSL_BACKENDS@"
;;
--static-libs)
if test "X@ENABLE_STATIC@" != "Xno" ; then
echo @libdir@/libcurl.@libext@ @LDFLAGS@ @LIBCURL_LIBS@
else
echo "curl was built with static libraries disabled" >&2
exit 1
fi
;;
--configure)
echo @CONFIGURE_OPTIONS@
;;
*)
echo "unknown option: $1"
usage 1
;;
esac
shift
done
exit 0
|
0 | repos/gpt4all.zig/src/zig-libcurl | repos/gpt4all.zig/src/zig-libcurl/curl/CMakeLists.txt | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
# curl/libcurl CMake script
# by Tetetest and Sukender (Benoit Neil)
# TODO:
# The output .so file lacks the soname number which we currently have within the lib/Makefile.am file
# Add full (4 or 5 libs) SSL support
# Add INSTALL target (EXTRA_DIST variables in Makefile.am may be moved to Makefile.inc so that CMake/CPack is aware of what's to include).
# Check on all possible platforms
# Test with as many configurations possible (With or without any option)
# Create scripts that help keeping the CMake build system up to date (to reduce maintenance). According to Tetetest:
# - lists of headers that 'configure' checks for;
# - curl-specific tests (the ones that are in m4/curl-*.m4 files);
# - (most obvious thing:) curl version numbers.
# Add documentation subproject
#
# To check:
# (From Daniel Stenberg) The cmake build selected to run gcc with -fPIC on my box while the plain configure script did not.
# (From Daniel Stenberg) The gcc command line use neither -g nor any -O options. As a developer, I also treasure our configure scripts's --enable-debug option that sets a long range of "picky" compiler options.
cmake_minimum_required(VERSION 3.2...3.16 FATAL_ERROR)
set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/CMake;${CMAKE_MODULE_PATH}")
include(Utilities)
include(Macros)
include(CMakeDependentOption)
include(CheckCCompilerFlag)
project(CURL C)
file(STRINGS ${CURL_SOURCE_DIR}/include/curl/curlver.h CURL_VERSION_H_CONTENTS REGEX "#define LIBCURL_VERSION( |_NUM )")
string(REGEX MATCH "#define LIBCURL_VERSION \"[^\"]*"
CURL_VERSION ${CURL_VERSION_H_CONTENTS})
string(REGEX REPLACE "[^\"]+\"" "" CURL_VERSION ${CURL_VERSION})
string(REGEX MATCH "#define LIBCURL_VERSION_NUM 0x[0-9a-fA-F]+"
CURL_VERSION_NUM ${CURL_VERSION_H_CONTENTS})
string(REGEX REPLACE "[^0]+0x" "" CURL_VERSION_NUM ${CURL_VERSION_NUM})
# Setup package meta-data
# SET(PACKAGE "curl")
message(STATUS "curl version=[${CURL_VERSION}]")
# SET(PACKAGE_TARNAME "curl")
# SET(PACKAGE_NAME "curl")
# SET(PACKAGE_VERSION "-")
# SET(PACKAGE_STRING "curl-")
# SET(PACKAGE_BUGREPORT "a suitable curl mailing list => https://curl.se/mail/")
set(OPERATING_SYSTEM "${CMAKE_SYSTEM_NAME}")
set(OS "\"${CMAKE_SYSTEM_NAME}\"")
include_directories(${CURL_SOURCE_DIR}/include)
option(CURL_WERROR "Turn compiler warnings into errors" OFF)
option(PICKY_COMPILER "Enable picky compiler options" ON)
option(BUILD_CURL_EXE "Set to ON to build curl executable." ON)
option(BUILD_SHARED_LIBS "Build shared libraries" ON)
option(ENABLE_ARES "Set to ON to enable c-ares support" OFF)
if(WIN32)
option(CURL_STATIC_CRT "Set to ON to build libcurl with static CRT on Windows (/MT)." OFF)
option(ENABLE_INET_PTON "Set to OFF to prevent usage of inet_pton when building against modern SDKs while still requiring compatibility with older Windows versions, such as Windows XP, Windows Server 2003 etc." ON)
option(ENABLE_UNICODE "Set to ON to use the Unicode version of the Windows API functions" OFF)
set(CURL_TARGET_WINDOWS_VERSION "" CACHE STRING "Minimum target Windows version as hex string")
if(CURL_TARGET_WINDOWS_VERSION)
add_definitions(-D_WIN32_WINNT=${CURL_TARGET_WINDOWS_VERSION})
set(CMAKE_REQUIRED_DEFINITIONS "${CMAKE_REQUIRED_DEFINITIONS} -D_WIN32_WINNT=${CURL_TARGET_WINDOWS_VERSION}")
elseif(ENABLE_INET_PTON)
# _WIN32_WINNT_VISTA (0x0600)
add_definitions(-D_WIN32_WINNT=0x0600)
set(CMAKE_REQUIRED_DEFINITIONS "${CMAKE_REQUIRED_DEFINITIONS} -D_WIN32_WINNT=0x0600")
else()
# _WIN32_WINNT_WINXP (0x0501)
add_definitions(-D_WIN32_WINNT=0x0501)
set(CMAKE_REQUIRED_DEFINITIONS "${CMAKE_REQUIRED_DEFINITIONS} -D_WIN32_WINNT=0x0501")
endif()
if(ENABLE_UNICODE)
add_definitions(-DUNICODE -D_UNICODE)
if(MINGW)
add_compile_options(-municode)
endif()
endif()
endif()
option(CURL_LTO "Turn on compiler Link Time Optimizations" OFF)
cmake_dependent_option(ENABLE_THREADED_RESOLVER "Set to ON to enable threaded DNS lookup"
ON "NOT ENABLE_ARES"
OFF)
option(ENABLE_DEBUG "Set to ON to enable curl debug features" OFF)
option(ENABLE_CURLDEBUG "Set to ON to build with TrackMemory feature enabled" OFF)
if(CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_CLANG)
if(PICKY_COMPILER)
foreach(_CCOPT -pedantic -Wall -W -Wpointer-arith -Wwrite-strings -Wunused -Wshadow -Winline -Wnested-externs -Wmissing-declarations -Wmissing-prototypes -Wfloat-equal -Wsign-compare -Wundef -Wendif-labels -Wstrict-prototypes -Wdeclaration-after-statement -Wstrict-aliasing=3 -Wcast-align -Wtype-limits -Wold-style-declaration -Wmissing-parameter-type -Wempty-body -Wclobbered -Wignored-qualifiers -Wconversion -Wvla -Wdouble-promotion)
# surprisingly, CHECK_C_COMPILER_FLAG needs a new variable to store each new
# test result in.
string(MAKE_C_IDENTIFIER "OPT${_CCOPT}" _optvarname)
check_c_compiler_flag(${_CCOPT} ${_optvarname})
if(${_optvarname})
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${_CCOPT}")
endif()
endforeach()
foreach(_CCOPT long-long multichar format-nonliteral sign-conversion system-headers pedantic-ms-format)
# GCC only warns about unknown -Wno- options if there are also other diagnostic messages,
# so test for the positive form instead
string(MAKE_C_IDENTIFIER "OPT${_CCOPT}" _optvarname)
check_c_compiler_flag("-W${_CCOPT}" ${_optvarname})
if(${_optvarname})
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-${_CCOPT}")
endif()
endforeach()
endif()
endif()
if(ENABLE_DEBUG)
# DEBUGBUILD will be defined only for Debug builds
set_property(DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS $<$<CONFIG:Debug>:DEBUGBUILD>)
set(ENABLE_CURLDEBUG ON)
endif()
if(ENABLE_CURLDEBUG)
set_property(DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS CURLDEBUG)
endif()
# For debug libs and exes, add "-d" postfix
if(NOT DEFINED CMAKE_DEBUG_POSTFIX)
set(CMAKE_DEBUG_POSTFIX "-d")
endif()
# initialize CURL_LIBS
set(CURL_LIBS "")
if(ENABLE_ARES)
set(USE_ARES 1)
find_package(CARES REQUIRED)
list(APPEND CURL_LIBS ${CARES_LIBRARY})
endif()
include(CurlSymbolHiding)
option(CURL_ENABLE_EXPORT_TARGET "to enable cmake export target" ON)
mark_as_advanced(CURL_ENABLE_EXPORT_TARGET)
option(CURL_DISABLE_ALTSVC "disables alt-svc support" OFF)
mark_as_advanced(CURL_DISABLE_ALTSVC)
option(CURL_DISABLE_COOKIES "disables cookies support" OFF)
mark_as_advanced(CURL_DISABLE_COOKIES)
option(CURL_DISABLE_CRYPTO_AUTH "disables cryptographic authentication" OFF)
mark_as_advanced(CURL_DISABLE_CRYPTO_AUTH)
option(CURL_DISABLE_DICT "disables DICT" OFF)
mark_as_advanced(CURL_DISABLE_DICT)
option(CURL_DISABLE_DOH "disables DNS-over-HTTPS" OFF)
mark_as_advanced(CURL_DISABLE_DOH)
option(CURL_DISABLE_FILE "disables FILE" OFF)
mark_as_advanced(CURL_DISABLE_FILE)
option(CURL_DISABLE_FTP "disables FTP" OFF)
mark_as_advanced(CURL_DISABLE_FTP)
option(CURL_DISABLE_GETOPTIONS "disables curl_easy_options API for existing options to curl_easy_setopt" OFF)
mark_as_advanced(CURL_DISABLE_GETOPTIONS)
option(CURL_DISABLE_GOPHER "disables Gopher" OFF)
mark_as_advanced(CURL_DISABLE_GOPHER)
option(CURL_DISABLE_HSTS "disables HSTS support" OFF)
mark_as_advanced(CURL_DISABLE_HSTS)
option(CURL_DISABLE_HTTP "disables HTTP" OFF)
mark_as_advanced(CURL_DISABLE_HTTP)
option(CURL_DISABLE_HTTP_AUTH "disables all HTTP authentication methods" OFF)
mark_as_advanced(CURL_DISABLE_HTTP_AUTH)
option(CURL_DISABLE_IMAP "disables IMAP" OFF)
mark_as_advanced(CURL_DISABLE_IMAP)
option(CURL_DISABLE_LDAP "disables LDAP" OFF)
mark_as_advanced(CURL_DISABLE_LDAP)
option(CURL_DISABLE_LDAPS "disables LDAPS" OFF)
mark_as_advanced(CURL_DISABLE_LDAPS)
option(CURL_DISABLE_LIBCURL_OPTION "disables --libcurl option from the curl tool" OFF)
mark_as_advanced(CURL_DISABLE_LIBCURL_OPTION)
option(CURL_DISABLE_MIME "disables MIME support" OFF)
mark_as_advanced(CURL_DISABLE_MIME)
option(CURL_DISABLE_MQTT "disables MQTT" OFF)
mark_as_advanced(CURL_DISABLE_MQTT)
option(CURL_DISABLE_NETRC "disables netrc parser" OFF)
mark_as_advanced(CURL_DISABLE_NETRC)
option(CURL_DISABLE_NTLM "disables NTLM support" OFF)
mark_as_advanced(CURL_DISABLE_NTLM)
option(CURL_DISABLE_PARSEDATE "disables date parsing" OFF)
mark_as_advanced(CURL_DISABLE_PARSEDATE)
option(CURL_DISABLE_POP3 "disables POP3" OFF)
mark_as_advanced(CURL_DISABLE_POP3)
option(CURL_DISABLE_PROGRESS_METER "disables built-in progress meter" OFF)
mark_as_advanced(CURL_DISABLE_PROGRESS_METER)
option(CURL_DISABLE_PROXY "disables proxy support" OFF)
mark_as_advanced(CURL_DISABLE_PROXY)
option(CURL_DISABLE_RTSP "disables RTSP" OFF)
mark_as_advanced(CURL_DISABLE_RTSP)
option(CURL_DISABLE_SHUFFLE_DNS "disables shuffle DNS feature" OFF)
mark_as_advanced(CURL_DISABLE_SHUFFLE_DNS)
option(CURL_DISABLE_SMB "disables SMB" OFF)
mark_as_advanced(CURL_DISABLE_SMB)
option(CURL_DISABLE_SMTP "disables SMTP" OFF)
mark_as_advanced(CURL_DISABLE_SMTP)
option(CURL_DISABLE_SOCKETPAIR "disables use of socketpair for curl_multi_poll" OFF)
mark_as_advanced(CURL_DISABLE_SOCKETPAIR)
option(CURL_DISABLE_TELNET "disables Telnet" OFF)
mark_as_advanced(CURL_DISABLE_TELNET)
option(CURL_DISABLE_TFTP "disables TFTP" OFF)
mark_as_advanced(CURL_DISABLE_TFTP)
option(CURL_DISABLE_VERBOSE_STRINGS "disables verbose strings" OFF)
mark_as_advanced(CURL_DISABLE_VERBOSE_STRINGS)
# Corresponds to HTTP_ONLY in lib/curl_setup.h
option(HTTP_ONLY "disables all protocols except HTTP (This overrides all CURL_DISABLE_* options)" OFF)
mark_as_advanced(HTTP_ONLY)
if(HTTP_ONLY)
set(CURL_DISABLE_DICT ON)
set(CURL_DISABLE_FILE ON)
set(CURL_DISABLE_FTP ON)
set(CURL_DISABLE_GOPHER ON)
set(CURL_DISABLE_IMAP ON)
set(CURL_DISABLE_LDAP ON)
set(CURL_DISABLE_LDAPS ON)
set(CURL_DISABLE_MQTT ON)
set(CURL_DISABLE_POP3 ON)
set(CURL_DISABLE_RTSP ON)
set(CURL_DISABLE_SMB ON)
set(CURL_DISABLE_SMTP ON)
set(CURL_DISABLE_TELNET ON)
set(CURL_DISABLE_TFTP ON)
endif()
option(ENABLE_IPV6 "Define if you want to enable IPv6 support" ON)
mark_as_advanced(ENABLE_IPV6)
if(ENABLE_IPV6 AND NOT WIN32)
include(CheckStructHasMember)
check_struct_has_member("struct sockaddr_in6" sin6_addr "netinet/in.h"
HAVE_SOCKADDR_IN6_SIN6_ADDR)
check_struct_has_member("struct sockaddr_in6" sin6_scope_id "netinet/in.h"
HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID)
if(NOT HAVE_SOCKADDR_IN6_SIN6_ADDR)
message(WARNING "struct sockaddr_in6 not available, disabling IPv6 support")
# Force the feature off as this name is used as guard macro...
set(ENABLE_IPV6 OFF
CACHE BOOL "Define if you want to enable IPv6 support" FORCE)
endif()
if(CMAKE_SYSTEM_NAME STREQUAL "Darwin" AND NOT ENABLE_ARES)
set(use_core_foundation ON)
find_library(SYSTEMCONFIGURATION_FRAMEWORK "SystemConfiguration")
if(NOT SYSTEMCONFIGURATION_FRAMEWORK)
message(FATAL_ERROR "SystemConfiguration framework not found")
endif()
list(APPEND CURL_LIBS "-framework SystemConfiguration")
endif()
endif()
if(USE_MANUAL)
#nroff is currently only used when USE_MANUAL is set, so we can prevent the warning of no *NROFF if USE_MANUAL is OFF (or not defined), by not even looking for NROFF..
curl_nroff_check()
endif()
find_package(Perl)
cmake_dependent_option(ENABLE_MANUAL "to provide the built-in manual"
ON "NROFF_USEFUL;PERL_FOUND"
OFF)
if(ENABLE_MANUAL)
set(USE_MANUAL ON)
endif()
if(CURL_STATIC_CRT)
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} /MT")
set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /MTd")
endif()
# Disable warnings on Borland to avoid changing 3rd party code.
if(BORLAND)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -w-")
endif()
# If we are on AIX, do the _ALL_SOURCE magic
if(${CMAKE_SYSTEM_NAME} MATCHES AIX)
set(_ALL_SOURCE 1)
endif()
# Include all the necessary files for macros
include(CMakePushCheckState)
include(CheckFunctionExists)
include(CheckIncludeFile)
include(CheckIncludeFiles)
include(CheckLibraryExists)
include(CheckSymbolExists)
include(CheckTypeSize)
include(CheckCSourceCompiles)
# On windows preload settings
if(WIN32)
set(CMAKE_REQUIRED_DEFINITIONS "${CMAKE_REQUIRED_DEFINITIONS} -D_WINSOCKAPI_=")
include(${CMAKE_CURRENT_SOURCE_DIR}/CMake/Platforms/WindowsCache.cmake)
endif()
if(ENABLE_THREADED_RESOLVER)
find_package(Threads REQUIRED)
if(WIN32)
set(USE_THREADS_WIN32 ON)
else()
set(USE_THREADS_POSIX ${CMAKE_USE_PTHREADS_INIT})
set(HAVE_PTHREAD_H ${CMAKE_USE_PTHREADS_INIT})
endif()
set(CURL_LIBS ${CURL_LIBS} ${CMAKE_THREAD_LIBS_INIT})
endif()
# Check for all needed libraries
check_library_exists_concat("${CMAKE_DL_LIBS}" dlopen HAVE_LIBDL)
check_library_exists_concat("socket" connect HAVE_LIBSOCKET)
check_library_exists("c" gethostbyname "" NOT_NEED_LIBNSL)
# Yellowtab Zeta needs different libraries than BeOS 5.
if(BEOS)
set(NOT_NEED_LIBNSL 1)
check_library_exists_concat("bind" gethostbyname HAVE_LIBBIND)
check_library_exists_concat("bnetapi" closesocket HAVE_LIBBNETAPI)
endif()
if(NOT NOT_NEED_LIBNSL)
check_library_exists_concat("nsl" gethostbyname HAVE_LIBNSL)
endif()
check_function_exists(gethostname HAVE_GETHOSTNAME)
if(WIN32)
check_library_exists_concat("ws2_32" getch HAVE_LIBWS2_32)
check_library_exists_concat("winmm" getch HAVE_LIBWINMM)
endif()
# check SSL libraries
# TODO support GnuTLS
option(CURL_ENABLE_SSL "Enable SSL support" ON)
if(CMAKE_USE_WINSSL)
message(FATAL_ERROR "The cmake option CMAKE_USE_WINSSL was renamed to CMAKE_USE_SCHANNEL.")
endif()
if(APPLE)
cmake_dependent_option(CMAKE_USE_SECTRANSP "enable Apple OS native SSL/TLS" OFF CURL_ENABLE_SSL OFF)
endif()
if(WIN32)
cmake_dependent_option(CMAKE_USE_SCHANNEL "enable Windows native SSL/TLS" OFF CURL_ENABLE_SSL OFF)
cmake_dependent_option(CURL_WINDOWS_SSPI "Use windows libraries to allow NTLM authentication without openssl" ON
CMAKE_USE_SCHANNEL OFF)
endif()
cmake_dependent_option(CMAKE_USE_MBEDTLS "Enable mbedTLS for SSL/TLS" OFF CURL_ENABLE_SSL OFF)
cmake_dependent_option(CMAKE_USE_BEARSSL "Enable BearSSL for SSL/TLS" OFF CURL_ENABLE_SSL OFF)
cmake_dependent_option(CMAKE_USE_NSS "Enable NSS for SSL/TLS" OFF CURL_ENABLE_SSL OFF)
cmake_dependent_option(CMAKE_USE_WOLFSSL "enable wolfSSL for SSL/TLS" OFF CURL_ENABLE_SSL OFF)
set(openssl_default ON)
if(WIN32 OR CMAKE_USE_SECTRANSP OR CMAKE_USE_SCHANNEL OR CMAKE_USE_MBEDTLS OR CMAKE_USE_NSS OR CMAKE_USE_WOLFSSL)
set(openssl_default OFF)
endif()
cmake_dependent_option(CMAKE_USE_OPENSSL "Use OpenSSL code. Experimental" ${openssl_default} CURL_ENABLE_SSL OFF)
option(CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG "Disable automatic loading of OpenSSL configuration" OFF)
count_true(enabled_ssl_options_count
CMAKE_USE_SCHANNEL
CMAKE_USE_SECTRANSP
CMAKE_USE_OPENSSL
CMAKE_USE_MBEDTLS
CMAKE_USE_BEARSSL
CMAKE_USE_NSS
CMAKE_USE_WOLFSSL
)
if(enabled_ssl_options_count GREATER "1")
set(CURL_WITH_MULTI_SSL ON)
endif()
if(CMAKE_USE_SCHANNEL)
set(SSL_ENABLED ON)
set(USE_SCHANNEL ON) # Windows native SSL/TLS support
set(USE_WINDOWS_SSPI ON) # CMAKE_USE_SCHANNEL implies CURL_WINDOWS_SSPI
endif()
if(CURL_WINDOWS_SSPI)
set(USE_WINDOWS_SSPI ON)
set(CMAKE_REQUIRED_DEFINITIONS "${CMAKE_REQUIRED_DEFINITIONS} -DSECURITY_WIN32")
endif()
if(CMAKE_USE_DARWINSSL)
message(FATAL_ERROR "The cmake option CMAKE_USE_DARWINSSL was renamed to CMAKE_USE_SECTRANSP.")
endif()
if(CMAKE_USE_SECTRANSP)
set(use_core_foundation ON)
find_library(SECURITY_FRAMEWORK "Security")
if(NOT SECURITY_FRAMEWORK)
message(FATAL_ERROR "Security framework not found")
endif()
set(SSL_ENABLED ON)
set(USE_SECTRANSP ON)
list(APPEND CURL_LIBS "-framework Security")
endif()
if(use_core_foundation)
find_library(COREFOUNDATION_FRAMEWORK "CoreFoundation")
if(NOT COREFOUNDATION_FRAMEWORK)
message(FATAL_ERROR "CoreFoundation framework not found")
endif()
list(APPEND CURL_LIBS "-framework CoreFoundation")
endif()
if(CMAKE_USE_OPENSSL)
find_package(OpenSSL REQUIRED)
set(SSL_ENABLED ON)
set(USE_OPENSSL ON)
# Depend on OpenSSL via imported targets if supported by the running
# version of CMake. This allows our dependents to get our dependencies
# transitively.
if(NOT CMAKE_VERSION VERSION_LESS 3.4)
list(APPEND CURL_LIBS OpenSSL::SSL OpenSSL::Crypto)
else()
list(APPEND CURL_LIBS ${OPENSSL_LIBRARIES})
include_directories(${OPENSSL_INCLUDE_DIR})
endif()
set(CMAKE_REQUIRED_INCLUDES ${OPENSSL_INCLUDE_DIR})
check_include_file("openssl/crypto.h" HAVE_OPENSSL_CRYPTO_H)
check_include_file("openssl/err.h" HAVE_OPENSSL_ERR_H)
check_include_file("openssl/pem.h" HAVE_OPENSSL_PEM_H)
check_include_file("openssl/rsa.h" HAVE_OPENSSL_RSA_H)
check_include_file("openssl/ssl.h" HAVE_OPENSSL_SSL_H)
check_include_file("openssl/x509.h" HAVE_OPENSSL_X509_H)
check_include_file("openssl/rand.h" HAVE_OPENSSL_RAND_H)
check_symbol_exists(RAND_status "${CURL_INCLUDES}" HAVE_RAND_STATUS)
check_symbol_exists(RAND_screen "${CURL_INCLUDES}" HAVE_RAND_SCREEN)
check_symbol_exists(RAND_egd "${CURL_INCLUDES}" HAVE_RAND_EGD)
add_definitions(-DOPENSSL_SUPPRESS_DEPRECATED)
endif()
if(CMAKE_USE_MBEDTLS)
find_package(MbedTLS REQUIRED)
set(SSL_ENABLED ON)
set(USE_MBEDTLS ON)
list(APPEND CURL_LIBS ${MBEDTLS_LIBRARIES})
include_directories(${MBEDTLS_INCLUDE_DIRS})
endif()
if(CMAKE_USE_BEARSSL)
find_package(BearSSL REQUIRED)
set(SSL_ENABLED ON)
set(USE_BEARSSL ON)
list(APPEND CURL_LIBS ${BEARSSL_LIBRARY})
include_directories(${BEARSSL_INCLUDE_DIRS})
endif()
if(CMAKE_USE_WOLFSSL)
find_package(WolfSSL REQUIRED)
set(SSL_ENABLED ON)
set(USE_WOLFSSL ON)
list(APPEND CURL_LIBS ${WolfSSL_LIBRARIES})
include_directories(${WolfSSL_INCLUDE_DIRS})
endif()
if(CMAKE_USE_NSS)
find_package(NSS REQUIRED)
include_directories(${NSS_INCLUDE_DIRS})
list(APPEND CURL_LIBS ${NSS_LIBRARIES})
set(SSL_ENABLED ON)
set(USE_NSS ON)
cmake_push_check_state()
set(CMAKE_REQUIRED_INCLUDES ${NSS_INCLUDE_DIRS})
set(CMAKE_REQUIRED_LIBRARIES ${NSS_LIBRARIES})
check_symbol_exists(PK11_CreateManagedGenericObject "pk11pub.h" HAVE_PK11_CREATEMANAGEDGENERICOBJECT)
cmake_pop_check_state()
endif()
option(USE_NGHTTP2 "Use Nghttp2 library" OFF)
if(USE_NGHTTP2)
find_package(NGHTTP2 REQUIRED)
include_directories(${NGHTTP2_INCLUDE_DIRS})
list(APPEND CURL_LIBS ${NGHTTP2_LIBRARIES})
endif()
function(CheckQuicSupportInOpenSSL)
# Be sure that the OpenSSL library actually supports QUIC.
cmake_push_check_state()
set(CMAKE_REQUIRED_INCLUDES "${OPENSSL_INCLUDE_DIR}")
set(CMAKE_REQUIRED_LIBRARIES "${OPENSSL_LIBRARIES}")
check_symbol_exists(SSL_CTX_set_quic_method "openssl/ssl.h" HAVE_SSL_CTX_SET_QUIC_METHOD)
if(NOT HAVE_SSL_CTX_SET_QUIC_METHOD)
message(FATAL_ERROR "QUIC support is missing in OpenSSL/boringssl. Try setting -DOPENSSL_ROOT_DIR")
endif()
cmake_pop_check_state()
endfunction()
option(USE_NGTCP2 "Use ngtcp2 and nghttp3 libraries for HTTP/3 support" OFF)
if(USE_NGTCP2)
if(USE_OPENSSL)
find_package(NGTCP2 REQUIRED OpenSSL)
CheckQuicSupportInOpenSSL()
elseif(USE_GNUTLS)
# TODO add GnuTLS support as vtls library.
find_package(NGTCP2 REQUIRED GnuTLS)
else()
message(FATAL_ERROR "ngtcp2 requires OpenSSL or GnuTLS")
endif()
set(USE_NGTCP2 ON)
include_directories(${NGTCP2_INCLUDE_DIRS})
list(APPEND CURL_LIBS ${NGTCP2_LIBRARIES})
find_package(NGHTTP3 REQUIRED)
set(USE_NGHTTP3 ON)
include_directories(${NGHTTP3_INCLUDE_DIRS})
list(APPEND CURL_LIBS ${NGHTTP3_LIBRARIES})
endif()
option(USE_QUICHE "Use quiche library for HTTP/3 support" OFF)
if(USE_QUICHE)
if(USE_NGTCP2)
message(FATAL_ERROR "Only one HTTP/3 backend can be selected!")
endif()
find_package(QUICHE REQUIRED)
CheckQuicSupportInOpenSSL()
set(USE_QUICHE ON)
include_directories(${QUICHE_INCLUDE_DIRS})
list(APPEND CURL_LIBS ${QUICHE_LIBRARIES})
cmake_push_check_state()
set(CMAKE_REQUIRED_INCLUDES "${QUICHE_INCLUDE_DIRS}")
set(CMAKE_REQUIRED_LIBRARIES "${QUICHE_LIBRARIES}")
check_symbol_exists(quiche_conn_set_qlog_fd "quiche.h" HAVE_QUICHE_CONN_SET_QLOG_FD)
cmake_pop_check_state()
endif()
if(NOT CURL_DISABLE_LDAP)
if(WIN32)
option(USE_WIN32_LDAP "Use Windows LDAP implementation" ON)
if(USE_WIN32_LDAP)
check_library_exists_concat("wldap32" cldap_open HAVE_WLDAP32)
if(NOT HAVE_WLDAP32)
set(USE_WIN32_LDAP OFF)
endif()
endif()
endif()
option(CMAKE_USE_OPENLDAP "Use OpenLDAP code." OFF)
mark_as_advanced(CMAKE_USE_OPENLDAP)
set(CMAKE_LDAP_LIB "ldap" CACHE STRING "Name or full path to ldap library")
set(CMAKE_LBER_LIB "lber" CACHE STRING "Name or full path to lber library")
if(CMAKE_USE_OPENLDAP AND USE_WIN32_LDAP)
message(FATAL_ERROR "Cannot use USE_WIN32_LDAP and CMAKE_USE_OPENLDAP at the same time")
endif()
# Now that we know, we're not using windows LDAP...
if(USE_WIN32_LDAP)
check_include_file_concat("winldap.h" HAVE_WINLDAP_H)
check_include_file_concat("winber.h" HAVE_WINBER_H)
else()
# Check for LDAP
set(CMAKE_REQUIRED_LIBRARIES ${OPENSSL_LIBRARIES})
check_library_exists_concat(${CMAKE_LDAP_LIB} ldap_init HAVE_LIBLDAP)
check_library_exists_concat(${CMAKE_LBER_LIB} ber_init HAVE_LIBLBER)
set(CMAKE_REQUIRED_INCLUDES_BAK ${CMAKE_REQUIRED_INCLUDES})
set(CMAKE_LDAP_INCLUDE_DIR "" CACHE STRING "Path to LDAP include directory")
if(CMAKE_LDAP_INCLUDE_DIR)
list(APPEND CMAKE_REQUIRED_INCLUDES ${CMAKE_LDAP_INCLUDE_DIR})
endif()
check_include_file_concat("ldap.h" HAVE_LDAP_H)
check_include_file_concat("lber.h" HAVE_LBER_H)
if(NOT HAVE_LDAP_H)
message(STATUS "LDAP_H not found CURL_DISABLE_LDAP set ON")
set(CURL_DISABLE_LDAP ON CACHE BOOL "" FORCE)
set(CMAKE_REQUIRED_INCLUDES ${CMAKE_REQUIRED_INCLUDES_BAK}) #LDAP includes won't be used
elseif(NOT HAVE_LIBLDAP)
message(STATUS "LDAP library '${CMAKE_LDAP_LIB}' not found CURL_DISABLE_LDAP set ON")
set(CURL_DISABLE_LDAP ON CACHE BOOL "" FORCE)
set(CMAKE_REQUIRED_INCLUDES ${CMAKE_REQUIRED_INCLUDES_BAK}) #LDAP includes won't be used
else()
if(CMAKE_USE_OPENLDAP)
set(USE_OPENLDAP ON)
endif()
if(CMAKE_LDAP_INCLUDE_DIR)
include_directories(${CMAKE_LDAP_INCLUDE_DIR})
endif()
set(NEED_LBER_H ON)
set(_HEADER_LIST)
if(HAVE_WINDOWS_H)
list(APPEND _HEADER_LIST "windows.h")
endif()
if(HAVE_SYS_TYPES_H)
list(APPEND _HEADER_LIST "sys/types.h")
endif()
list(APPEND _HEADER_LIST "ldap.h")
set(_SRC_STRING "")
foreach(_HEADER ${_HEADER_LIST})
set(_INCLUDE_STRING "${_INCLUDE_STRING}#include <${_HEADER}>\n")
endforeach()
set(_SRC_STRING
"
${_INCLUDE_STRING}
int main(int argc, char ** argv)
{
BerValue *bvp = NULL;
BerElement *bep = ber_init(bvp);
ber_free(bep, 1);
return 0;
}"
)
set(CMAKE_REQUIRED_DEFINITIONS "${CMAKE_REQUIRED_DEFINITIONS} -DLDAP_DEPRECATED=1")
list(APPEND CMAKE_REQUIRED_LIBRARIES ${CMAKE_LDAP_LIB})
if(HAVE_LIBLBER)
list(APPEND CMAKE_REQUIRED_LIBRARIES ${CMAKE_LBER_LIB})
endif()
check_c_source_compiles("${_SRC_STRING}" NOT_NEED_LBER_H)
unset(CMAKE_REQUIRED_LIBRARIES)
if(NOT_NEED_LBER_H)
set(NEED_LBER_H OFF)
else()
set(CURL_TEST_DEFINES "${CURL_TEST_DEFINES} -DNEED_LBER_H")
endif()
endif()
endif()
endif()
# No ldap, no ldaps.
if(CURL_DISABLE_LDAP)
if(NOT CURL_DISABLE_LDAPS)
message(STATUS "LDAP needs to be enabled to support LDAPS")
set(CURL_DISABLE_LDAPS ON CACHE BOOL "" FORCE)
endif()
endif()
if(NOT CURL_DISABLE_LDAPS)
check_include_file_concat("ldap_ssl.h" HAVE_LDAP_SSL_H)
check_include_file_concat("ldapssl.h" HAVE_LDAPSSL_H)
endif()
# Check for idn
option(USE_LIBIDN2 "Use libidn2 for IDN support" ON)
set(HAVE_LIBIDN2 OFF)
if(USE_LIBIDN2)
check_library_exists_concat("idn2" idn2_lookup_ul HAVE_LIBIDN2)
endif()
if(WIN32)
option(USE_WIN32_IDN "Use WinIDN for IDN support" OFF)
if(USE_WIN32_IDN)
list(APPEND CURL_LIBS "Normaliz")
set(WANT_IDN_PROTOTYPES ON)
endif()
endif()
# Check for symbol dlopen (same as HAVE_LIBDL)
check_library_exists("${CURL_LIBS}" dlopen "" HAVE_DLOPEN)
set(HAVE_LIBZ OFF)
set(HAVE_ZLIB_H OFF)
set(USE_ZLIB OFF)
optional_dependency(ZLIB)
if(ZLIB_FOUND)
set(HAVE_ZLIB_H ON)
set(HAVE_LIBZ ON)
set(USE_ZLIB ON)
# Depend on ZLIB via imported targets if supported by the running
# version of CMake. This allows our dependents to get our dependencies
# transitively.
if(NOT CMAKE_VERSION VERSION_LESS 3.4)
list(APPEND CURL_LIBS ZLIB::ZLIB)
else()
list(APPEND CURL_LIBS ${ZLIB_LIBRARIES})
include_directories(${ZLIB_INCLUDE_DIRS})
endif()
list(APPEND CMAKE_REQUIRED_INCLUDES ${ZLIB_INCLUDE_DIRS})
endif()
option(CURL_BROTLI "Set to ON to enable building curl with brotli support." OFF)
set(HAVE_BROTLI OFF)
if(CURL_BROTLI)
find_package(Brotli QUIET)
if(BROTLI_FOUND)
set(HAVE_BROTLI ON)
list(APPEND CURL_LIBS ${BROTLI_LIBRARIES})
include_directories(${BROTLI_INCLUDE_DIRS})
list(APPEND CMAKE_REQUIRED_INCLUDES ${BROTLI_INCLUDE_DIRS})
endif()
endif()
option(CURL_ZSTD "Set to ON to enable building curl with zstd support." OFF)
set(HAVE_ZSTD OFF)
if(CURL_ZSTD)
find_package(Zstd REQUIRED)
cmake_push_check_state()
set(CMAKE_REQUIRED_INCLUDES ${Zstd_INCLUDE_DIRS})
set(CMAKE_REQUIRED_LIBRARIES ${Zstd_LIBRARIES})
check_symbol_exists(ZSTD_createDStream "zstd.h" HAVE_ZSTD_CREATEDSTREAM)
cmake_pop_check_state()
if(Zstd_FOUND AND HAVE_ZSTD_CREATEDSTREAM)
set(HAVE_ZSTD ON)
list(APPEND CURL_LIBS ${Zstd_LIBRARIES})
include_directories(${Zstd_INCLUDE_DIRS})
endif()
endif()
#libSSH2
option(CMAKE_USE_LIBSSH2 "Use libSSH2" ON)
mark_as_advanced(CMAKE_USE_LIBSSH2)
set(USE_LIBSSH2 OFF)
set(HAVE_LIBSSH2 OFF)
set(HAVE_LIBSSH2_H OFF)
if(CMAKE_USE_LIBSSH2)
find_package(LibSSH2)
if(LIBSSH2_FOUND)
list(APPEND CURL_LIBS ${LIBSSH2_LIBRARY})
set(CMAKE_REQUIRED_LIBRARIES ${LIBSSH2_LIBRARY})
list(APPEND CMAKE_REQUIRED_INCLUDES "${LIBSSH2_INCLUDE_DIR}")
include_directories("${LIBSSH2_INCLUDE_DIR}")
set(HAVE_LIBSSH2 ON)
set(USE_LIBSSH2 ON)
# find_package has already found the headers
set(HAVE_LIBSSH2_H ON)
set(CURL_INCLUDES ${CURL_INCLUDES} "${LIBSSH2_INCLUDE_DIR}/libssh2.h")
set(CURL_TEST_DEFINES "${CURL_TEST_DEFINES} -DHAVE_LIBSSH2_H")
unset(CMAKE_REQUIRED_LIBRARIES)
endif()
endif()
# libssh
option(CMAKE_USE_LIBSSH "Use libSSH" OFF)
mark_as_advanced(CMAKE_USE_LIBSSH)
if(NOT HAVE_LIBSSH2 AND CMAKE_USE_LIBSSH)
find_package(libssh CONFIG)
if(libssh_FOUND)
message(STATUS "Found libssh ${libssh_VERSION}")
# Use imported target for include and library paths.
list(APPEND CURL_LIBS ssh)
set(USE_LIBSSH ON)
set(HAVE_LIBSSH_LIBSSH_H 1)
endif()
endif()
option(CMAKE_USE_GSSAPI "Use GSSAPI implementation (right now only Heimdal is supported with CMake build)" OFF)
mark_as_advanced(CMAKE_USE_GSSAPI)
if(CMAKE_USE_GSSAPI)
find_package(GSS)
set(HAVE_GSSAPI ${GSS_FOUND})
if(GSS_FOUND)
message(STATUS "Found ${GSS_FLAVOUR} GSSAPI version: \"${GSS_VERSION}\"")
list(APPEND CMAKE_REQUIRED_INCLUDES ${GSS_INCLUDE_DIR})
check_include_file_concat("gssapi/gssapi.h" HAVE_GSSAPI_GSSAPI_H)
check_include_file_concat("gssapi/gssapi_generic.h" HAVE_GSSAPI_GSSAPI_GENERIC_H)
check_include_file_concat("gssapi/gssapi_krb5.h" HAVE_GSSAPI_GSSAPI_KRB5_H)
if(GSS_FLAVOUR STREQUAL "Heimdal")
set(HAVE_GSSHEIMDAL ON)
else() # MIT
set(HAVE_GSSMIT ON)
set(_INCLUDE_LIST "")
if(HAVE_GSSAPI_GSSAPI_H)
list(APPEND _INCLUDE_LIST "gssapi/gssapi.h")
endif()
if(HAVE_GSSAPI_GSSAPI_GENERIC_H)
list(APPEND _INCLUDE_LIST "gssapi/gssapi_generic.h")
endif()
if(HAVE_GSSAPI_GSSAPI_KRB5_H)
list(APPEND _INCLUDE_LIST "gssapi/gssapi_krb5.h")
endif()
string(REPLACE ";" " " _COMPILER_FLAGS_STR "${GSS_COMPILER_FLAGS}")
string(REPLACE ";" " " _LINKER_FLAGS_STR "${GSS_LINKER_FLAGS}")
foreach(_dir ${GSS_LINK_DIRECTORIES})
set(_LINKER_FLAGS_STR "${_LINKER_FLAGS_STR} -L\"${_dir}\"")
endforeach()
set(CMAKE_REQUIRED_FLAGS "${_COMPILER_FLAGS_STR} ${_LINKER_FLAGS_STR}")
set(CMAKE_REQUIRED_LIBRARIES ${GSS_LIBRARIES})
check_symbol_exists("GSS_C_NT_HOSTBASED_SERVICE" ${_INCLUDE_LIST} HAVE_GSS_C_NT_HOSTBASED_SERVICE)
if(NOT HAVE_GSS_C_NT_HOSTBASED_SERVICE)
set(HAVE_OLD_GSSMIT ON)
endif()
unset(CMAKE_REQUIRED_LIBRARIES)
endif()
include_directories(${GSS_INCLUDE_DIR})
link_directories(${GSS_LINK_DIRECTORIES})
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${GSS_COMPILER_FLAGS}")
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${GSS_LINKER_FLAGS}")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${GSS_LINKER_FLAGS}")
set(CMAKE_STATIC_LINKER_FLAGS "${CMAKE_STATIC_LINKER_FLAGS} ${GSS_LINKER_FLAGS}")
list(APPEND CURL_LIBS ${GSS_LIBRARIES})
else()
message(WARNING "GSSAPI support has been requested but no supporting libraries found. Skipping.")
endif()
endif()
option(ENABLE_UNIX_SOCKETS "Define if you want Unix domain sockets support" ON)
if(ENABLE_UNIX_SOCKETS)
include(CheckStructHasMember)
if(WIN32)
set(USE_UNIX_SOCKETS ON)
else()
check_struct_has_member("struct sockaddr_un" sun_path "sys/un.h" USE_UNIX_SOCKETS)
endif()
else()
unset(USE_UNIX_SOCKETS CACHE)
endif()
#
# CA handling
#
set(CURL_CA_BUNDLE "auto" CACHE STRING
"Path to the CA bundle. Set 'none' to disable or 'auto' for auto-detection. Defaults to 'auto'.")
set(CURL_CA_FALLBACK OFF CACHE BOOL
"Set ON to use built-in CA store of TLS backend. Defaults to OFF")
set(CURL_CA_PATH "auto" CACHE STRING
"Location of default CA path. Set 'none' to disable or 'auto' for auto-detection. Defaults to 'auto'.")
if("${CURL_CA_BUNDLE}" STREQUAL "")
message(FATAL_ERROR "Invalid value of CURL_CA_BUNDLE. Use 'none', 'auto' or file path.")
elseif("${CURL_CA_BUNDLE}" STREQUAL "none")
unset(CURL_CA_BUNDLE CACHE)
elseif("${CURL_CA_BUNDLE}" STREQUAL "auto")
unset(CURL_CA_BUNDLE CACHE)
set(CURL_CA_BUNDLE_AUTODETECT TRUE)
else()
set(CURL_CA_BUNDLE_SET TRUE)
endif()
if("${CURL_CA_PATH}" STREQUAL "")
message(FATAL_ERROR "Invalid value of CURL_CA_PATH. Use 'none', 'auto' or directory path.")
elseif("${CURL_CA_PATH}" STREQUAL "none")
unset(CURL_CA_PATH CACHE)
elseif("${CURL_CA_PATH}" STREQUAL "auto")
unset(CURL_CA_PATH CACHE)
if(NOT USE_NSS)
set(CURL_CA_PATH_AUTODETECT TRUE)
endif()
else()
set(CURL_CA_PATH_SET TRUE)
endif()
if(CURL_CA_BUNDLE_SET AND CURL_CA_PATH_AUTODETECT)
# Skip autodetection of unset CA path because CA bundle is set explicitly
elseif(CURL_CA_PATH_SET AND CURL_CA_BUNDLE_AUTODETECT)
# Skip autodetection of unset CA bundle because CA path is set explicitly
elseif(CURL_CA_PATH_AUTODETECT OR CURL_CA_BUNDLE_AUTODETECT)
# first try autodetecting a CA bundle, then a CA path
if(CURL_CA_BUNDLE_AUTODETECT)
set(SEARCH_CA_BUNDLE_PATHS
/etc/ssl/certs/ca-certificates.crt
/etc/pki/tls/certs/ca-bundle.crt
/usr/share/ssl/certs/ca-bundle.crt
/usr/local/share/certs/ca-root-nss.crt
/etc/ssl/cert.pem)
foreach(SEARCH_CA_BUNDLE_PATH ${SEARCH_CA_BUNDLE_PATHS})
if(EXISTS "${SEARCH_CA_BUNDLE_PATH}")
message(STATUS "Found CA bundle: ${SEARCH_CA_BUNDLE_PATH}")
set(CURL_CA_BUNDLE "${SEARCH_CA_BUNDLE_PATH}" CACHE STRING
"Path to the CA bundle. Set 'none' to disable or 'auto' for auto-detection. Defaults to 'auto'.")
set(CURL_CA_BUNDLE_SET TRUE CACHE BOOL "Path to the CA bundle has been set")
break()
endif()
endforeach()
endif()
if(CURL_CA_PATH_AUTODETECT AND (NOT CURL_CA_PATH_SET))
if(EXISTS "/etc/ssl/certs")
set(CURL_CA_PATH "/etc/ssl/certs" CACHE STRING
"Location of default CA path. Set 'none' to disable or 'auto' for auto-detection. Defaults to 'auto'.")
set(CURL_CA_PATH_SET TRUE CACHE BOOL "Path to the CA bundle has been set")
endif()
endif()
endif()
if(CURL_CA_PATH_SET AND NOT USE_OPENSSL AND NOT USE_MBEDTLS)
message(STATUS
"CA path only supported by OpenSSL, GnuTLS or mbed TLS. "
"Set CURL_CA_PATH=none or enable one of those TLS backends.")
endif()
# Check for header files
if(NOT UNIX)
check_include_file_concat("windows.h" HAVE_WINDOWS_H)
check_include_file_concat("ws2tcpip.h" HAVE_WS2TCPIP_H)
check_include_file_concat("winsock2.h" HAVE_WINSOCK2_H)
check_include_file_concat("wincrypt.h" HAVE_WINCRYPT_H)
endif()
check_include_file_concat("stdio.h" HAVE_STDIO_H)
check_include_file_concat("inttypes.h" HAVE_INTTYPES_H)
check_include_file_concat("sys/filio.h" HAVE_SYS_FILIO_H)
check_include_file_concat("sys/ioctl.h" HAVE_SYS_IOCTL_H)
check_include_file_concat("sys/param.h" HAVE_SYS_PARAM_H)
check_include_file_concat("sys/poll.h" HAVE_SYS_POLL_H)
check_include_file_concat("sys/resource.h" HAVE_SYS_RESOURCE_H)
check_include_file_concat("sys/select.h" HAVE_SYS_SELECT_H)
check_include_file_concat("sys/socket.h" HAVE_SYS_SOCKET_H)
check_include_file_concat("sys/sockio.h" HAVE_SYS_SOCKIO_H)
check_include_file_concat("sys/stat.h" HAVE_SYS_STAT_H)
check_include_file_concat("sys/time.h" HAVE_SYS_TIME_H)
check_include_file_concat("sys/types.h" HAVE_SYS_TYPES_H)
check_include_file_concat("sys/uio.h" HAVE_SYS_UIO_H)
check_include_file_concat("sys/un.h" HAVE_SYS_UN_H)
check_include_file_concat("sys/utime.h" HAVE_SYS_UTIME_H)
check_include_file_concat("sys/xattr.h" HAVE_SYS_XATTR_H)
check_include_file_concat("alloca.h" HAVE_ALLOCA_H)
check_include_file_concat("arpa/inet.h" HAVE_ARPA_INET_H)
check_include_file_concat("arpa/tftp.h" HAVE_ARPA_TFTP_H)
check_include_file_concat("assert.h" HAVE_ASSERT_H)
check_include_file_concat("errno.h" HAVE_ERRNO_H)
check_include_file_concat("fcntl.h" HAVE_FCNTL_H)
check_include_file_concat("idn2.h" HAVE_IDN2_H)
check_include_file_concat("ifaddrs.h" HAVE_IFADDRS_H)
check_include_file_concat("io.h" HAVE_IO_H)
check_include_file_concat("krb.h" HAVE_KRB_H)
check_include_file_concat("libgen.h" HAVE_LIBGEN_H)
check_include_file_concat("locale.h" HAVE_LOCALE_H)
check_include_file_concat("net/if.h" HAVE_NET_IF_H)
check_include_file_concat("netdb.h" HAVE_NETDB_H)
check_include_file_concat("netinet/in.h" HAVE_NETINET_IN_H)
check_include_file_concat("netinet/tcp.h" HAVE_NETINET_TCP_H)
check_include_file("linux/tcp.h" HAVE_LINUX_TCP_H)
check_include_file_concat("pem.h" HAVE_PEM_H)
check_include_file_concat("poll.h" HAVE_POLL_H)
check_include_file_concat("pwd.h" HAVE_PWD_H)
check_include_file_concat("setjmp.h" HAVE_SETJMP_H)
check_include_file_concat("signal.h" HAVE_SIGNAL_H)
check_include_file_concat("ssl.h" HAVE_SSL_H)
check_include_file_concat("stdbool.h" HAVE_STDBOOL_H)
check_include_file_concat("stdint.h" HAVE_STDINT_H)
check_include_file_concat("stdio.h" HAVE_STDIO_H)
check_include_file_concat("stdlib.h" HAVE_STDLIB_H)
check_include_file_concat("string.h" HAVE_STRING_H)
check_include_file_concat("strings.h" HAVE_STRINGS_H)
check_include_file_concat("stropts.h" HAVE_STROPTS_H)
check_include_file_concat("termio.h" HAVE_TERMIO_H)
check_include_file_concat("termios.h" HAVE_TERMIOS_H)
check_include_file_concat("time.h" HAVE_TIME_H)
check_include_file_concat("unistd.h" HAVE_UNISTD_H)
check_include_file_concat("utime.h" HAVE_UTIME_H)
check_include_file_concat("x509.h" HAVE_X509_H)
check_include_file_concat("process.h" HAVE_PROCESS_H)
check_include_file_concat("stddef.h" HAVE_STDDEF_H)
check_include_file_concat("dlfcn.h" HAVE_DLFCN_H)
check_include_file_concat("malloc.h" HAVE_MALLOC_H)
check_include_file_concat("memory.h" HAVE_MEMORY_H)
check_include_file_concat("netinet/if_ether.h" HAVE_NETINET_IF_ETHER_H)
check_include_file_concat("stdint.h" HAVE_STDINT_H)
check_include_file_concat("sockio.h" HAVE_SOCKIO_H)
check_include_file_concat("sys/utsname.h" HAVE_SYS_UTSNAME_H)
check_type_size(size_t SIZEOF_SIZE_T)
check_type_size(ssize_t SIZEOF_SSIZE_T)
check_type_size("long long" SIZEOF_LONG_LONG)
check_type_size("long" SIZEOF_LONG)
check_type_size("short" SIZEOF_SHORT)
check_type_size("int" SIZEOF_INT)
check_type_size("__int64" SIZEOF___INT64)
check_type_size("long double" SIZEOF_LONG_DOUBLE)
check_type_size("time_t" SIZEOF_TIME_T)
if(NOT HAVE_SIZEOF_SSIZE_T)
if(SIZEOF_LONG EQUAL SIZEOF_SIZE_T)
set(ssize_t long)
endif()
if(NOT ssize_t AND SIZEOF___INT64 EQUAL SIZEOF_SIZE_T)
set(ssize_t __int64)
endif()
endif()
# off_t is sized later, after the HAVE_FILE_OFFSET_BITS test
if(HAVE_SIZEOF_LONG_LONG)
set(HAVE_LONGLONG 1)
set(HAVE_LL 1)
endif()
find_file(RANDOM_FILE urandom /dev)
mark_as_advanced(RANDOM_FILE)
# Check for some functions that are used
if(HAVE_LIBWS2_32)
set(CMAKE_REQUIRED_LIBRARIES ws2_32)
elseif(HAVE_LIBSOCKET)
set(CMAKE_REQUIRED_LIBRARIES socket)
endif()
check_symbol_exists(basename "${CURL_INCLUDES}" HAVE_BASENAME)
check_symbol_exists(socket "${CURL_INCLUDES}" HAVE_SOCKET)
check_symbol_exists(select "${CURL_INCLUDES}" HAVE_SELECT)
check_symbol_exists(poll "${CURL_INCLUDES}" HAVE_POLL)
check_symbol_exists(strdup "${CURL_INCLUDES}" HAVE_STRDUP)
check_symbol_exists(strstr "${CURL_INCLUDES}" HAVE_STRSTR)
check_symbol_exists(strtok_r "${CURL_INCLUDES}" HAVE_STRTOK_R)
check_symbol_exists(strftime "${CURL_INCLUDES}" HAVE_STRFTIME)
check_symbol_exists(uname "${CURL_INCLUDES}" HAVE_UNAME)
check_symbol_exists(strcasecmp "${CURL_INCLUDES}" HAVE_STRCASECMP)
check_symbol_exists(stricmp "${CURL_INCLUDES}" HAVE_STRICMP)
check_symbol_exists(strcmpi "${CURL_INCLUDES}" HAVE_STRCMPI)
check_symbol_exists(strncmpi "${CURL_INCLUDES}" HAVE_STRNCMPI)
check_symbol_exists(alarm "${CURL_INCLUDES}" HAVE_ALARM)
if(NOT HAVE_STRNCMPI)
set(HAVE_STRCMPI)
endif()
check_symbol_exists(getppid "${CURL_INCLUDES}" HAVE_GETPPID)
check_symbol_exists(utimes "${CURL_INCLUDES}" HAVE_UTIMES)
check_symbol_exists(gettimeofday "${CURL_INCLUDES}" HAVE_GETTIMEOFDAY)
check_symbol_exists(inet_addr "${CURL_INCLUDES}" HAVE_INET_ADDR)
check_symbol_exists(closesocket "${CURL_INCLUDES}" HAVE_CLOSESOCKET)
check_symbol_exists(sigsetjmp "${CURL_INCLUDES}" HAVE_SIGSETJMP)
check_symbol_exists(getpass_r "${CURL_INCLUDES}" HAVE_GETPASS_R)
check_symbol_exists(getpwuid "${CURL_INCLUDES}" HAVE_GETPWUID)
check_symbol_exists(getpwuid_r "${CURL_INCLUDES}" HAVE_GETPWUID_R)
check_symbol_exists(geteuid "${CURL_INCLUDES}" HAVE_GETEUID)
check_symbol_exists(usleep "${CURL_INCLUDES}" HAVE_USLEEP)
check_symbol_exists(utime "${CURL_INCLUDES}" HAVE_UTIME)
check_symbol_exists(gmtime_r "${CURL_INCLUDES}" HAVE_GMTIME_R)
check_symbol_exists(localtime_r "${CURL_INCLUDES}" HAVE_LOCALTIME_R)
check_symbol_exists(gethostbyname "${CURL_INCLUDES}" HAVE_GETHOSTBYNAME)
check_symbol_exists(gethostbyname_r "${CURL_INCLUDES}" HAVE_GETHOSTBYNAME_R)
check_symbol_exists(signal "${CURL_INCLUDES}" HAVE_SIGNAL_FUNC)
check_symbol_exists(SIGALRM "${CURL_INCLUDES}" HAVE_SIGNAL_MACRO)
if(HAVE_SIGNAL_FUNC AND HAVE_SIGNAL_MACRO)
set(HAVE_SIGNAL 1)
endif()
check_symbol_exists(uname "${CURL_INCLUDES}" HAVE_UNAME)
check_symbol_exists(strtoll "${CURL_INCLUDES}" HAVE_STRTOLL)
check_symbol_exists(_strtoi64 "${CURL_INCLUDES}" HAVE__STRTOI64)
check_symbol_exists(strerror_r "${CURL_INCLUDES}" HAVE_STRERROR_R)
check_symbol_exists(siginterrupt "${CURL_INCLUDES}" HAVE_SIGINTERRUPT)
check_symbol_exists(getaddrinfo "${CURL_INCLUDES}" HAVE_GETADDRINFO)
check_symbol_exists(freeaddrinfo "${CURL_INCLUDES}" HAVE_FREEADDRINFO)
check_symbol_exists(pipe "${CURL_INCLUDES}" HAVE_PIPE)
check_symbol_exists(ftruncate "${CURL_INCLUDES}" HAVE_FTRUNCATE)
check_symbol_exists(getprotobyname "${CURL_INCLUDES}" HAVE_GETPROTOBYNAME)
check_symbol_exists(getpeername "${CURL_INCLUDES}" HAVE_GETPEERNAME)
check_symbol_exists(getsockname "${CURL_INCLUDES}" HAVE_GETSOCKNAME)
check_symbol_exists(if_nametoindex "${CURL_INCLUDES}" HAVE_IF_NAMETOINDEX)
check_symbol_exists(getrlimit "${CURL_INCLUDES}" HAVE_GETRLIMIT)
check_symbol_exists(setlocale "${CURL_INCLUDES}" HAVE_SETLOCALE)
check_symbol_exists(setmode "${CURL_INCLUDES}" HAVE_SETMODE)
check_symbol_exists(setrlimit "${CURL_INCLUDES}" HAVE_SETRLIMIT)
check_symbol_exists(fcntl "${CURL_INCLUDES}" HAVE_FCNTL)
check_symbol_exists(ioctl "${CURL_INCLUDES}" HAVE_IOCTL)
check_symbol_exists(setsockopt "${CURL_INCLUDES}" HAVE_SETSOCKOPT)
check_function_exists(mach_absolute_time HAVE_MACH_ABSOLUTE_TIME)
check_symbol_exists(inet_pton "${CURL_INCLUDES}" HAVE_INET_PTON)
check_symbol_exists(fsetxattr "${CURL_INCLUDES}" HAVE_FSETXATTR)
if(HAVE_FSETXATTR)
foreach(CURL_TEST HAVE_FSETXATTR_5 HAVE_FSETXATTR_6)
curl_internal_test(${CURL_TEST})
endforeach()
endif()
set(CMAKE_EXTRA_INCLUDE_FILES "sys/socket.h")
check_type_size("sa_family_t" SIZEOF_SA_FAMILY_T)
set(HAVE_SA_FAMILY_T ${HAVE_SIZEOF_SA_FAMILY_T})
set(CMAKE_EXTRA_INCLUDE_FILES "")
set(CMAKE_EXTRA_INCLUDE_FILES "ws2def.h")
check_type_size("ADDRESS_FAMILY" SIZEOF_ADDRESS_FAMILY)
set(HAVE_ADDRESS_FAMILY ${HAVE_SIZEOF_ADDRESS_FAMILY})
set(CMAKE_EXTRA_INCLUDE_FILES "")
# sigaction and sigsetjmp are special. Use special mechanism for
# detecting those, but only if previous attempt failed.
if(HAVE_SIGNAL_H)
check_symbol_exists(sigaction "signal.h" HAVE_SIGACTION)
endif()
if(NOT HAVE_SIGSETJMP)
if(HAVE_SETJMP_H)
check_symbol_exists(sigsetjmp "setjmp.h" HAVE_MACRO_SIGSETJMP)
if(HAVE_MACRO_SIGSETJMP)
set(HAVE_SIGSETJMP 1)
endif()
endif()
endif()
# If there is no stricmp(), do not allow LDAP to parse URLs
if(NOT HAVE_STRICMP)
set(HAVE_LDAP_URL_PARSE 1)
endif()
# Do curl specific tests
foreach(CURL_TEST
HAVE_FCNTL_O_NONBLOCK
HAVE_IOCTLSOCKET
HAVE_IOCTLSOCKET_CAMEL
HAVE_IOCTLSOCKET_CAMEL_FIONBIO
HAVE_IOCTLSOCKET_FIONBIO
HAVE_IOCTL_FIONBIO
HAVE_IOCTL_SIOCGIFADDR
HAVE_SETSOCKOPT_SO_NONBLOCK
HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
TIME_WITH_SYS_TIME
HAVE_O_NONBLOCK
HAVE_GETHOSTBYNAME_R_3
HAVE_GETHOSTBYNAME_R_5
HAVE_GETHOSTBYNAME_R_6
HAVE_GETHOSTBYNAME_R_3_REENTRANT
HAVE_GETHOSTBYNAME_R_5_REENTRANT
HAVE_GETHOSTBYNAME_R_6_REENTRANT
HAVE_IN_ADDR_T
HAVE_BOOL_T
STDC_HEADERS
HAVE_GETADDRINFO
HAVE_FILE_OFFSET_BITS
HAVE_VARIADIC_MACROS_C99
HAVE_VARIADIC_MACROS_GCC
)
curl_internal_test(${CURL_TEST})
endforeach()
if(HAVE_FILE_OFFSET_BITS)
set(_FILE_OFFSET_BITS 64)
set(CMAKE_REQUIRED_FLAGS "-D_FILE_OFFSET_BITS=64")
endif()
check_type_size("off_t" SIZEOF_OFF_T)
# include this header to get the type
set(CMAKE_REQUIRED_INCLUDES "${CURL_SOURCE_DIR}/include")
set(CMAKE_EXTRA_INCLUDE_FILES "curl/system.h")
check_type_size("curl_off_t" SIZEOF_CURL_OFF_T)
set(CMAKE_EXTRA_INCLUDE_FILES "")
set(CMAKE_REQUIRED_FLAGS)
foreach(CURL_TEST
HAVE_GLIBC_STRERROR_R
HAVE_POSIX_STRERROR_R
)
curl_internal_test(${CURL_TEST})
endforeach()
# Check for reentrant
foreach(CURL_TEST
HAVE_GETHOSTBYNAME_R_3
HAVE_GETHOSTBYNAME_R_5
HAVE_GETHOSTBYNAME_R_6)
if(NOT ${CURL_TEST})
if(${CURL_TEST}_REENTRANT)
set(NEED_REENTRANT 1)
endif()
endif()
endforeach()
if(NEED_REENTRANT)
foreach(CURL_TEST
HAVE_GETHOSTBYNAME_R_3
HAVE_GETHOSTBYNAME_R_5
HAVE_GETHOSTBYNAME_R_6)
set(${CURL_TEST} 0)
if(${CURL_TEST}_REENTRANT)
set(${CURL_TEST} 1)
endif()
endforeach()
endif()
# Check clock_gettime(CLOCK_MONOTONIC, x) support
curl_internal_test(HAVE_CLOCK_GETTIME_MONOTONIC)
# Check compiler support of __builtin_available()
curl_internal_test(HAVE_BUILTIN_AVAILABLE)
# Some other minor tests
if(NOT HAVE_IN_ADDR_T)
set(in_addr_t "unsigned long")
endif()
# Fix libz / zlib.h
if(NOT CURL_SPECIAL_LIBZ)
if(NOT HAVE_LIBZ)
set(HAVE_ZLIB_H 0)
endif()
if(NOT HAVE_ZLIB_H)
set(HAVE_LIBZ 0)
endif()
endif()
# Check for nonblocking
set(HAVE_DISABLED_NONBLOCKING 1)
if(HAVE_FIONBIO OR
HAVE_IOCTLSOCKET OR
HAVE_IOCTLSOCKET_CASE OR
HAVE_O_NONBLOCK)
set(HAVE_DISABLED_NONBLOCKING)
endif()
if(CMAKE_COMPILER_IS_GNUCC AND APPLE)
include(CheckCCompilerFlag)
check_c_compiler_flag(-Wno-long-double HAVE_C_FLAG_Wno_long_double)
if(HAVE_C_FLAG_Wno_long_double)
# The Mac version of GCC warns about use of long double. Disable it.
get_source_file_property(MPRINTF_COMPILE_FLAGS mprintf.c COMPILE_FLAGS)
if(MPRINTF_COMPILE_FLAGS)
set(MPRINTF_COMPILE_FLAGS "${MPRINTF_COMPILE_FLAGS} -Wno-long-double")
else()
set(MPRINTF_COMPILE_FLAGS "-Wno-long-double")
endif()
set_source_files_properties(mprintf.c PROPERTIES
COMPILE_FLAGS ${MPRINTF_COMPILE_FLAGS})
endif()
endif()
# TODO test which of these headers are required
if(WIN32)
set(CURL_PULL_WS2TCPIP_H ${HAVE_WS2TCPIP_H})
else()
set(CURL_PULL_SYS_TYPES_H ${HAVE_SYS_TYPES_H})
set(CURL_PULL_SYS_SOCKET_H ${HAVE_SYS_SOCKET_H})
set(CURL_PULL_SYS_POLL_H ${HAVE_SYS_POLL_H})
endif()
set(CURL_PULL_STDINT_H ${HAVE_STDINT_H})
set(CURL_PULL_INTTYPES_H ${HAVE_INTTYPES_H})
include(CMake/OtherTests.cmake)
add_definitions(-DHAVE_CONFIG_H)
# For Windows, all compilers used by CMake should support large files
if(WIN32)
set(USE_WIN32_LARGE_FILES ON)
# Use the manifest embedded in the Windows Resource
set(CMAKE_RC_FLAGS "${CMAKE_RC_FLAGS} -DCURL_EMBED_MANIFEST")
# Check if crypto functions in wincrypt.h are actually available
if(HAVE_WINCRYPT_H)
check_symbol_exists(CryptAcquireContext "${CURL_INCLUDES}" USE_WINCRYPT)
endif()
if(USE_WINCRYPT)
set(USE_WIN32_CRYPTO ON)
endif()
# Link required libraries for USE_WIN32_CRYPTO or USE_SCHANNEL
if(USE_WIN32_CRYPTO OR USE_SCHANNEL)
list(APPEND CURL_LIBS "advapi32" "crypt32")
endif()
endif()
if(MSVC)
# Disable default manifest added by CMake
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /MANIFEST:NO")
add_definitions(-D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE)
if(CMAKE_C_FLAGS MATCHES "/W[0-4]")
string(REGEX REPLACE "/W[0-4]" "/W4" CMAKE_C_FLAGS "${CMAKE_C_FLAGS}")
else()
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /W4")
endif()
# Use multithreaded compilation on VS 2008+
if(MSVC_VERSION GREATER_EQUAL 1500)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /MP")
endif()
endif()
if(CURL_WERROR)
if(MSVC_VERSION)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /WX")
else()
# this assumes clang or gcc style options
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror")
endif()
endif()
if(CURL_LTO)
if(CMAKE_VERSION VERSION_LESS 3.9)
message(FATAL_ERROR "Requested LTO but your cmake version ${CMAKE_VERSION} is to old. You need at least 3.9")
endif()
cmake_policy(SET CMP0069 NEW)
include(CheckIPOSupported)
check_ipo_supported(RESULT CURL_HAS_LTO OUTPUT CURL_LTO_ERROR LANGUAGES C)
if(CURL_HAS_LTO)
message(STATUS "LTO supported and enabled")
else()
message(FATAL_ERROR "LTO was requested - but compiler doesn't support it\n${CURL_LTO_ERROR}")
endif()
endif()
# Ugly (but functional) way to include "Makefile.inc" by transforming it (= regenerate it).
function(transform_makefile_inc INPUT_FILE OUTPUT_FILE)
file(READ ${INPUT_FILE} MAKEFILE_INC_TEXT)
string(REPLACE "$(top_srcdir)" "\${CURL_SOURCE_DIR}" MAKEFILE_INC_TEXT ${MAKEFILE_INC_TEXT})
string(REPLACE "$(top_builddir)" "\${CURL_BINARY_DIR}" MAKEFILE_INC_TEXT ${MAKEFILE_INC_TEXT})
string(REGEX REPLACE "\\\\\n" "!π!α!" MAKEFILE_INC_TEXT ${MAKEFILE_INC_TEXT})
string(REGEX REPLACE "([a-zA-Z_][a-zA-Z0-9_]*)[\t ]*=[\t ]*([^\n]*)" "SET(\\1 \\2)" MAKEFILE_INC_TEXT ${MAKEFILE_INC_TEXT})
string(REPLACE "!π!α!" "\n" MAKEFILE_INC_TEXT ${MAKEFILE_INC_TEXT})
string(REGEX REPLACE "\\$\\(([a-zA-Z_][a-zA-Z0-9_]*)\\)" "\${\\1}" MAKEFILE_INC_TEXT ${MAKEFILE_INC_TEXT}) # Replace $() with ${}
string(REGEX REPLACE "@([a-zA-Z_][a-zA-Z0-9_]*)@" "\${\\1}" MAKEFILE_INC_TEXT ${MAKEFILE_INC_TEXT}) # Replace @@ with ${}, even if that may not be read by CMake scripts.
file(WRITE ${OUTPUT_FILE} ${MAKEFILE_INC_TEXT})
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${INPUT_FILE}")
endfunction()
include(GNUInstallDirs)
set(CURL_INSTALL_CMAKE_DIR ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME})
set(TARGETS_EXPORT_NAME "${PROJECT_NAME}Targets")
set(generated_dir "${CMAKE_CURRENT_BINARY_DIR}/generated")
set(project_config "${generated_dir}/${PROJECT_NAME}Config.cmake")
set(version_config "${generated_dir}/${PROJECT_NAME}ConfigVersion.cmake")
if(USE_MANUAL)
add_subdirectory(docs)
endif()
add_subdirectory(lib)
if(BUILD_CURL_EXE)
add_subdirectory(src)
endif()
cmake_dependent_option(BUILD_TESTING "Build tests"
ON "PERL_FOUND;NOT CURL_DISABLE_TESTS"
OFF)
if(BUILD_TESTING)
add_subdirectory(tests)
endif()
# Helper to populate a list (_items) with a label when conditions (the remaining
# args) are satisfied
macro(_add_if label)
# needs to be a macro to allow this indirection
if(${ARGN})
set(_items ${_items} "${label}")
endif()
endmacro()
# NTLM support requires crypto function adaptions from various SSL libs
# TODO alternative SSL libs tests for SSP1, GNUTLS, NSS
if(NOT (CURL_DISABLE_CRYPTO_AUTH OR CURL_DISABLE_NTLM) AND
(USE_OPENSSL OR USE_MBEDTLS OR USE_DARWINSSL OR USE_WIN32_CRYPTO))
set(use_curl_ntlm_core ON)
endif()
# Clear list and try to detect available features
set(_items)
_add_if("SSL" SSL_ENABLED)
_add_if("IPv6" ENABLE_IPV6)
_add_if("unixsockets" USE_UNIX_SOCKETS)
_add_if("libz" HAVE_LIBZ)
_add_if("brotli" HAVE_BROTLI)
_add_if("zstd" HAVE_ZSTD)
_add_if("AsynchDNS" USE_ARES OR USE_THREADS_POSIX OR USE_THREADS_WIN32)
_add_if("IDN" HAVE_LIBIDN2 OR USE_WIN32_IDN)
_add_if("Largefile" (SIZEOF_CURL_OFF_T GREATER 4) AND
((SIZEOF_OFF_T GREATER 4) OR USE_WIN32_LARGE_FILES))
# TODO SSP1 (Schannel) check is missing
_add_if("SSPI" USE_WINDOWS_SSPI)
_add_if("GSS-API" HAVE_GSSAPI)
_add_if("alt-svc" NOT CURL_DISABLE_ALTSVC)
_add_if("HSTS" NOT CURL_DISABLE_HSTS)
# TODO SSP1 missing for SPNEGO
_add_if("SPNEGO" NOT CURL_DISABLE_CRYPTO_AUTH AND
(HAVE_GSSAPI OR USE_WINDOWS_SSPI))
_add_if("Kerberos" NOT CURL_DISABLE_CRYPTO_AUTH AND
(HAVE_GSSAPI OR USE_WINDOWS_SSPI))
# NTLM support requires crypto function adaptions from various SSL libs
# TODO alternative SSL libs tests for SSP1, GNUTLS, NSS
_add_if("NTLM" NOT (CURL_DISABLE_CRYPTO_AUTH OR CURL_DISABLE_NTLM) AND
(use_curl_ntlm_core OR USE_WINDOWS_SSPI))
# TODO missing option (autoconf: --enable-ntlm-wb)
_add_if("NTLM_WB" NOT (CURL_DISABLE_CRYPTO_AUTH OR CURL_DISABLE_NTLM) AND
(use_curl_ntlm_core OR USE_WINDOWS_SSPI) AND
NOT CURL_DISABLE_HTTP AND NTLM_WB_ENABLED)
# TODO missing option (--enable-tls-srp), depends on GNUTLS_SRP/OPENSSL_SRP
_add_if("TLS-SRP" USE_TLS_SRP)
# TODO option --with-nghttp2 tests for nghttp2 lib and nghttp2/nghttp2.h header
_add_if("HTTP2" USE_NGHTTP2)
_add_if("HTTP3" USE_NGTCP2 OR USE_QUICHE)
_add_if("MultiSSL" CURL_WITH_MULTI_SSL)
_add_if("HTTPS-proxy" SSL_ENABLED AND (USE_OPENSSL OR USE_GNUTLS OR USE_NSS))
_add_if("unicode" ENABLE_UNICODE)
string(REPLACE ";" " " SUPPORT_FEATURES "${_items}")
message(STATUS "Enabled features: ${SUPPORT_FEATURES}")
# Clear list and try to detect available protocols
set(_items)
_add_if("HTTP" NOT CURL_DISABLE_HTTP)
_add_if("HTTPS" NOT CURL_DISABLE_HTTP AND SSL_ENABLED)
_add_if("FTP" NOT CURL_DISABLE_FTP)
_add_if("FTPS" NOT CURL_DISABLE_FTP AND SSL_ENABLED)
_add_if("FILE" NOT CURL_DISABLE_FILE)
_add_if("TELNET" NOT CURL_DISABLE_TELNET)
_add_if("LDAP" NOT CURL_DISABLE_LDAP)
# CURL_DISABLE_LDAP implies CURL_DISABLE_LDAPS
# TODO check HAVE_LDAP_SSL (in autoconf this is enabled with --enable-ldaps)
_add_if("LDAPS" NOT CURL_DISABLE_LDAPS AND
((USE_OPENLDAP AND SSL_ENABLED) OR
(NOT USE_OPENLDAP AND HAVE_LDAP_SSL)))
_add_if("DICT" NOT CURL_DISABLE_DICT)
_add_if("TFTP" NOT CURL_DISABLE_TFTP)
_add_if("GOPHER" NOT CURL_DISABLE_GOPHER)
_add_if("GOPHERS" NOT CURL_DISABLE_GOPHER AND SSL_ENABLED)
_add_if("POP3" NOT CURL_DISABLE_POP3)
_add_if("POP3S" NOT CURL_DISABLE_POP3 AND SSL_ENABLED)
_add_if("IMAP" NOT CURL_DISABLE_IMAP)
_add_if("IMAPS" NOT CURL_DISABLE_IMAP AND SSL_ENABLED)
_add_if("SMB" NOT CURL_DISABLE_SMB AND
use_curl_ntlm_core AND (SIZEOF_CURL_OFF_T GREATER 4))
_add_if("SMBS" NOT CURL_DISABLE_SMB AND SSL_ENABLED AND
use_curl_ntlm_core AND (SIZEOF_CURL_OFF_T GREATER 4))
_add_if("SMTP" NOT CURL_DISABLE_SMTP)
_add_if("SMTPS" NOT CURL_DISABLE_SMTP AND SSL_ENABLED)
_add_if("SCP" USE_LIBSSH2 OR USE_LIBSSH)
_add_if("SFTP" USE_LIBSSH2 OR USE_LIBSSH)
_add_if("RTSP" NOT CURL_DISABLE_RTSP)
_add_if("RTMP" USE_LIBRTMP)
_add_if("MQTT" NOT CURL_DISABLE_MQTT)
if(_items)
list(SORT _items)
endif()
string(REPLACE ";" " " SUPPORT_PROTOCOLS "${_items}")
message(STATUS "Enabled protocols: ${SUPPORT_PROTOCOLS}")
# Clear list and collect SSL backends
set(_items)
_add_if("Schannel" SSL_ENABLED AND USE_SCHANNEL)
_add_if("OpenSSL" SSL_ENABLED AND USE_OPENSSL)
_add_if("Secure Transport" SSL_ENABLED AND USE_SECTRANSP)
_add_if("mbedTLS" SSL_ENABLED AND USE_MBEDTLS)
_add_if("BearSSL" SSL_ENABLED AND USE_BEARSSL)
_add_if("NSS" SSL_ENABLED AND USE_NSS)
_add_if("wolfSSL" SSL_ENABLED AND USE_WOLFSSL)
if(_items)
list(SORT _items)
endif()
string(REPLACE ";" " " SSL_BACKENDS "${_items}")
message(STATUS "Enabled SSL backends: ${SSL_BACKENDS}")
# curl-config needs the following options to be set.
set(CC "${CMAKE_C_COMPILER}")
# TODO probably put a -D... options here?
set(CONFIGURE_OPTIONS "")
# TODO when to set "-DCURL_STATICLIB" for CPPFLAG_CURL_STATICLIB?
set(CPPFLAG_CURL_STATICLIB "")
set(CURLVERSION "${CURL_VERSION}")
set(exec_prefix "\${prefix}")
set(includedir "\${prefix}/include")
set(LDFLAGS "${CMAKE_SHARED_LINKER_FLAGS}")
set(LIBCURL_LIBS "")
set(libdir "${CMAKE_INSTALL_PREFIX}/lib")
foreach(_lib ${CMAKE_C_IMPLICIT_LINK_LIBRARIES} ${CURL_LIBS})
if(TARGET "${_lib}")
set(_libname "${_lib}")
get_target_property(_imported "${_libname}" IMPORTED)
if(NOT _imported)
# Reading the LOCATION property on non-imported target will error out.
# Assume the user won't need this information in the .pc file.
continue()
endif()
get_target_property(_lib "${_libname}" LOCATION)
if(NOT _lib)
message(WARNING "Bad lib in library list: ${_libname}")
continue()
endif()
endif()
if(_lib MATCHES ".*/.*" OR _lib MATCHES "^-")
set(LIBCURL_LIBS "${LIBCURL_LIBS} ${_lib}")
else()
set(LIBCURL_LIBS "${LIBCURL_LIBS} -l${_lib}")
endif()
endforeach()
if(BUILD_SHARED_LIBS)
set(ENABLE_SHARED "yes")
set(ENABLE_STATIC "no")
set(LIBCURL_NO_SHARED "")
else()
set(ENABLE_SHARED "no")
set(ENABLE_STATIC "yes")
set(LIBCURL_NO_SHARED "${LIBCURL_LIBS}")
endif()
# "a" (Linux) or "lib" (Windows)
string(REPLACE "." "" libext "${CMAKE_STATIC_LIBRARY_SUFFIX}")
set(prefix "${CMAKE_INSTALL_PREFIX}")
# Set this to "yes" to append all libraries on which -lcurl is dependent
set(REQUIRE_LIB_DEPS "no")
# SUPPORT_FEATURES
# SUPPORT_PROTOCOLS
set(VERSIONNUM "${CURL_VERSION_NUM}")
# Finally generate a "curl-config" matching this config
# Use:
# * ENABLE_SHARED
# * ENABLE_STATIC
configure_file("${CURL_SOURCE_DIR}/curl-config.in"
"${CURL_BINARY_DIR}/curl-config" @ONLY)
install(FILES "${CURL_BINARY_DIR}/curl-config"
DESTINATION ${CMAKE_INSTALL_BINDIR}
PERMISSIONS
OWNER_READ OWNER_WRITE OWNER_EXECUTE
GROUP_READ GROUP_EXECUTE
WORLD_READ WORLD_EXECUTE)
# Finally generate a pkg-config file matching this config
configure_file("${CURL_SOURCE_DIR}/libcurl.pc.in"
"${CURL_BINARY_DIR}/libcurl.pc" @ONLY)
install(FILES "${CURL_BINARY_DIR}/libcurl.pc"
DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig)
# install headers
install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/include/curl"
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
FILES_MATCHING PATTERN "*.h")
include(CMakePackageConfigHelpers)
write_basic_package_version_file(
"${version_config}"
VERSION ${CURL_VERSION}
COMPATIBILITY SameMajorVersion
)
# Use:
# * TARGETS_EXPORT_NAME
# * PROJECT_NAME
configure_package_config_file(CMake/curl-config.cmake.in
"${project_config}"
INSTALL_DESTINATION ${CURL_INSTALL_CMAKE_DIR}
)
if(CURL_ENABLE_EXPORT_TARGET)
install(
EXPORT "${TARGETS_EXPORT_NAME}"
NAMESPACE "${PROJECT_NAME}::"
DESTINATION ${CURL_INSTALL_CMAKE_DIR}
)
endif()
install(
FILES ${version_config} ${project_config}
DESTINATION ${CURL_INSTALL_CMAKE_DIR}
)
# Workaround for MSVS10 to avoid the Dialog Hell
# FIXME: This could be removed with future version of CMake.
if(MSVC_VERSION EQUAL 1600)
set(CURL_SLN_FILENAME "${CMAKE_CURRENT_BINARY_DIR}/CURL.sln")
if(EXISTS "${CURL_SLN_FILENAME}")
file(APPEND "${CURL_SLN_FILENAME}" "\n# This should be regenerated!\n")
endif()
endif()
if(NOT TARGET uninstall)
configure_file(
${CMAKE_CURRENT_SOURCE_DIR}/CMake/cmake_uninstall.cmake.in
${CMAKE_CURRENT_BINARY_DIR}/CMake/cmake_uninstall.cmake
IMMEDIATE @ONLY)
add_custom_target(uninstall
COMMAND ${CMAKE_COMMAND} -P
${CMAKE_CURRENT_BINARY_DIR}/CMake/cmake_uninstall.cmake)
endif()
|
0 | repos/gpt4all.zig/src/zig-libcurl | repos/gpt4all.zig/src/zig-libcurl/curl/README.md | 
[](https://bestpractices.coreinfrastructure.org/projects/63)
[](https://scan.coverity.com/projects/curl)
[](https://ci.appveyor.com/project/curlorg/curl)
[](https://dev.azure.com/daniel0244/curl/_build/latest?definitionId=1&branchName=master)
[](https://cirrus-ci.com/github/curl/curl)
[](#backers)
[](#sponsors)
[](https://lgtm.com/projects/g/curl/curl/context:cpp)
[](https://app.codacy.com/app/curl/curl)
[](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:curl)
Curl is a command-line tool for transferring data specified with URL
syntax. Find out how to use curl by reading [the curl.1 man
page](https://curl.se/docs/manpage.html) or [the MANUAL
document](https://curl.se/docs/manual.html). Find out how to install Curl
by reading [the INSTALL document](https://curl.se/docs/install.html).
libcurl is the library curl is using to do its job. It is readily available to
be used by your software. Read [the libcurl.3 man
page](https://curl.se/libcurl/c/libcurl.html) to learn how!
You can find answers to the most frequent questions we get in [the FAQ
document](https://curl.se/docs/faq.html).
Study [the COPYING file](https://curl.se/docs/copyright.html) for
distribution terms.
## Contact
If you have problems, questions, ideas or suggestions, please contact us by
posting to a suitable [mailing list](https://curl.se/mail/).
All contributors to the project are listed in [the THANKS
document](https://curl.se/docs/thanks.html).
## Commercial support
For commercial support, maybe private and dedicated help with your problems or
applications using (lib)curl: https://curl.se/support.html
## Website
Visit the [curl website](https://curl.se/) for the latest news and
downloads.
## Git
To download the very latest source from the Git server do this:
git clone https://github.com/curl/curl.git
(you will get a directory named curl created, filled with the source code)
## Security problems
Report suspected security problems via [our HackerOne
page](https://hackerone.com/curl) and not in public!
## Notice
Curl contains pieces of source code that is Copyright (c) 1998, 1999 Kungliga
Tekniska Högskolan. This notice is included here to comply with the
distribution terms.
## Backers
Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/curl#backer)]
<a href="https://opencollective.com/curl#backers" target="_blank"><img src="https://opencollective.com/curl/backers.svg?width=890"></a>
## Sponsors
Support this project by becoming a sponsor. Your logo will show up here with a
link to your website. [[Become a
sponsor](https://opencollective.com/curl#sponsor)]
<a href="https://opencollective.com/curl/sponsor/0/website" target="_blank"><img src="https://opencollective.com/curl/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/curl/sponsor/1/website" target="_blank"><img src="https://opencollective.com/curl/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/curl/sponsor/2/website" target="_blank"><img src="https://opencollective.com/curl/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/curl/sponsor/3/website" target="_blank"><img src="https://opencollective.com/curl/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/curl/sponsor/4/website" target="_blank"><img src="https://opencollective.com/curl/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/curl/sponsor/5/website" target="_blank"><img src="https://opencollective.com/curl/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/curl/sponsor/6/website" target="_blank"><img src="https://opencollective.com/curl/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/curl/sponsor/7/website" target="_blank"><img src="https://opencollective.com/curl/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/curl/sponsor/8/website" target="_blank"><img src="https://opencollective.com/curl/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/curl/sponsor/9/website" target="_blank"><img src="https://opencollective.com/curl/sponsor/9/avatar.svg"></a>
|
0 | repos/gpt4all.zig/src/zig-libcurl | repos/gpt4all.zig/src/zig-libcurl/curl/.cirrus.yml | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
# Cirrus CI configuration
# https://cirrus-ci.com/github/curl/curl
freebsd_task:
name: FreeBSD
matrix:
- name: FreeBSD 13.0
freebsd_instance:
image_family: freebsd-13-0
- name: FreeBSD 12.2
freebsd_instance:
image_family: freebsd-12-2
env:
CIRRUS_CLONE_DEPTH: 10
CRYPTOGRAPHY_DONT_BUILD_RUST: 1
MAKE_FLAGS: -j 2
pkginstall_script:
- pkg update -f
- pkg install -y autoconf automake libtool pkgconf brotli openldap24-client heimdal libpsl libssh2 openssh-portable libidn2 librtmp libnghttp2 nghttp2 stunnel
- pkg delete -y curl
- easy_install "cryptography<3.2"
- easy_install "pyOpenSSL<20.0"
- easy_install "impacket"
configure_script:
- ./buildconf
# Building with the address sanitizer is causing unexplainable test issues due to timeouts
#- case `uname -r` in
# 12.2*)
# export CC=clang;
# export CFLAGS="-fsanitize=address,undefined,signed-integer-overflow -fno-sanitize-recover=undefined,integer -Wformat -Werror=format-security -Werror=array-bounds -g";
# export CXXFLAGS="-fsanitize=address,undefined -fno-sanitize-recover=undefined,integer -Wformat -Werror=format-security -Werror=array-bounds -g";
# export LDFLAGS="-fsanitize=address,undefined -fno-sanitize-recover=undefined,integer" ;;
# esac
- ./configure --prefix="${HOME}"/install --enable-debug --with-openssl --with-libssh2 --with-brotli --with-gssapi --with-libidn2 --enable-manual --enable-ldap --enable-ldaps --with-librtmp --with-libpsl --with-nghttp2 || { tail -300 config.log; false; }
compile_script:
- make V=1 && cd tests && make V=1
test_script:
# blackhole?
- sysctl net.inet.tcp.blackhole
# make sure we don't run blackhole != 0
- sudo sysctl net.inet.tcp.blackhole=0
# Some tests won't run if run as root so run them as another user.
# Make directories world writable so the test step can write wherever it needs.
- find . -type d -exec chmod 777 {} \;
# The OpenSSH server instance for the testsuite cannot be started on FreeBSD,
# therefore the SFTP and SCP tests are disabled right away from the beginning.
- sudo -u nobody make V=1 TFLAGS="-n !SFTP !SCP" test-ci
install_script:
- make V=1 install
windows_task:
name: Windows
timeout_in: 90m
windows_container:
image: ${container_img}
matrix:
- name: Windows 32-bit shared/release Schannel/SSPI/WinIDN/libssh2
env:
container_img: ghcr.io/mback2k/curl-docker-winbuildenv/msys2-mingw32:ltsc2019
container_cmd: C:\msys64\usr\bin\sh
prepare: pacman -S --needed --noconfirm --noprogressbar libssh2-devel mingw-w64-i686-libssh2
configure: --host=i686-w64-mingw32 --build=i686-w64-mingw32 --prefix=/mingw32 --enable-werror --enable-sspi --with-schannel --with-winidn --with-libssh2
tests: "~571"
- name: Windows 32-bit static/release Schannel/SSPI/WinIDN/libssh2
env:
container_img: ghcr.io/mback2k/curl-docker-winbuildenv/msys2-mingw32:ltsc2019
container_cmd: C:\msys64\usr\bin\sh
prepare: pacman -S --needed --noconfirm --noprogressbar libssh2-devel mingw-w64-i686-libssh2
configure: --host=i686-w64-mingw32 --build=i686-w64-mingw32 --prefix=/mingw32 --enable-werror --enable-sspi --with-schannel --with-winidn --with-libssh2 --disable-shared --enable-static
tests: "~571"
curl_LDFLAGS: -all-static
PKG_CONFIG: pkg-config --static
- name: Windows 64-bit shared/release Schannel/SSPI/WinIDN/libssh2
env:
container_img: ghcr.io/mback2k/curl-docker-winbuildenv/msys2-mingw64:ltsc2019
container_cmd: C:\msys64\usr\bin\sh
prepare: pacman -S --needed --noconfirm --noprogressbar libssh2-devel mingw-w64-x86_64-libssh2
configure: --host=x86_64-w64-mingw32 --build=x86_64-w64-mingw32 --prefix=/mingw64 --enable-werror --enable-sspi --with-schannel --with-winidn --with-libssh2
tests: "~571"
- name: Windows 64-bit static/release Schannel/SSPI/WinIDN/libssh2
env:
container_img: ghcr.io/mback2k/curl-docker-winbuildenv/msys2-mingw64:ltsc2019
container_cmd: C:\msys64\usr\bin\sh
prepare: pacman -S --needed --noconfirm --noprogressbar libssh2-devel mingw-w64-x86_64-libssh2
configure: --host=x86_64-w64-mingw32 --build=x86_64-w64-mingw32 --prefix=/mingw64 --enable-werror --enable-sspi --with-schannel --with-winidn --with-libssh2 --disable-shared --enable-static
tests: "~571"
curl_LDFLAGS: -all-static
PKG_CONFIG: pkg-config --static
env:
CIRRUS_CLONE_DEPTH: 10
MSYS2_PATH_TYPE: inherit
MAKEFLAGS: -j 2
prepare_script: |
%container_cmd% -l -c "cd $(echo '%cd%') && %prepare%"
configure_script: |
%container_cmd% -l -c "cd $(echo '%cd%') && ./buildconf && ./configure %configure%"
compile_script: |
%container_cmd% -l -c "cd $(echo '%cd%') && make V=1 && cd tests && make V=1"
install_script: |
%container_cmd% -l -c "cd $(echo '%cd%') && make V=1 install && PATH=/usr/bin:/bin find . -type f -path '*/.libs/*.exe' -print -execdir mv -t .. {} \;"
test_script: |
%container_cmd% -l -c "cd $(echo '%cd%') && make V=1 TFLAGS='!IDN !SCP ~612 ~1056 %tests%' test-ci"
|
0 | repos/gpt4all.zig/src/zig-libcurl | repos/gpt4all.zig/src/zig-libcurl/curl/appveyor.yml | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
version: 7.50.0.{build}
environment:
matrix:
# generated CMake-based Visual Studio Release builds
- APPVEYOR_BUILD_WORKER_IMAGE: "Visual Studio 2015"
BUILD_SYSTEM: CMake
PRJ_GEN: "Visual Studio 9 2008"
PRJ_CFG: Release
OPENSSL: OFF
SCHANNEL: ON
ENABLE_UNICODE: OFF
HTTP_ONLY: OFF
TESTING: OFF
SHARED: ON
DISABLED_TESTS: ""
COMPILER_PATH: ""
- APPVEYOR_BUILD_WORKER_IMAGE: "Visual Studio 2019"
BUILD_SYSTEM: CMake
PRJ_GEN: "Visual Studio 16 2019"
TARGET: "-A x64"
PRJ_CFG: Release
OPENSSL: ON
SCHANNEL: OFF
ENABLE_UNICODE: OFF
HTTP_ONLY: OFF
TESTING: OFF
SHARED: ON
DISABLED_TESTS: ""
COMPILER_PATH: ""
- APPVEYOR_BUILD_WORKER_IMAGE: "Visual Studio 2019"
BUILD_SYSTEM: CMake
PRJ_GEN: "Visual Studio 16 2019"
TARGET: "-A ARM64"
PRJ_CFG: Release
OPENSSL: OFF
SCHANNEL: ON
ENABLE_UNICODE: OFF
HTTP_ONLY: OFF
TESTING: OFF
SHARED: OFF
DISABLED_TESTS: ""
COMPILER_PATH: ""
# generated CMake-based Visual Studio Debug builds
- APPVEYOR_BUILD_WORKER_IMAGE: "Visual Studio 2015"
BUILD_SYSTEM: CMake
PRJ_GEN: "Visual Studio 10 2010 Win64"
PRJ_CFG: Debug
OPENSSL: OFF
SCHANNEL: OFF
ENABLE_UNICODE: OFF
HTTP_ONLY: OFF
TESTING: ON
SHARED: OFF
DISABLED_TESTS: "!1139 !1501"
COMPILER_PATH: ""
- APPVEYOR_BUILD_WORKER_IMAGE: "Visual Studio 2019"
BUILD_SYSTEM: CMake
PRJ_GEN: "Visual Studio 16 2019"
TARGET: "-A x64"
PRJ_CFG: Debug
OPENSSL: OFF
SCHANNEL: ON
ENABLE_UNICODE: ON
HTTP_ONLY: OFF
TESTING: ON
SHARED: OFF
DISABLED_TESTS: "~571 !1139 !1501 "
COMPILER_PATH: ""
- APPVEYOR_BUILD_WORKER_IMAGE: "Visual Studio 2019"
BUILD_SYSTEM: CMake
PRJ_GEN: "Visual Studio 16 2019"
TARGET: "-A x64"
PRJ_CFG: Debug
OPENSSL: OFF
SCHANNEL: OFF
ENABLE_UNICODE: OFF
HTTP_ONLY: OFF
TESTING: ON
SHARED: OFF
DISABLED_TESTS: "~571 !1139 !1501"
COMPILER_PATH: ""
- APPVEYOR_BUILD_WORKER_IMAGE: "Visual Studio 2019"
BUILD_SYSTEM: CMake
PRJ_GEN: "Visual Studio 16 2019"
TARGET: "-A x64"
PRJ_CFG: Debug
OPENSSL: OFF
SCHANNEL: OFF
ENABLE_UNICODE: OFF
HTTP_ONLY: ON
TESTING: ON
SHARED: OFF
DISABLED_TESTS: "!1139 !1501"
COMPILER_PATH: ""
# generated CMake-based MSYS Makefiles builds (mingw cross-compiling)
- APPVEYOR_BUILD_WORKER_IMAGE: "Visual Studio 2015"
BUILD_SYSTEM: CMake
PRJ_GEN: "MSYS Makefiles"
PRJ_CFG: Debug
OPENSSL: OFF
SCHANNEL: ON
ENABLE_UNICODE: ON
HTTP_ONLY: OFF
TESTING: ON
SHARED: OFF
DISABLED_TESTS: "!1139 !1501"
COMPILER_PATH: "C:\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin"
MSYS2_ARG_CONV_EXCL: "/*"
BUILD_OPT: -k
- APPVEYOR_BUILD_WORKER_IMAGE: "Visual Studio 2017"
BUILD_SYSTEM: CMake
PRJ_GEN: "MSYS Makefiles"
PRJ_CFG: Debug
OPENSSL: OFF
SCHANNEL: ON
ENABLE_UNICODE: ON
HTTP_ONLY: OFF
TESTING: ON
SHARED: OFF
DISABLED_TESTS: "!1139 !1501"
COMPILER_PATH: "C:\\mingw-w64\\x86_64-7.2.0-posix-seh-rt_v5-rev1\\mingw64\\bin"
MSYS2_ARG_CONV_EXCL: "/*"
BUILD_OPT: -k
- APPVEYOR_BUILD_WORKER_IMAGE: "Visual Studio 2015"
BUILD_SYSTEM: CMake
PRJ_GEN: "MSYS Makefiles"
PRJ_CFG: Debug
OPENSSL: OFF
SCHANNEL: ON
ENABLE_UNICODE: OFF
HTTP_ONLY: OFF
TESTING: ON
SHARED: OFF
DISABLED_TESTS: "!1139 !1501"
COMPILER_PATH: "C:\\mingw-w64\\i686-6.3.0-posix-dwarf-rt_v5-rev1\\mingw32\\bin"
MSYS2_ARG_CONV_EXCL: "/*"
BUILD_OPT: -k
- APPVEYOR_BUILD_WORKER_IMAGE: "Visual Studio 2015"
BUILD_SYSTEM: CMake
PRJ_GEN: "MSYS Makefiles"
PRJ_CFG: Debug
OPENSSL: OFF
SCHANNEL: OFF
ENABLE_UNICODE: OFF
HTTP_ONLY: OFF
TESTING: ON
SHARED: OFF
DISABLED_TESTS: "!1139 !1501"
COMPILER_PATH: "C:\\MinGW\\bin"
MSYS2_ARG_CONV_EXCL: "/*"
BUILD_OPT: -k
# winbuild-based builds
- APPVEYOR_BUILD_WORKER_IMAGE: "Visual Studio 2015"
BUILD_SYSTEM: winbuild_vs2015
DEBUG: yes
PATHPART: debug
TESTING: OFF
ENABLE_UNICODE: no
- APPVEYOR_BUILD_WORKER_IMAGE: "Visual Studio 2015"
BUILD_SYSTEM: winbuild_vs2015
DEBUG: no
PATHPART: release
TESTING: OFF
ENABLE_UNICODE: no
- APPVEYOR_BUILD_WORKER_IMAGE: "Visual Studio 2017"
BUILD_SYSTEM: winbuild_vs2017
DEBUG: yes
PATHPART: debug
TESTING: OFF
ENABLE_UNICODE: no
- APPVEYOR_BUILD_WORKER_IMAGE: "Visual Studio 2017"
BUILD_SYSTEM: winbuild_vs2017
DEBUG: no
PATHPART: release
TESTING: OFF
ENABLE_UNICODE: no
- APPVEYOR_BUILD_WORKER_IMAGE: "Visual Studio 2015"
BUILD_SYSTEM: winbuild_vs2015
DEBUG: yes
PATHPART: debug
TESTING: OFF
ENABLE_UNICODE: yes
- APPVEYOR_BUILD_WORKER_IMAGE: "Visual Studio 2015"
BUILD_SYSTEM: winbuild_vs2015
DEBUG: no
PATHPART: release
TESTING: OFF
ENABLE_UNICODE: yes
- APPVEYOR_BUILD_WORKER_IMAGE: "Visual Studio 2017"
BUILD_SYSTEM: winbuild_vs2017
DEBUG: yes
PATHPART: debug
TESTING: OFF
ENABLE_UNICODE: yes
- APPVEYOR_BUILD_WORKER_IMAGE: "Visual Studio 2017"
BUILD_SYSTEM: winbuild_vs2017
DEBUG: no
PATHPART: release
TESTING: OFF
ENABLE_UNICODE: yes
# generated VisualStudioSolution-based builds
- APPVEYOR_BUILD_WORKER_IMAGE: "Visual Studio 2017"
BUILD_SYSTEM: VisualStudioSolution
PRJ_CFG: "DLL Debug - DLL Windows SSPI - DLL WinIDN"
TESTING: OFF
VC_VERSION: VC15
# autotools-based builds (NOT mingw cross-compiling, but msys2 native)
- APPVEYOR_BUILD_WORKER_IMAGE: "Visual Studio 2015"
BUILD_SYSTEM: autotools
TESTING: ON
DISABLED_TESTS: "!19 ~1056 !1233"
CONFIG_ARGS: "--enable-debug --enable-werror --disable-threaded-resolver --disable-proxy --with-schannel"
- APPVEYOR_BUILD_WORKER_IMAGE: "Visual Studio 2019"
BUILD_SYSTEM: autotools
TESTING: ON
DISABLED_TESTS: "!19 !504 !704 !705 ~1056 !1233"
CONFIG_ARGS: "--enable-debug --enable-werror --disable-threaded-resolver --with-schannel"
- APPVEYOR_BUILD_WORKER_IMAGE: "Visual Studio 2019"
BUILD_SYSTEM: autotools
TESTING: ON
DISABLED_TESTS: "!19 !504 !704 !705 ~1056 !1233"
CONFIG_ARGS: "--enable-warnings --enable-werror --with-schannel"
install:
- set "PATH=C:\msys64\usr\bin;%PATH%"
- if not "%COMPILER_PATH%"=="" (
set "PATH=%COMPILER_PATH%;%PATH%" )
build_script:
- if %BUILD_SYSTEM%==CMake (
cmake .
-G"%PRJ_GEN%"
%TARGET%
-DCMAKE_USE_OPENSSL=%OPENSSL%
-DCMAKE_USE_SCHANNEL=%SCHANNEL%
-DHTTP_ONLY=%HTTP_ONLY%
-DBUILD_SHARED_LIBS=%SHARED%
-DBUILD_TESTING=%TESTING%
-DCURL_WERROR=ON
-DENABLE_DEBUG=ON
-DENABLE_UNICODE=%ENABLE_UNICODE%
-DCMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE=""
-DCMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG=""
-DCMAKE_INSTALL_PREFIX="C:/CURL"
-DCMAKE_BUILD_TYPE=%PRJ_CFG% &&
cmake --build . --config %PRJ_CFG% --parallel 2 --clean-first -- %BUILD_OPT%
) else (
if %BUILD_SYSTEM%==VisualStudioSolution (
cd projects &&
.\\generate.bat %VC_VERSION% &&
msbuild.exe /p:Configuration="%PRJ_CFG%" "Windows\\%VC_VERSION%\\curl-all.sln"
) else (
if %BUILD_SYSTEM%==winbuild_vs2015 (
call buildconf.bat &&
cd winbuild &&
call "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.cmd" /x64 &&
call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x86_amd64 &&
nmake /f Makefile.vc mode=dll VC=14 "SSL_PATH=C:\OpenSSL-v111-Win64" WITH_SSL=dll MACHINE=x64 DEBUG=%DEBUG% ENABLE_UNICODE=%ENABLE_UNICODE% &&
..\builds\libcurl-vc14-x64-%PATHPART%-dll-ssl-dll-ipv6-sspi\bin\curl.exe -V
) else (
if %BUILD_SYSTEM%==winbuild_vs2017 (
call buildconf.bat &&
cd winbuild &&
call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars64.bat" &&
nmake /f Makefile.vc mode=dll VC=15 "SSL_PATH=C:\OpenSSL-v111-Win64" WITH_SSL=dll MACHINE=x64 DEBUG=%DEBUG% ENABLE_UNICODE=%ENABLE_UNICODE% &&
..\builds\libcurl-vc15-x64-%PATHPART%-dll-ssl-dll-ipv6-sspi\bin\curl.exe -V
) else (
if %BUILD_SYSTEM%==autotools (
bash.exe -e -l -c "cd /c/projects/curl && ./buildconf && ./configure %CONFIG_ARGS% && make V=1 && make V=1 examples && cd tests && make V=1"
)))))
- if %TESTING%==ON (
if %BUILD_SYSTEM%==CMake (
cmake --build . --config %PRJ_CFG% --parallel 2 --target testdeps
))
test_script:
- if %TESTING%==ON (
if %BUILD_SYSTEM%==CMake (
set TFLAGS=%DISABLED_TESTS% &&
cmake --build . --config %PRJ_CFG% --target test-ci
) else (
if %BUILD_SYSTEM%==autotools (
bash.exe -e -l -c "cd /c/projects/curl && make V=1 TFLAGS='%DISABLED_TESTS%' test-ci"
) else (
bash.exe -e -l -c "cd /c/projects/curl/tests && ./runtests.pl -a -p !flaky -r -rm %DISABLED_TESTS%"
))
)
# select branches to avoid testing feature branches twice (as branch and as pull request)
branches:
only:
- master
- /\/ci$/
artifacts:
- path: '**/curl.exe'
name: curl
- path: '**/*curl*.dll'
name: libcurl
|
0 | repos/gpt4all.zig/src/zig-libcurl | repos/gpt4all.zig/src/zig-libcurl/curl/buildconf.bat | @echo off
rem ***************************************************************************
rem * _ _ ____ _
rem * Project ___| | | | _ \| |
rem * / __| | | | |_) | |
rem * | (__| |_| | _ <| |___
rem * \___|\___/|_| \_\_____|
rem *
rem * Copyright (C) 1998 - 2019, Daniel Stenberg, <[email protected]>, et al.
rem *
rem * This software is licensed as described in the file COPYING, which
rem * you should have received as part of this distribution. The terms
rem * are also available at https://curl.se/docs/copyright.html.
rem *
rem * You may opt to use, copy, modify, merge, publish, distribute and/or sell
rem * copies of the Software, and permit persons to whom the Software is
rem * furnished to do so, under the terms of the COPYING file.
rem *
rem * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
rem * KIND, either express or implied.
rem *
rem ***************************************************************************
rem NOTES
rem
rem This batch file must be used to set up a git tree to build on systems where
rem there is no autotools support (i.e. DOS and Windows).
rem
:begin
rem Set our variables
if "%OS%" == "Windows_NT" setlocal
set MODE=GENERATE
rem Switch to this batch file's directory
cd /d "%~0\.." 1>NUL 2>&1
rem Check we are running from a curl git repository
if not exist GIT-INFO goto norepo
rem Detect programs. HAVE_<PROGNAME>
rem When not found the variable is set undefined. The undefined pattern
rem allows for statements like "if not defined HAVE_PERL (command)"
groff --version <NUL 1>NUL 2>&1
if errorlevel 1 (set HAVE_GROFF=) else (set HAVE_GROFF=Y)
nroff --version <NUL 1>NUL 2>&1
if errorlevel 1 (set HAVE_NROFF=) else (set HAVE_NROFF=Y)
perl --version <NUL 1>NUL 2>&1
if errorlevel 1 (set HAVE_PERL=) else (set HAVE_PERL=Y)
gzip --version <NUL 1>NUL 2>&1
if errorlevel 1 (set HAVE_GZIP=) else (set HAVE_GZIP=Y)
:parseArgs
if "%~1" == "" goto start
if /i "%~1" == "-clean" (
set MODE=CLEAN
) else if /i "%~1" == "-?" (
goto syntax
) else if /i "%~1" == "-h" (
goto syntax
) else if /i "%~1" == "-help" (
goto syntax
) else (
goto unknown
)
shift & goto parseArgs
:start
if "%MODE%" == "GENERATE" (
echo.
echo Generating prerequisite files
call :generate
if errorlevel 3 goto nogenhugehelp
if errorlevel 2 goto nogenmakefile
if errorlevel 1 goto warning
) else (
echo.
echo Removing prerequisite files
call :clean
if errorlevel 2 goto nocleanhugehelp
if errorlevel 1 goto nocleanmakefile
)
goto success
rem Main generate function.
rem
rem Returns:
rem
rem 0 - success
rem 1 - success with simplified tool_hugehelp.c
rem 2 - failed to generate Makefile
rem 3 - failed to generate tool_hugehelp.c
rem
:generate
if "%OS%" == "Windows_NT" setlocal
set BASIC_HUGEHELP=0
rem Create Makefile
echo * %CD%\Makefile
if exist Makefile.dist (
copy /Y Makefile.dist Makefile 1>NUL 2>&1
if errorlevel 1 (
if "%OS%" == "Windows_NT" endlocal
exit /B 2
)
)
rem Create tool_hugehelp.c
echo * %CD%\src\tool_hugehelp.c
call :genHugeHelp
if errorlevel 2 (
if "%OS%" == "Windows_NT" endlocal
exit /B 3
)
if errorlevel 1 (
set BASIC_HUGEHELP=1
)
cmd /c exit 0
rem Setup c-ares git tree
if exist ares\buildconf.bat (
echo.
echo Configuring c-ares build environment
cd ares
call buildconf.bat
cd ..
)
if "%BASIC_HUGEHELP%" == "1" (
if "%OS%" == "Windows_NT" endlocal
exit /B 1
)
if "%OS%" == "Windows_NT" endlocal
exit /B 0
rem Main clean function.
rem
rem Returns:
rem
rem 0 - success
rem 1 - failed to clean Makefile
rem 2 - failed to clean tool_hugehelp.c
rem
:clean
rem Remove Makefile
echo * %CD%\Makefile
if exist Makefile (
del Makefile 2>NUL
if exist Makefile (
exit /B 1
)
)
rem Remove tool_hugehelp.c
echo * %CD%\src\tool_hugehelp.c
if exist src\tool_hugehelp.c (
del src\tool_hugehelp.c 2>NUL
if exist src\tool_hugehelp.c (
exit /B 2
)
)
exit /B
rem Function to generate src\tool_hugehelp.c
rem
rem Returns:
rem
rem 0 - full tool_hugehelp.c generated
rem 1 - simplified tool_hugehelp.c
rem 2 - failure
rem
:genHugeHelp
if "%OS%" == "Windows_NT" setlocal
set LC_ALL=C
set ROFFCMD=
set BASIC=1
if defined HAVE_PERL (
if defined HAVE_GROFF (
set ROFFCMD=groff -mtty-char -Tascii -P-c -man
) else if defined HAVE_NROFF (
set ROFFCMD=nroff -c -Tascii -man
)
)
if defined ROFFCMD (
echo #include "tool_setup.h"> src\tool_hugehelp.c
echo #include "tool_hugehelp.h">> src\tool_hugehelp.c
if defined HAVE_GZIP (
echo #ifndef HAVE_LIBZ>> src\tool_hugehelp.c
)
%ROFFCMD% docs\curl.1 2>NUL | perl src\mkhelp.pl docs\MANUAL >> src\tool_hugehelp.c
if defined HAVE_GZIP (
echo #else>> src\tool_hugehelp.c
%ROFFCMD% docs\curl.1 2>NUL | perl src\mkhelp.pl -c docs\MANUAL >> src\tool_hugehelp.c
echo #endif /^* HAVE_LIBZ ^*/>> src\tool_hugehelp.c
)
set BASIC=0
) else (
if exist src\tool_hugehelp.c.cvs (
copy /Y src\tool_hugehelp.c.cvs src\tool_hugehelp.c 1>NUL 2>&1
) else (
echo #include "tool_setup.h"> src\tool_hugehelp.c
echo #include "tool_hugehelp.h">> src\tool_hugehelp.c
echo.>> src\tool_hugehelp.c
echo void hugehelp(void^)>> src\tool_hugehelp.c
echo {>> src\tool_hugehelp.c
echo #ifdef USE_MANUAL>> src\tool_hugehelp.c
echo fputs("Built-in manual not included\n", stdout^);>> src\tool_hugehelp.c
echo #endif>> src\tool_hugehelp.c
echo }>> src\tool_hugehelp.c
)
)
findstr "/C:void hugehelp(void)" src\tool_hugehelp.c 1>NUL 2>&1
if errorlevel 1 (
if "%OS%" == "Windows_NT" endlocal
exit /B 2
)
if "%BASIC%" == "1" (
if "%OS%" == "Windows_NT" endlocal
exit /B 1
)
if "%OS%" == "Windows_NT" endlocal
exit /B 0
rem Function to clean-up local variables under DOS, Windows 3.x and
rem Windows 9x as setlocal isn't available until Windows NT
rem
:dosCleanup
set MODE=
set HAVE_GROFF=
set HAVE_NROFF=
set HAVE_PERL=
set HAVE_GZIP=
set BASIC_HUGEHELP=
set LC_ALL
set ROFFCMD=
set BASIC=
exit /B
:syntax
rem Display the help
echo.
echo Usage: buildconf [-clean]
echo.
echo -clean - Removes the files
goto error
:unknown
echo.
echo Error: Unknown argument '%1'
goto error
:norepo
echo.
echo Error: This batch file should only be used with a curl git repository
goto error
:nogenmakefile
echo.
echo Error: Unable to generate Makefile
goto error
:nogenhugehelp
echo.
echo Error: Unable to generate src\tool_hugehelp.c
goto error
:nocleanmakefile
echo.
echo Error: Unable to clean Makefile
goto error
:nocleanhugehelp
echo.
echo Error: Unable to clean src\tool_hugehelp.c
goto error
:warning
echo.
echo Warning: The curl manual could not be integrated in the source. This means when
echo you build curl the manual will not be available (curl --man^). Integration of
echo the manual is not required and a summary of the options will still be available
echo (curl --help^). To integrate the manual your PATH is required to have
echo groff/nroff, perl and optionally gzip for compression.
goto success
:error
if "%OS%" == "Windows_NT" (
endlocal
) else (
call :dosCleanup
)
exit /B 1
:success
if "%OS%" == "Windows_NT" (
endlocal
) else (
call :dosCleanup
)
exit /B 0
|
0 | repos/gpt4all.zig/src/zig-libcurl | repos/gpt4all.zig/src/zig-libcurl/curl/.lgtm.yml | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
extraction:
cpp:
prepare:
packages: # to avoid confusion with libopenafs-dev which also provides a des.h
- libssl-dev
after_prepare: # make sure lgtm.com doesn't use CMake (which generates and runs tests)
- rm -f CMakeLists.txt
- ./buildconf
configure: # enable as many optional features as possible
command: ./configure --enable-ares --with-libssh2 --with-gssapi --with-librtmp --with-openssl
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/.circleci/config.yml | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
# Use the latest 2.1 version of CircleCI pipeline process engine. See: https://circleci.com/docs/2.0/configuration-reference
version: 2.1
commands:
configure:
steps:
- run:
command: |
./buildconf
./configure --enable-warnings --enable-werror --with-openssl
build:
steps:
- run: make V=1
test:
steps:
- run: make V=1 test-ci
executors:
ubuntu:
machine:
image: ubuntu-2004:202010-01
jobs:
basic:
executor: ubuntu
steps:
- checkout
- configure
- build
- test
arm:
machine:
image: ubuntu-2004:202101-01
resource_class: arm.medium
steps:
- checkout
- configure
- build
- test
workflows:
x86-openssl:
jobs:
- basic
arm-openssl:
jobs:
- arm
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/CMake/FindZstd.cmake | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
#[=======================================================================[.rst:
FindZstd
----------
Find the zstd library
Result Variables
^^^^^^^^^^^^^^^^
``Zstd_FOUND``
System has zstd
``Zstd_INCLUDE_DIRS``
The zstd include directories.
``Zstd_LIBRARIES``
The libraries needed to use zstd
#]=======================================================================]
if(UNIX)
find_package(PkgConfig QUIET)
pkg_search_module(PC_Zstd libzstd)
endif()
find_path(Zstd_INCLUDE_DIR zstd.h
HINTS
${PC_Zstd_INCLUDEDIR}
${PC_Zstd_INCLUDE_DIRS}
)
find_library(Zstd_LIBRARY NAMES zstd
HINTS
${PC_Zstd_LIBDIR}
${PC_Zstd_LIBRARY_DIRS}
)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(Zstd
REQUIRED_VARS
Zstd_LIBRARY
Zstd_INCLUDE_DIR
)
if(Zstd_FOUND)
set(Zstd_LIBRARIES ${Zstd_LIBRARY})
set(Zstd_INCLUDE_DIRS ${Zstd_INCLUDE_DIR})
endif()
mark_as_advanced(Zstd_INCLUDE_DIRS Zstd_LIBRARIES)
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/CMake/FindMbedTLS.cmake | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
find_path(MBEDTLS_INCLUDE_DIRS mbedtls/ssl.h)
find_library(MBEDTLS_LIBRARY mbedtls)
find_library(MBEDX509_LIBRARY mbedx509)
find_library(MBEDCRYPTO_LIBRARY mbedcrypto)
set(MBEDTLS_LIBRARIES "${MBEDTLS_LIBRARY}" "${MBEDX509_LIBRARY}" "${MBEDCRYPTO_LIBRARY}")
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(MBEDTLS DEFAULT_MSG
MBEDTLS_INCLUDE_DIRS MBEDTLS_LIBRARY MBEDX509_LIBRARY MBEDCRYPTO_LIBRARY)
mark_as_advanced(MBEDTLS_INCLUDE_DIRS MBEDTLS_LIBRARY MBEDX509_LIBRARY MBEDCRYPTO_LIBRARY)
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/CMake/FindNGTCP2.cmake | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
#[=======================================================================[.rst:
FindNGTCP2
----------
Find the ngtcp2 library
This module accepts optional COMPONENTS to control the crypto library (these are
mutually exclusive)::
OpenSSL: Use libngtcp2_crypto_openssl
GnuTLS: Use libngtcp2_crypto_gnutls
Result Variables
^^^^^^^^^^^^^^^^
``NGTCP2_FOUND``
System has ngtcp2
``NGTCP2_INCLUDE_DIRS``
The ngtcp2 include directories.
``NGTCP2_LIBRARIES``
The libraries needed to use ngtcp2
``NGTCP2_VERSION``
version of ngtcp2.
#]=======================================================================]
if(UNIX)
find_package(PkgConfig QUIET)
pkg_search_module(PC_NGTCP2 libngtcp2)
endif()
find_path(NGTCP2_INCLUDE_DIR ngtcp2/ngtcp2.h
HINTS
${PC_NGTCP2_INCLUDEDIR}
${PC_NGTCP2_INCLUDE_DIRS}
)
find_library(NGTCP2_LIBRARY NAMES ngtcp2
HINTS
${PC_NGTCP2_LIBDIR}
${PC_NGTCP2_LIBRARY_DIRS}
)
if(PC_NGTCP2_VERSION)
set(NGTCP2_VERSION ${PC_NGTCP2_VERSION})
endif()
if(NGTCP2_FIND_COMPONENTS)
set(NGTCP2_CRYPTO_BACKEND "")
foreach(component IN LISTS NGTCP2_FIND_COMPONENTS)
if(component MATCHES "^(OpenSSL|GnuTLS)")
if(NGTCP2_CRYPTO_BACKEND)
message(FATAL_ERROR "NGTCP2: Only one crypto library can be selected")
endif()
set(NGTCP2_CRYPTO_BACKEND ${component})
endif()
endforeach()
if(NGTCP2_CRYPTO_BACKEND)
string(TOLOWER "ngtcp2_crypto_${NGTCP2_CRYPTO_BACKEND}" _crypto_library)
if(UNIX)
pkg_search_module(PC_${_crypto_library} lib${_crypto_library})
endif()
find_library(${_crypto_library}_LIBRARY
NAMES
${_crypto_library}
HINTS
${PC_${_crypto_library}_LIBDIR}
${PC_${_crypto_library}_LIBRARY_DIRS}
)
if(${_crypto_library}_LIBRARY)
set(NGTCP2_${NGTCP2_CRYPTO_BACKEND}_FOUND TRUE)
set(NGTCP2_CRYPTO_LIBRARY ${${_crypto_library}_LIBRARY})
endif()
endif()
endif()
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(NGTCP2
REQUIRED_VARS
NGTCP2_LIBRARY
NGTCP2_INCLUDE_DIR
VERSION_VAR NGTCP2_VERSION
HANDLE_COMPONENTS
)
if(NGTCP2_FOUND)
set(NGTCP2_LIBRARIES ${NGTCP2_LIBRARY} ${NGTCP2_CRYPTO_LIBRARY})
set(NGTCP2_INCLUDE_DIRS ${NGTCP2_INCLUDE_DIR})
endif()
mark_as_advanced(NGTCP2_INCLUDE_DIRS NGTCP2_LIBRARIES)
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/CMake/FindWolfSSL.cmake | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
find_path(WolfSSL_INCLUDE_DIR NAMES wolfssl/ssl.h)
find_library(WolfSSL_LIBRARY NAMES wolfssl)
mark_as_advanced(WolfSSL_INCLUDE_DIR WolfSSL_LIBRARY)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(WolfSSL
REQUIRED_VARS WolfSSL_INCLUDE_DIR WolfSSL_LIBRARY
)
if(WolfSSL_FOUND)
set(WolfSSL_INCLUDE_DIRS ${WolfSSL_INCLUDE_DIR})
set(WolfSSL_LIBRARIES ${WolfSSL_LIBRARY})
endif()
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/CMake/FindLibSSH2.cmake | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
# - Try to find the libssh2 library
# Once done this will define
#
# LIBSSH2_FOUND - system has the libssh2 library
# LIBSSH2_INCLUDE_DIR - the libssh2 include directory
# LIBSSH2_LIBRARY - the libssh2 library name
find_path(LIBSSH2_INCLUDE_DIR libssh2.h)
find_library(LIBSSH2_LIBRARY NAMES ssh2 libssh2)
if(LIBSSH2_INCLUDE_DIR)
file(STRINGS "${LIBSSH2_INCLUDE_DIR}/libssh2.h" libssh2_version_str REGEX "^#define[\t ]+LIBSSH2_VERSION[\t ]+\"(.*)\"")
string(REGEX REPLACE "^.*\"([^\"]+)\"" "\\1" LIBSSH2_VERSION "${libssh2_version_str}")
endif()
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(LibSSH2
REQUIRED_VARS LIBSSH2_LIBRARY LIBSSH2_INCLUDE_DIR
VERSION_VAR LIBSSH2_VERSION)
mark_as_advanced(LIBSSH2_INCLUDE_DIR LIBSSH2_LIBRARY)
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/CMake/CMakeConfigurableFile.in | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
@CMAKE_CONFIGURABLE_FILE_CONTENT@
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/CMake/FindGSS.cmake | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
# - Try to find the GSS Kerberos library
# Once done this will define
#
# GSS_ROOT_DIR - Set this variable to the root installation of GSS
#
# Read-Only variables:
# GSS_FOUND - system has the Heimdal library
# GSS_FLAVOUR - "MIT" or "Heimdal" if anything found.
# GSS_INCLUDE_DIR - the Heimdal include directory
# GSS_LIBRARIES - The libraries needed to use GSS
# GSS_LINK_DIRECTORIES - Directories to add to linker search path
# GSS_LINKER_FLAGS - Additional linker flags
# GSS_COMPILER_FLAGS - Additional compiler flags
# GSS_VERSION - This is set to version advertised by pkg-config or read from manifest.
# In case the library is found but no version info available it'll be set to "unknown"
set(_MIT_MODNAME mit-krb5-gssapi)
set(_HEIMDAL_MODNAME heimdal-gssapi)
include(CheckIncludeFile)
include(CheckIncludeFiles)
include(CheckTypeSize)
set(_GSS_ROOT_HINTS
"${GSS_ROOT_DIR}"
"$ENV{GSS_ROOT_DIR}"
)
# try to find library using system pkg-config if user didn't specify root dir
if(NOT GSS_ROOT_DIR AND NOT "$ENV{GSS_ROOT_DIR}")
if(UNIX)
find_package(PkgConfig QUIET)
pkg_search_module(_GSS_PKG ${_MIT_MODNAME} ${_HEIMDAL_MODNAME})
list(APPEND _GSS_ROOT_HINTS "${_GSS_PKG_PREFIX}")
elseif(WIN32)
list(APPEND _GSS_ROOT_HINTS "[HKEY_LOCAL_MACHINE\\SOFTWARE\\MIT\\Kerberos;InstallDir]")
endif()
endif()
if(NOT _GSS_FOUND) #not found by pkg-config. Let's take more traditional approach.
find_file(_GSS_CONFIGURE_SCRIPT
NAMES
"krb5-config"
HINTS
${_GSS_ROOT_HINTS}
PATH_SUFFIXES
bin
NO_CMAKE_PATH
NO_CMAKE_ENVIRONMENT_PATH
)
# if not found in user-supplied directories, maybe system knows better
find_file(_GSS_CONFIGURE_SCRIPT
NAMES
"krb5-config"
PATH_SUFFIXES
bin
)
if(_GSS_CONFIGURE_SCRIPT)
execute_process(
COMMAND ${_GSS_CONFIGURE_SCRIPT} "--cflags" "gssapi"
OUTPUT_VARIABLE _GSS_CFLAGS
RESULT_VARIABLE _GSS_CONFIGURE_FAILED
OUTPUT_STRIP_TRAILING_WHITESPACE
)
message(STATUS "CFLAGS: ${_GSS_CFLAGS}")
if(NOT _GSS_CONFIGURE_FAILED) # 0 means success
# should also work in an odd case when multiple directories are given
string(STRIP "${_GSS_CFLAGS}" _GSS_CFLAGS)
string(REGEX REPLACE " +-I" ";" _GSS_CFLAGS "${_GSS_CFLAGS}")
string(REGEX REPLACE " +-([^I][^ \\t;]*)" ";-\\1" _GSS_CFLAGS "${_GSS_CFLAGS}")
foreach(_flag ${_GSS_CFLAGS})
if(_flag MATCHES "^-I.*")
string(REGEX REPLACE "^-I" "" _val "${_flag}")
list(APPEND _GSS_INCLUDE_DIR "${_val}")
else()
list(APPEND _GSS_COMPILER_FLAGS "${_flag}")
endif()
endforeach()
endif()
execute_process(
COMMAND ${_GSS_CONFIGURE_SCRIPT} "--libs" "gssapi"
OUTPUT_VARIABLE _GSS_LIB_FLAGS
RESULT_VARIABLE _GSS_CONFIGURE_FAILED
OUTPUT_STRIP_TRAILING_WHITESPACE
)
message(STATUS "LDFLAGS: ${_GSS_LIB_FLAGS}")
if(NOT _GSS_CONFIGURE_FAILED) # 0 means success
# this script gives us libraries and link directories. Blah. We have to deal with it.
string(STRIP "${_GSS_LIB_FLAGS}" _GSS_LIB_FLAGS)
string(REGEX REPLACE " +-(L|l)" ";-\\1" _GSS_LIB_FLAGS "${_GSS_LIB_FLAGS}")
string(REGEX REPLACE " +-([^Ll][^ \\t;]*)" ";-\\1" _GSS_LIB_FLAGS "${_GSS_LIB_FLAGS}")
foreach(_flag ${_GSS_LIB_FLAGS})
if(_flag MATCHES "^-l.*")
string(REGEX REPLACE "^-l" "" _val "${_flag}")
list(APPEND _GSS_LIBRARIES "${_val}")
elseif(_flag MATCHES "^-L.*")
string(REGEX REPLACE "^-L" "" _val "${_flag}")
list(APPEND _GSS_LINK_DIRECTORIES "${_val}")
else()
list(APPEND _GSS_LINKER_FLAGS "${_flag}")
endif()
endforeach()
endif()
execute_process(
COMMAND ${_GSS_CONFIGURE_SCRIPT} "--version"
OUTPUT_VARIABLE _GSS_VERSION
RESULT_VARIABLE _GSS_CONFIGURE_FAILED
OUTPUT_STRIP_TRAILING_WHITESPACE
)
# older versions may not have the "--version" parameter. In this case we just don't care.
if(_GSS_CONFIGURE_FAILED)
set(_GSS_VERSION 0)
endif()
execute_process(
COMMAND ${_GSS_CONFIGURE_SCRIPT} "--vendor"
OUTPUT_VARIABLE _GSS_VENDOR
RESULT_VARIABLE _GSS_CONFIGURE_FAILED
OUTPUT_STRIP_TRAILING_WHITESPACE
)
# older versions may not have the "--vendor" parameter. In this case we just don't care.
if(_GSS_CONFIGURE_FAILED)
set(GSS_FLAVOUR "Heimdal") # most probably, shouldn't really matter
else()
if(_GSS_VENDOR MATCHES ".*H|heimdal.*")
set(GSS_FLAVOUR "Heimdal")
else()
set(GSS_FLAVOUR "MIT")
endif()
endif()
else() # either there is no config script or we are on a platform that doesn't provide one (Windows?)
find_path(_GSS_INCLUDE_DIR
NAMES
"gssapi/gssapi.h"
HINTS
${_GSS_ROOT_HINTS}
PATH_SUFFIXES
include
inc
)
if(_GSS_INCLUDE_DIR) #jay, we've found something
set(CMAKE_REQUIRED_INCLUDES "${_GSS_INCLUDE_DIR}")
check_include_files( "gssapi/gssapi_generic.h;gssapi/gssapi_krb5.h" _GSS_HAVE_MIT_HEADERS)
if(_GSS_HAVE_MIT_HEADERS)
set(GSS_FLAVOUR "MIT")
else()
# prevent compiling the header - just check if we can include it
set(CMAKE_REQUIRED_DEFINITIONS "${CMAKE_REQUIRED_DEFINITIONS} -D__ROKEN_H__")
check_include_file( "roken.h" _GSS_HAVE_ROKEN_H)
check_include_file( "heimdal/roken.h" _GSS_HAVE_HEIMDAL_ROKEN_H)
if(_GSS_HAVE_ROKEN_H OR _GSS_HAVE_HEIMDAL_ROKEN_H)
set(GSS_FLAVOUR "Heimdal")
endif()
set(CMAKE_REQUIRED_DEFINITIONS "")
endif()
else()
# I'm not convinced if this is the right way but this is what autotools do at the moment
find_path(_GSS_INCLUDE_DIR
NAMES
"gssapi.h"
HINTS
${_GSS_ROOT_HINTS}
PATH_SUFFIXES
include
inc
)
if(_GSS_INCLUDE_DIR)
set(GSS_FLAVOUR "Heimdal")
endif()
endif()
# if we have headers, check if we can link libraries
if(GSS_FLAVOUR)
set(_GSS_LIBDIR_SUFFIXES "")
set(_GSS_LIBDIR_HINTS ${_GSS_ROOT_HINTS})
get_filename_component(_GSS_CALCULATED_POTENTIAL_ROOT "${_GSS_INCLUDE_DIR}" PATH)
list(APPEND _GSS_LIBDIR_HINTS ${_GSS_CALCULATED_POTENTIAL_ROOT})
if(WIN32)
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
list(APPEND _GSS_LIBDIR_SUFFIXES "lib/AMD64")
if(GSS_FLAVOUR STREQUAL "MIT")
set(_GSS_LIBNAME "gssapi64")
else()
set(_GSS_LIBNAME "libgssapi")
endif()
else()
list(APPEND _GSS_LIBDIR_SUFFIXES "lib/i386")
if(GSS_FLAVOUR STREQUAL "MIT")
set(_GSS_LIBNAME "gssapi32")
else()
set(_GSS_LIBNAME "libgssapi")
endif()
endif()
else()
list(APPEND _GSS_LIBDIR_SUFFIXES "lib;lib64") # those suffixes are not checked for HINTS
if(GSS_FLAVOUR STREQUAL "MIT")
set(_GSS_LIBNAME "gssapi_krb5")
else()
set(_GSS_LIBNAME "gssapi")
endif()
endif()
find_library(_GSS_LIBRARIES
NAMES
${_GSS_LIBNAME}
HINTS
${_GSS_LIBDIR_HINTS}
PATH_SUFFIXES
${_GSS_LIBDIR_SUFFIXES}
)
endif()
endif()
else()
if(_GSS_PKG_${_MIT_MODNAME}_VERSION)
set(GSS_FLAVOUR "MIT")
set(_GSS_VERSION _GSS_PKG_${_MIT_MODNAME}_VERSION)
else()
set(GSS_FLAVOUR "Heimdal")
set(_GSS_VERSION _GSS_PKG_${_MIT_HEIMDAL}_VERSION)
endif()
endif()
set(GSS_INCLUDE_DIR ${_GSS_INCLUDE_DIR})
set(GSS_LIBRARIES ${_GSS_LIBRARIES})
set(GSS_LINK_DIRECTORIES ${_GSS_LINK_DIRECTORIES})
set(GSS_LINKER_FLAGS ${_GSS_LINKER_FLAGS})
set(GSS_COMPILER_FLAGS ${_GSS_COMPILER_FLAGS})
set(GSS_VERSION ${_GSS_VERSION})
if(GSS_FLAVOUR)
if(NOT GSS_VERSION AND GSS_FLAVOUR STREQUAL "Heimdal")
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
set(HEIMDAL_MANIFEST_FILE "Heimdal.Application.amd64.manifest")
else()
set(HEIMDAL_MANIFEST_FILE "Heimdal.Application.x86.manifest")
endif()
if(EXISTS "${GSS_INCLUDE_DIR}/${HEIMDAL_MANIFEST_FILE}")
file(STRINGS "${GSS_INCLUDE_DIR}/${HEIMDAL_MANIFEST_FILE}" heimdal_version_str
REGEX "^.*version=\"[0-9]\\.[^\"]+\".*$")
string(REGEX MATCH "[0-9]\\.[^\"]+"
GSS_VERSION "${heimdal_version_str}")
endif()
if(NOT GSS_VERSION)
set(GSS_VERSION "Heimdal Unknown")
endif()
elseif(NOT GSS_VERSION AND GSS_FLAVOUR STREQUAL "MIT")
get_filename_component(_MIT_VERSION "[HKEY_LOCAL_MACHINE\\SOFTWARE\\MIT\\Kerberos\\SDK\\CurrentVersion;VersionString]" NAME CACHE)
if(WIN32 AND _MIT_VERSION)
set(GSS_VERSION "${_MIT_VERSION}")
else()
set(GSS_VERSION "MIT Unknown")
endif()
endif()
endif()
include(FindPackageHandleStandardArgs)
set(_GSS_REQUIRED_VARS GSS_LIBRARIES GSS_FLAVOUR)
find_package_handle_standard_args(GSS
REQUIRED_VARS
${_GSS_REQUIRED_VARS}
VERSION_VAR
GSS_VERSION
FAIL_MESSAGE
"Could NOT find GSS, try to set the path to GSS root folder in the system variable GSS_ROOT_DIR"
)
mark_as_advanced(GSS_INCLUDE_DIR GSS_LIBRARIES)
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/CMake/FindBearSSL.cmake | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
find_path(BEARSSL_INCLUDE_DIRS bearssl.h)
find_library(BEARSSL_LIBRARY bearssl)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(BEARSSL DEFAULT_MSG
BEARSSL_INCLUDE_DIRS BEARSSL_LIBRARY)
mark_as_advanced(BEARSSL_INCLUDE_DIRS BEARSSL_LIBRARY)
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/CMake/FindNGHTTP3.cmake | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
#[=======================================================================[.rst:
FindNGHTTP3
----------
Find the nghttp3 library
Result Variables
^^^^^^^^^^^^^^^^
``NGHTTP3_FOUND``
System has nghttp3
``NGHTTP3_INCLUDE_DIRS``
The nghttp3 include directories.
``NGHTTP3_LIBRARIES``
The libraries needed to use nghttp3
``NGHTTP3_VERSION``
version of nghttp3.
#]=======================================================================]
if(UNIX)
find_package(PkgConfig QUIET)
pkg_search_module(PC_NGHTTP3 libnghttp3)
endif()
find_path(NGHTTP3_INCLUDE_DIR nghttp3/nghttp3.h
HINTS
${PC_NGHTTP3_INCLUDEDIR}
${PC_NGHTTP3_INCLUDE_DIRS}
)
find_library(NGHTTP3_LIBRARY NAMES nghttp3
HINTS
${PC_NGHTTP3_LIBDIR}
${PC_NGHTTP3_LIBRARY_DIRS}
)
if(PC_NGHTTP3_VERSION)
set(NGHTTP3_VERSION ${PC_NGHTTP3_VERSION})
endif()
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(NGHTTP3
REQUIRED_VARS
NGHTTP3_LIBRARY
NGHTTP3_INCLUDE_DIR
VERSION_VAR NGHTTP3_VERSION
)
if(NGHTTP3_FOUND)
set(NGHTTP3_LIBRARIES ${NGHTTP3_LIBRARY})
set(NGHTTP3_INCLUDE_DIRS ${NGHTTP3_INCLUDE_DIR})
endif()
mark_as_advanced(NGHTTP3_INCLUDE_DIRS NGHTTP3_LIBRARIES)
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/CMake/FindNSS.cmake | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
if(UNIX)
find_package(PkgConfig QUIET)
pkg_search_module(PC_NSS nss)
endif()
if(NOT PC_NSS_FOUND)
return()
endif()
set(NSS_LIBRARIES ${PC_NSS_LINK_LIBRARIES})
set(NSS_INCLUDE_DIRS ${PC_NSS_INCLUDE_DIRS})
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(NSS
REQUIRED_VARS NSS_LIBRARIES NSS_INCLUDE_DIRS
VERSION_VAR PC_NSS_VERSION)
mark_as_advanced(NSS_INCLUDE_DIRS NSS_LIBRARIES)
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/CMake/Macros.cmake | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
#File defines convenience macros for available feature testing
# This macro checks if the symbol exists in the library and if it
# does, it prepends library to the list. It is intended to be called
# multiple times with a sequence of possibly dependent libraries in
# order of least-to-most-dependent. Some libraries depend on others
# to link correctly.
macro(check_library_exists_concat LIBRARY SYMBOL VARIABLE)
check_library_exists("${LIBRARY};${CURL_LIBS}" ${SYMBOL} "${CMAKE_LIBRARY_PATH}"
${VARIABLE})
if(${VARIABLE})
set(CURL_LIBS ${LIBRARY} ${CURL_LIBS})
endif()
endmacro()
# Check if header file exists and add it to the list.
# This macro is intended to be called multiple times with a sequence of
# possibly dependent header files. Some headers depend on others to be
# compiled correctly.
macro(check_include_file_concat FILE VARIABLE)
check_include_files("${CURL_INCLUDES};${FILE}" ${VARIABLE})
if(${VARIABLE})
set(CURL_INCLUDES ${CURL_INCLUDES} ${FILE})
set(CURL_TEST_DEFINES "${CURL_TEST_DEFINES} -D${VARIABLE}")
endif()
endmacro()
# For other curl specific tests, use this macro.
macro(curl_internal_test CURL_TEST)
if(NOT DEFINED "${CURL_TEST}")
set(MACRO_CHECK_FUNCTION_DEFINITIONS
"-D${CURL_TEST} ${CURL_TEST_DEFINES} ${CMAKE_REQUIRED_FLAGS}")
if(CMAKE_REQUIRED_LIBRARIES)
set(CURL_TEST_ADD_LIBRARIES
"-DLINK_LIBRARIES:STRING=${CMAKE_REQUIRED_LIBRARIES}")
endif()
message(STATUS "Performing Curl Test ${CURL_TEST}")
try_compile(${CURL_TEST}
${CMAKE_BINARY_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/CMake/CurlTests.c
CMAKE_FLAGS -DCOMPILE_DEFINITIONS:STRING=${MACRO_CHECK_FUNCTION_DEFINITIONS}
"${CURL_TEST_ADD_LIBRARIES}"
OUTPUT_VARIABLE OUTPUT)
if(${CURL_TEST})
set(${CURL_TEST} 1 CACHE INTERNAL "Curl test ${FUNCTION}")
message(STATUS "Performing Curl Test ${CURL_TEST} - Success")
file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
"Performing Curl Test ${CURL_TEST} passed with the following output:\n"
"${OUTPUT}\n")
else()
message(STATUS "Performing Curl Test ${CURL_TEST} - Failed")
set(${CURL_TEST} "" CACHE INTERNAL "Curl test ${FUNCTION}")
file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
"Performing Curl Test ${CURL_TEST} failed with the following output:\n"
"${OUTPUT}\n")
endif()
endif()
endmacro()
macro(curl_nroff_check)
find_program(NROFF NAMES gnroff nroff)
if(NROFF)
# Need a way to write to stdin, this will do
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/nroff-input.txt" "test")
# Tests for a valid nroff option to generate a manpage
foreach(_MANOPT "-man" "-mandoc")
execute_process(COMMAND "${NROFF}" ${_MANOPT}
OUTPUT_VARIABLE NROFF_MANOPT_OUTPUT
INPUT_FILE "${CMAKE_CURRENT_BINARY_DIR}/nroff-input.txt"
ERROR_QUIET)
# Save the option if it was valid
if(NROFF_MANOPT_OUTPUT)
message("Found *nroff option: -- ${_MANOPT}")
set(NROFF_MANOPT ${_MANOPT})
set(NROFF_USEFUL ON)
break()
endif()
endforeach()
# No need for the temporary file
file(REMOVE "${CMAKE_CURRENT_BINARY_DIR}/nroff-input.txt")
if(NOT NROFF_USEFUL)
message(WARNING "Found no *nroff option to get plaintext from man pages")
endif()
else()
message(WARNING "Found no *nroff program")
endif()
endmacro()
macro(optional_dependency DEPENDENCY)
set(CURL_${DEPENDENCY} AUTO CACHE STRING "Build curl with ${DEPENDENCY} support (AUTO, ON or OFF)")
set_property(CACHE CURL_${DEPENDENCY} PROPERTY STRINGS AUTO ON OFF)
if(CURL_${DEPENDENCY} STREQUAL AUTO)
find_package(${DEPENDENCY})
elseif(CURL_${DEPENDENCY})
find_package(${DEPENDENCY} REQUIRED)
endif()
endmacro()
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/CMake/Utilities.cmake | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
# File containing various utilities
# Returns a list of arguments that evaluate to true
function(count_true output_count_var)
set(lst_len 0)
foreach(option_var IN LISTS ARGN)
if(${option_var})
math(EXPR lst_len "${lst_len} + 1")
endif()
endforeach()
set(${output_count_var} ${lst_len} PARENT_SCOPE)
endfunction()
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/CMake/CurlTests.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#ifdef TIME_WITH_SYS_TIME
/* Time with sys/time test */
#include <sys/types.h>
#include <sys/time.h>
#include <time.h>
int
main ()
{
if ((struct tm *) 0)
return 0;
;
return 0;
}
#endif
#ifdef HAVE_FCNTL_O_NONBLOCK
/* headers for FCNTL_O_NONBLOCK test */
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
/* */
#if defined(sun) || defined(__sun__) || \
defined(__SUNPRO_C) || defined(__SUNPRO_CC)
# if defined(__SVR4) || defined(__srv4__)
# define PLATFORM_SOLARIS
# else
# define PLATFORM_SUNOS4
# endif
#endif
#if (defined(_AIX) || defined(__xlC__)) && !defined(_AIX41)
# define PLATFORM_AIX_V3
#endif
/* */
#if defined(PLATFORM_SUNOS4) || defined(PLATFORM_AIX_V3) || defined(__BEOS__)
#error "O_NONBLOCK does not work on this platform"
#endif
int
main ()
{
/* O_NONBLOCK source test */
int flags = 0;
if(0 != fcntl(0, F_SETFL, flags | O_NONBLOCK))
return 1;
return 0;
}
#endif
/* tests for gethostbyname_r */
#if defined(HAVE_GETHOSTBYNAME_R_3_REENTRANT) || \
defined(HAVE_GETHOSTBYNAME_R_5_REENTRANT) || \
defined(HAVE_GETHOSTBYNAME_R_6_REENTRANT)
# define _REENTRANT
/* no idea whether _REENTRANT is always set, just invent a new flag */
# define TEST_GETHOSTBYFOO_REENTRANT
#endif
#if defined(HAVE_GETHOSTBYNAME_R_3) || \
defined(HAVE_GETHOSTBYNAME_R_5) || \
defined(HAVE_GETHOSTBYNAME_R_6) || \
defined(TEST_GETHOSTBYFOO_REENTRANT)
#include <sys/types.h>
#include <netdb.h>
int main(void)
{
char *address = "example.com";
int length = 0;
int type = 0;
struct hostent h;
int rc = 0;
#if defined(HAVE_GETHOSTBYNAME_R_3) || \
defined(HAVE_GETHOSTBYNAME_R_3_REENTRANT)
struct hostent_data hdata;
#elif defined(HAVE_GETHOSTBYNAME_R_5) || \
defined(HAVE_GETHOSTBYNAME_R_5_REENTRANT) || \
defined(HAVE_GETHOSTBYNAME_R_6) || \
defined(HAVE_GETHOSTBYNAME_R_6_REENTRANT)
char buffer[8192];
int h_errnop;
struct hostent *hp;
#endif
#if defined(HAVE_GETHOSTBYNAME_R_3) || \
defined(HAVE_GETHOSTBYNAME_R_3_REENTRANT)
rc = gethostbyname_r(address, &h, &hdata);
#elif defined(HAVE_GETHOSTBYNAME_R_5) || \
defined(HAVE_GETHOSTBYNAME_R_5_REENTRANT)
rc = gethostbyname_r(address, &h, buffer, 8192, &h_errnop);
(void)hp; /* not used for test */
#elif defined(HAVE_GETHOSTBYNAME_R_6) || \
defined(HAVE_GETHOSTBYNAME_R_6_REENTRANT)
rc = gethostbyname_r(address, &h, buffer, 8192, &hp, &h_errnop);
#endif
(void)length;
(void)type;
(void)rc;
return 0;
}
#endif
#ifdef HAVE_SOCKLEN_T
#ifdef _WIN32
#include <ws2tcpip.h>
#else
#include <sys/types.h>
#include <sys/socket.h>
#endif
int
main ()
{
if ((socklen_t *) 0)
return 0;
if (sizeof (socklen_t))
return 0;
;
return 0;
}
#endif
#ifdef HAVE_IN_ADDR_T
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int
main ()
{
if ((in_addr_t *) 0)
return 0;
if (sizeof (in_addr_t))
return 0;
;
return 0;
}
#endif
#ifdef HAVE_BOOL_T
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_STDBOOL_H
#include <stdbool.h>
#endif
int
main ()
{
if (sizeof (bool *) )
return 0;
;
return 0;
}
#endif
#ifdef STDC_HEADERS
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <float.h>
int main() { return 0; }
#endif
#ifdef HAVE_GETADDRINFO
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
int main(void) {
struct addrinfo hints, *ai;
int error;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
#ifndef getaddrinfo
(void)getaddrinfo;
#endif
error = getaddrinfo("127.0.0.1", "8080", &hints, &ai);
if (error) {
return 1;
}
return 0;
}
#endif
#ifdef HAVE_FILE_OFFSET_BITS
#ifdef _FILE_OFFSET_BITS
#undef _FILE_OFFSET_BITS
#endif
#define _FILE_OFFSET_BITS 64
#include <sys/types.h>
/* Check that off_t can represent 2**63 - 1 correctly.
We can't simply define LARGE_OFF_T to be 9223372036854775807,
since some C++ compilers masquerading as C compilers
incorrectly reject 9223372036854775807. */
#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721
&& LARGE_OFF_T % 2147483647 == 1)
? 1 : -1];
int main () { ; return 0; }
#endif
#ifdef HAVE_IOCTLSOCKET
/* includes start */
#ifdef HAVE_WINDOWS_H
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
# ifdef HAVE_WINSOCK2_H
# include <winsock2.h>
# endif
#endif
int
main ()
{
/* ioctlsocket source code */
int socket;
unsigned long flags = ioctlsocket(socket, FIONBIO, &flags);
;
return 0;
}
#endif
#ifdef HAVE_IOCTLSOCKET_CAMEL
/* includes start */
#ifdef HAVE_WINDOWS_H
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
# ifdef HAVE_WINSOCK2_H
# include <winsock2.h>
# endif
#endif
int
main ()
{
/* IoctlSocket source code */
if(0 != IoctlSocket(0, 0, 0))
return 1;
;
return 0;
}
#endif
#ifdef HAVE_IOCTLSOCKET_CAMEL_FIONBIO
/* includes start */
#ifdef HAVE_WINDOWS_H
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
# ifdef HAVE_WINSOCK2_H
# include <winsock2.h>
# endif
#endif
int
main ()
{
/* IoctlSocket source code */
long flags = 0;
if(0 != IoctlSocket(0, FIONBIO, &flags))
return 1;
;
return 0;
}
#endif
#ifdef HAVE_IOCTLSOCKET_FIONBIO
/* includes start */
#ifdef HAVE_WINDOWS_H
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
# ifdef HAVE_WINSOCK2_H
# include <winsock2.h>
# endif
#endif
int
main ()
{
int flags = 0;
if(0 != ioctlsocket(0, FIONBIO, &flags))
return 1;
;
return 0;
}
#endif
#ifdef HAVE_IOCTL_FIONBIO
/* headers for FIONBIO test */
/* includes start */
#ifdef HAVE_SYS_TYPES_H
# include <sys/types.h>
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
# include <sys/socket.h>
#endif
#ifdef HAVE_SYS_IOCTL_H
# include <sys/ioctl.h>
#endif
#ifdef HAVE_STROPTS_H
# include <stropts.h>
#endif
int
main ()
{
int flags = 0;
if(0 != ioctl(0, FIONBIO, &flags))
return 1;
;
return 0;
}
#endif
#ifdef HAVE_IOCTL_SIOCGIFADDR
/* headers for FIONBIO test */
/* includes start */
#ifdef HAVE_SYS_TYPES_H
# include <sys/types.h>
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
# include <sys/socket.h>
#endif
#ifdef HAVE_SYS_IOCTL_H
# include <sys/ioctl.h>
#endif
#ifdef HAVE_STROPTS_H
# include <stropts.h>
#endif
#include <net/if.h>
int
main ()
{
struct ifreq ifr;
if(0 != ioctl(0, SIOCGIFADDR, &ifr))
return 1;
;
return 0;
}
#endif
#ifdef HAVE_SETSOCKOPT_SO_NONBLOCK
/* includes start */
#ifdef HAVE_WINDOWS_H
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
# ifdef HAVE_WINSOCK2_H
# include <winsock2.h>
# endif
#endif
/* includes start */
#ifdef HAVE_SYS_TYPES_H
# include <sys/types.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
# include <sys/socket.h>
#endif
/* includes end */
int
main ()
{
if(0 != setsockopt(0, SOL_SOCKET, SO_NONBLOCK, 0, 0))
return 1;
;
return 0;
}
#endif
#ifdef HAVE_GLIBC_STRERROR_R
#include <string.h>
#include <errno.h>
void check(char c) {}
int
main () {
char buffer[1024];
/* This will not compile if strerror_r does not return a char* */
check(strerror_r(EACCES, buffer, sizeof(buffer))[0]);
return 0;
}
#endif
#ifdef HAVE_POSIX_STRERROR_R
#include <string.h>
#include <errno.h>
/* float, because a pointer can't be implicitly cast to float */
void check(float f) {}
int
main () {
char buffer[1024];
/* This will not compile if strerror_r does not return an int */
check(strerror_r(EACCES, buffer, sizeof(buffer)));
return 0;
}
#endif
#ifdef HAVE_FSETXATTR_6
#include <sys/xattr.h> /* header from libc, not from libattr */
int
main() {
fsetxattr(0, 0, 0, 0, 0, 0);
return 0;
}
#endif
#ifdef HAVE_FSETXATTR_5
#include <sys/xattr.h> /* header from libc, not from libattr */
int
main() {
fsetxattr(0, 0, 0, 0, 0);
return 0;
}
#endif
#ifdef HAVE_CLOCK_GETTIME_MONOTONIC
#include <time.h>
int
main() {
struct timespec ts = {0, 0};
clock_gettime(CLOCK_MONOTONIC, &ts);
return 0;
}
#endif
#ifdef HAVE_BUILTIN_AVAILABLE
int
main() {
if(__builtin_available(macOS 10.12, *)) {}
return 0;
}
#endif
#ifdef HAVE_VARIADIC_MACROS_C99
#define c99_vmacro3(first, ...) fun3(first, __VA_ARGS__)
#define c99_vmacro2(first, ...) fun2(first, __VA_ARGS__)
int fun3(int arg1, int arg2, int arg3);
int fun2(int arg1, int arg2);
int fun3(int arg1, int arg2, int arg3) {
return arg1 + arg2 + arg3;
}
int fun2(int arg1, int arg2) {
return arg1 + arg2;
}
int
main() {
int res3 = c99_vmacro3(1, 2, 3);
int res2 = c99_vmacro2(1, 2);
(void)res3;
(void)res2;
return 0;
}
#endif
#ifdef HAVE_VARIADIC_MACROS_GCC
#define gcc_vmacro3(first, args...) fun3(first, args)
#define gcc_vmacro2(first, args...) fun2(first, args)
int fun3(int arg1, int arg2, int arg3);
int fun2(int arg1, int arg2);
int fun3(int arg1, int arg2, int arg3) {
return arg1 + arg2 + arg3;
}
int fun2(int arg1, int arg2) {
return arg1 + arg2;
}
int
main() {
int res3 = gcc_vmacro3(1, 2, 3);
int res2 = gcc_vmacro2(1, 2);
(void)res3;
(void)res2;
return 0;
}
#endif
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/CMake/FindNGHTTP2.cmake | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
include(FindPackageHandleStandardArgs)
find_path(NGHTTP2_INCLUDE_DIR "nghttp2/nghttp2.h")
find_library(NGHTTP2_LIBRARY NAMES nghttp2)
find_package_handle_standard_args(NGHTTP2
FOUND_VAR
NGHTTP2_FOUND
REQUIRED_VARS
NGHTTP2_LIBRARY
NGHTTP2_INCLUDE_DIR
)
set(NGHTTP2_INCLUDE_DIRS ${NGHTTP2_INCLUDE_DIR})
set(NGHTTP2_LIBRARIES ${NGHTTP2_LIBRARY})
mark_as_advanced(NGHTTP2_INCLUDE_DIRS NGHTTP2_LIBRARIES)
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/CMake/FindBrotli.cmake | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
include(FindPackageHandleStandardArgs)
find_path(BROTLI_INCLUDE_DIR "brotli/decode.h")
find_library(BROTLICOMMON_LIBRARY NAMES brotlicommon)
find_library(BROTLIDEC_LIBRARY NAMES brotlidec)
find_package_handle_standard_args(BROTLI
FOUND_VAR
BROTLI_FOUND
REQUIRED_VARS
BROTLIDEC_LIBRARY
BROTLICOMMON_LIBRARY
BROTLI_INCLUDE_DIR
FAIL_MESSAGE
"Could NOT find BROTLI"
)
set(BROTLI_INCLUDE_DIRS ${BROTLI_INCLUDE_DIR})
set(BROTLI_LIBRARIES ${BROTLICOMMON_LIBRARY} ${BROTLIDEC_LIBRARY})
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/CMake/FindCARES.cmake | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
# - Find c-ares
# Find the c-ares includes and library
# This module defines
# CARES_INCLUDE_DIR, where to find ares.h, etc.
# CARES_LIBRARIES, the libraries needed to use c-ares.
# CARES_FOUND, If false, do not try to use c-ares.
# also defined, but not for general use are
# CARES_LIBRARY, where to find the c-ares library.
find_path(CARES_INCLUDE_DIR ares.h)
set(CARES_NAMES ${CARES_NAMES} cares)
find_library(CARES_LIBRARY
NAMES ${CARES_NAMES}
)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(CARES
REQUIRED_VARS CARES_LIBRARY CARES_INCLUDE_DIR)
mark_as_advanced(
CARES_LIBRARY
CARES_INCLUDE_DIR
)
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/CMake/curl-config.cmake.in | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
@PACKAGE_INIT@
include(CMakeFindDependencyMacro)
if(@USE_OPENSSL@)
find_dependency(OpenSSL @OPENSSL_VERSION_MAJOR@)
endif()
if(@USE_ZLIB@)
find_dependency(ZLIB @ZLIB_VERSION_MAJOR@)
endif()
include("${CMAKE_CURRENT_LIST_DIR}/@[email protected]")
check_required_components("@PROJECT_NAME@")
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/CMake/CurlSymbolHiding.cmake | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
include(CheckCSourceCompiles)
option(CURL_HIDDEN_SYMBOLS "Set to ON to hide libcurl internal symbols (=hide all symbols that aren't officially external)." ON)
mark_as_advanced(CURL_HIDDEN_SYMBOLS)
if(CURL_HIDDEN_SYMBOLS)
set(SUPPORTS_SYMBOL_HIDING FALSE)
if(CMAKE_C_COMPILER_ID MATCHES "Clang" AND NOT MSVC)
set(SUPPORTS_SYMBOL_HIDING TRUE)
set(_SYMBOL_EXTERN "__attribute__ ((__visibility__ (\"default\")))")
set(_CFLAG_SYMBOLS_HIDE "-fvisibility=hidden")
elseif(CMAKE_COMPILER_IS_GNUCC)
if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 3.4)
# note: this is considered buggy prior to 4.0 but the autotools don't care, so let's ignore that fact
set(SUPPORTS_SYMBOL_HIDING TRUE)
set(_SYMBOL_EXTERN "__attribute__ ((__visibility__ (\"default\")))")
set(_CFLAG_SYMBOLS_HIDE "-fvisibility=hidden")
endif()
elseif(CMAKE_C_COMPILER_ID MATCHES "SunPro" AND NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 8.0)
set(SUPPORTS_SYMBOL_HIDING TRUE)
set(_SYMBOL_EXTERN "__global")
set(_CFLAG_SYMBOLS_HIDE "-xldscope=hidden")
elseif(CMAKE_C_COMPILER_ID MATCHES "Intel" AND NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 9.0)
# note: this should probably just check for version 9.1.045 but I'm not 100% sure
# so let's do it the same way autotools do.
set(SUPPORTS_SYMBOL_HIDING TRUE)
set(_SYMBOL_EXTERN "__attribute__ ((__visibility__ (\"default\")))")
set(_CFLAG_SYMBOLS_HIDE "-fvisibility=hidden")
check_c_source_compiles("#include <stdio.h>
int main (void) { printf(\"icc fvisibility bug test\"); return 0; }" _no_bug)
if(NOT _no_bug)
set(SUPPORTS_SYMBOL_HIDING FALSE)
set(_SYMBOL_EXTERN "")
set(_CFLAG_SYMBOLS_HIDE "")
endif()
elseif(MSVC)
set(SUPPORTS_SYMBOL_HIDING TRUE)
endif()
set(HIDES_CURL_PRIVATE_SYMBOLS ${SUPPORTS_SYMBOL_HIDING})
elseif(MSVC)
if(NOT CMAKE_VERSION VERSION_LESS 3.7)
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS TRUE) #present since 3.4.3 but broken
set(HIDES_CURL_PRIVATE_SYMBOLS FALSE)
else()
message(WARNING "Hiding private symbols regardless CURL_HIDDEN_SYMBOLS being disabled.")
set(HIDES_CURL_PRIVATE_SYMBOLS TRUE)
endif()
else()
set(HIDES_CURL_PRIVATE_SYMBOLS FALSE)
endif()
set(CURL_CFLAG_SYMBOLS_HIDE ${_CFLAG_SYMBOLS_HIDE})
set(CURL_EXTERN_SYMBOL ${_SYMBOL_EXTERN})
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/CMake/FindQUICHE.cmake | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
#[=======================================================================[.rst:
FindQUICHE
----------
Find the quiche library
Result Variables
^^^^^^^^^^^^^^^^
``QUICHE_FOUND``
System has quiche
``QUICHE_INCLUDE_DIRS``
The quiche include directories.
``QUICHE_LIBRARIES``
The libraries needed to use quiche
#]=======================================================================]
if(UNIX)
find_package(PkgConfig QUIET)
pkg_search_module(PC_QUICHE quiche)
endif()
find_path(QUICHE_INCLUDE_DIR quiche.h
HINTS
${PC_QUICHE_INCLUDEDIR}
${PC_QUICHE_INCLUDE_DIRS}
)
find_library(QUICHE_LIBRARY NAMES quiche
HINTS
${PC_QUICHE_LIBDIR}
${PC_QUICHE_LIBRARY_DIRS}
)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(QUICHE
REQUIRED_VARS
QUICHE_LIBRARY
QUICHE_INCLUDE_DIR
)
if(QUICHE_FOUND)
set(QUICHE_LIBRARIES ${QUICHE_LIBRARY})
set(QUICHE_INCLUDE_DIRS ${QUICHE_INCLUDE_DIR})
endif()
mark_as_advanced(QUICHE_INCLUDE_DIRS QUICHE_LIBRARIES)
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/CMake/OtherTests.cmake | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
include(CheckCSourceCompiles)
# The begin of the sources (macros and includes)
set(_source_epilogue "#undef inline")
macro(add_header_include check header)
if(${check})
set(_source_epilogue "${_source_epilogue}\n#include <${header}>")
endif()
endmacro()
set(signature_call_conv)
if(HAVE_WINDOWS_H)
add_header_include(HAVE_WINSOCK2_H "winsock2.h")
add_header_include(HAVE_WINDOWS_H "windows.h")
set(_source_epilogue
"${_source_epilogue}\n#ifndef WIN32_LEAN_AND_MEAN\n#define WIN32_LEAN_AND_MEAN\n#endif")
set(signature_call_conv "PASCAL")
if(HAVE_LIBWS2_32)
set(CMAKE_REQUIRED_LIBRARIES ws2_32)
endif()
else()
add_header_include(HAVE_SYS_TYPES_H "sys/types.h")
add_header_include(HAVE_SYS_SOCKET_H "sys/socket.h")
endif()
set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)
function(curl_cv_func_recv_run_test recv_retv recv_arg1 recv_arg2 recv_arg3 recv_arg4)
unset(curl_cv_func_recv_test CACHE)
check_c_source_compiles("
${_source_epilogue}
#ifdef WINSOCK_API_LINKAGE
WINSOCK_API_LINKAGE
#endif
extern ${recv_retv} ${signature_call_conv}
recv(${recv_arg1}, ${recv_arg2}, ${recv_arg3}, ${recv_arg4});
int main(void) {
${recv_arg1} s=0;
${recv_arg2} buf=0;
${recv_arg3} len=0;
${recv_arg4} flags=0;
${recv_retv} res = recv(s, buf, len, flags);
(void) res;
return 0;
}"
curl_cv_func_recv_test)
message(STATUS
"Tested: ${recv_retv} recv(${recv_arg1}, ${recv_arg2}, ${recv_arg3}, ${recv_arg4})")
if(curl_cv_func_recv_test)
set(curl_cv_func_recv_args
"${recv_arg1},${recv_arg2},${recv_arg3},${recv_arg4},${recv_retv}" PARENT_SCOPE)
set(RECV_TYPE_ARG1 "${recv_arg1}" PARENT_SCOPE)
set(RECV_TYPE_ARG2 "${recv_arg2}" PARENT_SCOPE)
set(RECV_TYPE_ARG3 "${recv_arg3}" PARENT_SCOPE)
set(RECV_TYPE_ARG4 "${recv_arg4}" PARENT_SCOPE)
set(RECV_TYPE_RETV "${recv_retv}" PARENT_SCOPE)
set(HAVE_RECV 1 PARENT_SCOPE)
set(curl_cv_func_recv_done 1 PARENT_SCOPE)
endif()
endfunction()
check_c_source_compiles("${_source_epilogue}
int main(void) {
recv(0, 0, 0, 0);
return 0;
}" curl_cv_recv)
if(curl_cv_recv)
if(NOT DEFINED curl_cv_func_recv_args OR curl_cv_func_recv_args STREQUAL "unknown")
if(APPLE)
curl_cv_func_recv_run_test("ssize_t" "int" "void *" "size_t" "int")
endif()
foreach(recv_retv "int" "ssize_t" )
foreach(recv_arg1 "SOCKET" "int" )
foreach(recv_arg2 "char *" "void *" )
foreach(recv_arg3 "int" "size_t" "socklen_t" "unsigned int")
foreach(recv_arg4 "int" "unsigned int")
if(NOT curl_cv_func_recv_done)
curl_cv_func_recv_run_test(${recv_retv} ${recv_arg1} ${recv_arg2} ${recv_arg3} ${recv_arg4})
endif()
endforeach()
endforeach()
endforeach()
endforeach()
endforeach()
else()
string(REGEX REPLACE "^([^,]*),[^,]*,[^,]*,[^,]*,[^,]*$" "\\1" RECV_TYPE_ARG1 "${curl_cv_func_recv_args}")
string(REGEX REPLACE "^[^,]*,([^,]*),[^,]*,[^,]*,[^,]*$" "\\1" RECV_TYPE_ARG2 "${curl_cv_func_recv_args}")
string(REGEX REPLACE "^[^,]*,[^,]*,([^,]*),[^,]*,[^,]*$" "\\1" RECV_TYPE_ARG3 "${curl_cv_func_recv_args}")
string(REGEX REPLACE "^[^,]*,[^,]*,[^,]*,([^,]*),[^,]*$" "\\1" RECV_TYPE_ARG4 "${curl_cv_func_recv_args}")
string(REGEX REPLACE "^[^,]*,[^,]*,[^,]*,[^,]*,([^,]*)$" "\\1" RECV_TYPE_RETV "${curl_cv_func_recv_args}")
endif()
if(curl_cv_func_recv_args STREQUAL "unknown")
message(FATAL_ERROR "Cannot find proper types to use for recv args")
endif()
else()
message(FATAL_ERROR "Unable to link function recv")
endif()
set(curl_cv_func_recv_args "${curl_cv_func_recv_args}" CACHE INTERNAL "Arguments for recv")
set(HAVE_RECV 1)
function(curl_cv_func_send_run_test send_retv send_arg1 send_arg2 send_arg3 send_arg4)
unset(curl_cv_func_send_test CACHE)
check_c_source_compiles("
${_source_epilogue}
#ifdef WINSOCK_API_LINKAGE
WINSOCK_API_LINKAGE
#endif
extern ${send_retv} ${signature_call_conv}
send(${send_arg1}, ${send_arg2}, ${send_arg3}, ${send_arg4});
int main(void) {
${send_arg1} s=0;
${send_arg2} buf=0;
${send_arg3} len=0;
${send_arg4} flags=0;
${send_retv} res = send(s, buf, len, flags);
(void) res;
return 0;
}"
curl_cv_func_send_test)
message(STATUS
"Tested: ${send_retv} send(${send_arg1}, ${send_arg2}, ${send_arg3}, ${send_arg4})")
if(curl_cv_func_send_test)
string(REGEX REPLACE "(const) .*" "\\1" send_qual_arg2 "${send_arg2}")
string(REGEX REPLACE "const (.*)" "\\1" send_arg2 "${send_arg2}")
set(curl_cv_func_send_args
"${send_arg1},${send_arg2},${send_arg3},${send_arg4},${send_retv},${send_qual_arg2}" PARENT_SCOPE)
set(SEND_TYPE_ARG1 "${send_arg1}" PARENT_SCOPE)
set(SEND_TYPE_ARG2 "${send_arg2}" PARENT_SCOPE)
set(SEND_TYPE_ARG3 "${send_arg3}" PARENT_SCOPE)
set(SEND_TYPE_ARG4 "${send_arg4}" PARENT_SCOPE)
set(SEND_TYPE_RETV "${send_retv}" PARENT_SCOPE)
set(HAVE_SEND 1 PARENT_SCOPE)
set(curl_cv_func_send_done 1 PARENT_SCOPE)
endif()
endfunction()
check_c_source_compiles("${_source_epilogue}
int main(void) {
send(0, 0, 0, 0);
return 0;
}" curl_cv_send)
if(curl_cv_send)
if(NOT DEFINED curl_cv_func_send_args OR "${curl_cv_func_send_args}" STREQUAL "unknown")
if(APPLE)
curl_cv_func_send_run_test("ssize_t" "int" "const void *" "size_t" "int")
endif()
foreach(send_retv "int" "ssize_t" )
foreach(send_arg1 "SOCKET" "int" "ssize_t" )
foreach(send_arg2 "const char *" "const void *" "void *" "char *")
foreach(send_arg3 "int" "size_t" "socklen_t" "unsigned int")
foreach(send_arg4 "int" "unsigned int")
if(NOT curl_cv_func_send_done)
curl_cv_func_send_run_test("${send_retv}" "${send_arg1}" "${send_arg2}" "${send_arg3}" "${send_arg4}")
endif()
endforeach()
endforeach()
endforeach()
endforeach()
endforeach()
else()
string(REGEX REPLACE "^([^,]*),[^,]*,[^,]*,[^,]*,[^,]*,[^,]*$" "\\1" SEND_TYPE_ARG1 "${curl_cv_func_send_args}")
string(REGEX REPLACE "^[^,]*,([^,]*),[^,]*,[^,]*,[^,]*,[^,]*$" "\\1" SEND_TYPE_ARG2 "${curl_cv_func_send_args}")
string(REGEX REPLACE "^[^,]*,[^,]*,([^,]*),[^,]*,[^,]*,[^,]*$" "\\1" SEND_TYPE_ARG3 "${curl_cv_func_send_args}")
string(REGEX REPLACE "^[^,]*,[^,]*,[^,]*,([^,]*),[^,]*,[^,]*$" "\\1" SEND_TYPE_ARG4 "${curl_cv_func_send_args}")
string(REGEX REPLACE "^[^,]*,[^,]*,[^,]*,[^,]*,([^,]*),[^,]*$" "\\1" SEND_TYPE_RETV "${curl_cv_func_send_args}")
string(REGEX REPLACE "^[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,([^,]*)$" "\\1" SEND_QUAL_ARG2 "${curl_cv_func_send_args}")
endif()
if("${curl_cv_func_send_args}" STREQUAL "unknown")
message(FATAL_ERROR "Cannot find proper types to use for send args")
endif()
set(SEND_QUAL_ARG2 "const")
else()
message(FATAL_ERROR "Unable to link function send")
endif()
set(curl_cv_func_send_args "${curl_cv_func_send_args}" CACHE INTERNAL "Arguments for send")
set(HAVE_SEND 1)
check_c_source_compiles("${_source_epilogue}
int main(void) {
int flag = MSG_NOSIGNAL;
(void)flag;
return 0;
}" HAVE_MSG_NOSIGNAL)
if(NOT HAVE_WINDOWS_H)
add_header_include(HAVE_SYS_TIME_H "sys/time.h")
add_header_include(TIME_WITH_SYS_TIME "time.h")
add_header_include(HAVE_TIME_H "time.h")
endif()
check_c_source_compiles("${_source_epilogue}
int main(void) {
struct timeval ts;
ts.tv_sec = 0;
ts.tv_usec = 0;
(void)ts;
return 0;
}" HAVE_STRUCT_TIMEVAL)
if(HAVE_WINDOWS_H)
set(CMAKE_EXTRA_INCLUDE_FILES winsock2.h)
else()
set(CMAKE_EXTRA_INCLUDE_FILES)
if(HAVE_SYS_SOCKET_H)
set(CMAKE_EXTRA_INCLUDE_FILES sys/socket.h)
endif()
endif()
check_type_size("struct sockaddr_storage" SIZEOF_STRUCT_SOCKADDR_STORAGE)
if(HAVE_SIZEOF_STRUCT_SOCKADDR_STORAGE)
set(HAVE_STRUCT_SOCKADDR_STORAGE 1)
endif()
unset(CMAKE_TRY_COMPILE_TARGET_TYPE)
if(NOT DEFINED CMAKE_TOOLCHAIN_FILE)
if(NOT ${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
# only try this on non-macOS
# if not cross-compilation...
include(CheckCSourceRuns)
set(CMAKE_REQUIRED_FLAGS "")
if(HAVE_SYS_POLL_H)
set(CMAKE_REQUIRED_FLAGS "-DHAVE_SYS_POLL_H")
elseif(HAVE_POLL_H)
set(CMAKE_REQUIRED_FLAGS "-DHAVE_POLL_H")
endif()
check_c_source_runs("
#include <stdlib.h>
#include <sys/time.h>
#ifdef HAVE_SYS_POLL_H
# include <sys/poll.h>
#elif HAVE_POLL_H
# include <poll.h>
#endif
int main(void)
{
if(0 != poll(0, 0, 10)) {
return 1; /* fail */
}
else {
/* detect the 10.12 poll() breakage */
struct timeval before, after;
int rc;
size_t us;
gettimeofday(&before, NULL);
rc = poll(NULL, 0, 500);
gettimeofday(&after, NULL);
us = (after.tv_sec - before.tv_sec) * 1000000 +
(after.tv_usec - before.tv_usec);
if(us < 400000) {
return 1;
}
}
return 0;
}" HAVE_POLL_FINE)
endif()
endif()
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/CMake/cmake_uninstall.cmake.in | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
if(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt")
message(FATAL_ERROR "Cannot find install manifest: @CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt")
endif()
if(NOT DEFINED CMAKE_INSTALL_PREFIX)
set(CMAKE_INSTALL_PREFIX "@CMAKE_INSTALL_PREFIX@")
endif()
message(${CMAKE_INSTALL_PREFIX})
file(READ "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt" files)
string(REGEX REPLACE "\n" ";" files "${files}")
foreach(file ${files})
message(STATUS "Uninstalling $ENV{DESTDIR}${file}")
if(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}")
exec_program(
"@CMAKE_COMMAND@" ARGS "-E remove \"$ENV{DESTDIR}${file}\""
OUTPUT_VARIABLE rm_out
RETURN_VALUE rm_retval
)
if(NOT "${rm_retval}" STREQUAL 0)
message(FATAL_ERROR "Problem when removing $ENV{DESTDIR}${file}")
endif()
else()
message(STATUS "File $ENV{DESTDIR}${file} does not exist.")
endif()
endforeach()
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/CMake | repos/gpt4all.zig/src/zig-libcurl/curl/CMake/Platforms/WindowsCache.cmake | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
if(NOT UNIX)
if(WIN32)
set(HAVE_LIBDL 0)
set(HAVE_LIBUCB 0)
set(HAVE_LIBSOCKET 0)
set(NOT_NEED_LIBNSL 0)
set(HAVE_LIBNSL 0)
set(HAVE_GETHOSTNAME 1)
set(HAVE_LIBZ 0)
set(HAVE_DLOPEN 0)
set(HAVE_ALLOCA_H 0)
set(HAVE_ARPA_INET_H 0)
set(HAVE_DLFCN_H 0)
set(HAVE_FCNTL_H 1)
set(HAVE_INTTYPES_H 0)
set(HAVE_IO_H 1)
set(HAVE_MALLOC_H 1)
set(HAVE_MEMORY_H 1)
set(HAVE_NETDB_H 0)
set(HAVE_NETINET_IF_ETHER_H 0)
set(HAVE_NETINET_IN_H 0)
set(HAVE_NET_IF_H 0)
set(HAVE_PROCESS_H 1)
set(HAVE_PWD_H 0)
set(HAVE_SETJMP_H 1)
set(HAVE_SIGNAL_H 1)
set(HAVE_SOCKIO_H 0)
set(HAVE_STDINT_H 0)
set(HAVE_STDLIB_H 1)
set(HAVE_STRINGS_H 0)
set(HAVE_STRING_H 1)
set(HAVE_SYS_PARAM_H 0)
set(HAVE_SYS_POLL_H 0)
set(HAVE_SYS_SELECT_H 0)
set(HAVE_SYS_SOCKET_H 0)
set(HAVE_SYS_SOCKIO_H 0)
set(HAVE_SYS_STAT_H 1)
set(HAVE_SYS_TIME_H 0)
set(HAVE_SYS_TYPES_H 1)
set(HAVE_SYS_UTIME_H 1)
set(HAVE_TERMIOS_H 0)
set(HAVE_TERMIO_H 0)
set(HAVE_TIME_H 1)
set(HAVE_UNISTD_H 0)
set(HAVE_UTIME_H 0)
set(HAVE_X509_H 0)
set(HAVE_ZLIB_H 0)
set(HAVE_SIZEOF_LONG_DOUBLE 1)
set(SIZEOF_LONG_DOUBLE 8)
set(HAVE_SOCKET 1)
set(HAVE_POLL 0)
set(HAVE_SELECT 1)
set(HAVE_STRDUP 1)
set(HAVE_STRSTR 1)
set(HAVE_STRTOK_R 0)
set(HAVE_STRFTIME 1)
set(HAVE_UNAME 0)
set(HAVE_STRCASECMP 0)
set(HAVE_STRICMP 1)
set(HAVE_STRCMPI 1)
set(HAVE_GETTIMEOFDAY 0)
set(HAVE_INET_ADDR 1)
set(HAVE_CLOSESOCKET 1)
set(HAVE_SETVBUF 0)
set(HAVE_SIGSETJMP 0)
set(HAVE_GETPASS_R 0)
set(HAVE_STRLCAT 0)
set(HAVE_GETPWUID 0)
set(HAVE_GETEUID 0)
set(HAVE_UTIME 1)
set(HAVE_RAND_EGD 0)
set(HAVE_RAND_SCREEN 0)
set(HAVE_RAND_STATUS 0)
set(HAVE_GMTIME_R 0)
set(HAVE_LOCALTIME_R 0)
set(HAVE_GETHOSTBYNAME_R 0)
set(HAVE_SIGNAL_FUNC 1)
set(HAVE_SIGNAL_MACRO 0)
set(HAVE_GETHOSTBYNAME_R_3 0)
set(HAVE_GETHOSTBYNAME_R_3_REENTRANT 0)
set(HAVE_GETHOSTBYNAME_R_5 0)
set(HAVE_GETHOSTBYNAME_R_5_REENTRANT 0)
set(HAVE_GETHOSTBYNAME_R_6 0)
set(HAVE_GETHOSTBYNAME_R_6_REENTRANT 0)
set(TIME_WITH_SYS_TIME 0)
set(HAVE_O_NONBLOCK 0)
set(HAVE_IN_ADDR_T 0)
if(ENABLE_IPV6)
set(HAVE_GETADDRINFO 1)
else()
set(HAVE_GETADDRINFO 0)
endif()
set(STDC_HEADERS 1)
set(HAVE_SIGACTION 0)
set(HAVE_MACRO_SIGSETJMP 0)
else()
message("This file should be included on Windows platform only")
endif()
endif()
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/memanalyze.pl | #!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
#
# Example input:
#
# MEM mprintf.c:1094 malloc(32) = e5718
# MEM mprintf.c:1103 realloc(e5718, 64) = e6118
# MEM sendf.c:232 free(f6520)
my $mallocs=0;
my $callocs=0;
my $reallocs=0;
my $strdups=0;
my $wcsdups=0;
my $showlimit;
my $sends=0;
my $recvs=0;
my $sockets=0;
while(1) {
if($ARGV[0] eq "-v") {
$verbose=1;
shift @ARGV;
}
elsif($ARGV[0] eq "-t") {
$trace=1;
shift @ARGV;
}
elsif($ARGV[0] eq "-l") {
# only show what alloc that caused a memlimit failure
$showlimit=1;
shift @ARGV;
}
else {
last;
}
}
my $maxmem;
sub newtotal {
my ($newtot)=@_;
# count a max here
if($newtot > $maxmem) {
$maxmem= $newtot;
}
}
my $file = $ARGV[0];
if(! -f $file) {
print "Usage: memanalyze.pl [options] <dump file>\n",
"Options:\n",
" -l memlimit failure displayed\n",
" -v Verbose\n",
" -t Trace\n";
exit;
}
open(FILE, "<$file");
if($showlimit) {
while(<FILE>) {
if(/^LIMIT.*memlimit$/) {
print $_;
last;
}
}
close(FILE);
exit;
}
my $lnum=0;
while(<FILE>) {
chomp $_;
$line = $_;
$lnum++;
if($line =~ /^LIMIT ([^ ]*):(\d*) (.*)/) {
# new memory limit test prefix
my $i = $3;
my ($source, $linenum) = ($1, $2);
if($trace && ($i =~ /([^ ]*) reached memlimit/)) {
print "LIMIT: $1 returned error at $source:$linenum\n";
}
}
elsif($line =~ /^MEM ([^ ]*):(\d*) (.*)/) {
# generic match for the filename+linenumber
$source = $1;
$linenum = $2;
$function = $3;
if($function =~ /free\((\(nil\)|0x([0-9a-f]*))/) {
$addr = $2;
if($1 eq "(nil)") {
; # do nothing when free(NULL)
}
elsif(!exists $sizeataddr{$addr}) {
print "FREE ERROR: No memory allocated: $line\n";
}
elsif(-1 == $sizeataddr{$addr}) {
print "FREE ERROR: Memory freed twice: $line\n";
print "FREE ERROR: Previously freed at: ".$getmem{$addr}."\n";
}
else {
$totalmem -= $sizeataddr{$addr};
if($trace) {
print "FREE: malloc at ".$getmem{$addr}." is freed again at $source:$linenum\n";
printf("FREE: %d bytes freed, left allocated: $totalmem bytes\n", $sizeataddr{$addr});
}
newtotal($totalmem);
$frees++;
$sizeataddr{$addr}=-1; # set -1 to mark as freed
$getmem{$addr}="$source:$linenum";
}
}
elsif($function =~ /malloc\((\d*)\) = 0x([0-9a-f]*)/) {
$size = $1;
$addr = $2;
if($sizeataddr{$addr}>0) {
# this means weeeeeirdo
print "Mixed debug compile ($source:$linenum at line $lnum), rebuild curl now\n";
print "We think $sizeataddr{$addr} bytes are already allocated at that memory address: $addr!\n";
}
$sizeataddr{$addr}=$size;
$totalmem += $size;
if($trace) {
print "MALLOC: malloc($size) at $source:$linenum",
" makes totally $totalmem bytes\n";
}
newtotal($totalmem);
$mallocs++;
$getmem{$addr}="$source:$linenum";
}
elsif($function =~ /calloc\((\d*),(\d*)\) = 0x([0-9a-f]*)/) {
$size = $1*$2;
$addr = $3;
$arg1 = $1;
$arg2 = $2;
if($sizeataddr{$addr}>0) {
# this means weeeeeirdo
print "Mixed debug compile, rebuild curl now\n";
}
$sizeataddr{$addr}=$size;
$totalmem += $size;
if($trace) {
print "CALLOC: calloc($arg1,$arg2) at $source:$linenum",
" makes totally $totalmem bytes\n";
}
newtotal($totalmem);
$callocs++;
$getmem{$addr}="$source:$linenum";
}
elsif($function =~ /realloc\((\(nil\)|0x([0-9a-f]*)), (\d*)\) = 0x([0-9a-f]*)/) {
my ($oldaddr, $newsize, $newaddr) = ($2, $3, $4);
$totalmem -= $sizeataddr{$oldaddr};
if($trace) {
printf("REALLOC: %d less bytes and ", $sizeataddr{$oldaddr});
}
$sizeataddr{$oldaddr}=0;
$totalmem += $newsize;
$sizeataddr{$newaddr}=$newsize;
if($trace) {
printf("%d more bytes ($source:$linenum)\n", $newsize);
}
newtotal($totalmem);
$reallocs++;
$getmem{$oldaddr}="";
$getmem{$newaddr}="$source:$linenum";
}
elsif($function =~ /strdup\(0x([0-9a-f]*)\) \((\d*)\) = 0x([0-9a-f]*)/) {
# strdup(a5b50) (8) = df7c0
$dup = $1;
$size = $2;
$addr = $3;
$getmem{$addr}="$source:$linenum";
$sizeataddr{$addr}=$size;
$totalmem += $size;
if($trace) {
printf("STRDUP: $size bytes at %s, makes totally: %d bytes\n",
$getmem{$addr}, $totalmem);
}
newtotal($totalmem);
$strdups++;
}
elsif($function =~ /wcsdup\(0x([0-9a-f]*)\) \((\d*)\) = 0x([0-9a-f]*)/) {
# wcsdup(a5b50) (8) = df7c0
$dup = $1;
$size = $2;
$addr = $3;
$getmem{$addr}="$source:$linenum";
$sizeataddr{$addr}=$size;
$totalmem += $size;
if($trace) {
printf("WCSDUP: $size bytes at %s, makes totally: %d bytes\n",
$getmem{$addr}, $totalmem);
}
newtotal($totalmem);
$wcsdups++;
}
else {
print "Not recognized input line: $function\n";
}
}
# FD url.c:1282 socket() = 5
elsif($_ =~ /^FD ([^ ]*):(\d*) (.*)/) {
# generic match for the filename+linenumber
$source = $1;
$linenum = $2;
$function = $3;
if($function =~ /socket\(\) = (\d*)/) {
$filedes{$1}=1;
$getfile{$1}="$source:$linenum";
$openfile++;
$sockets++; # number of socket() calls
}
elsif($function =~ /socketpair\(\) = (\d*) (\d*)/) {
$filedes{$1}=1;
$getfile{$1}="$source:$linenum";
$openfile++;
$filedes{$2}=1;
$getfile{$2}="$source:$linenum";
$openfile++;
}
elsif($function =~ /accept\(\) = (\d*)/) {
$filedes{$1}=1;
$getfile{$1}="$source:$linenum";
$openfile++;
}
elsif($function =~ /sclose\((\d*)\)/) {
if($filedes{$1} != 1) {
print "Close without open: $line\n";
}
else {
$filedes{$1}=0; # closed now
$openfile--;
}
}
}
# FILE url.c:1282 fopen("blabla") = 0x5ddd
elsif($_ =~ /^FILE ([^ ]*):(\d*) (.*)/) {
# generic match for the filename+linenumber
$source = $1;
$linenum = $2;
$function = $3;
if($function =~ /f[d]*open\(\"(.*)\",\"([^\"]*)\"\) = (\(nil\)|0x([0-9a-f]*))/) {
if($3 eq "(nil)") {
;
}
else {
$fopen{$4}=1;
$fopenfile{$4}="$source:$linenum";
$fopens++;
}
}
# fclose(0x1026c8)
elsif($function =~ /fclose\(0x([0-9a-f]*)\)/) {
if(!$fopen{$1}) {
print "fclose() without fopen(): $line\n";
}
else {
$fopen{$1}=0;
$fopens--;
}
}
}
# GETNAME url.c:1901 getnameinfo()
elsif($_ =~ /^GETNAME ([^ ]*):(\d*) (.*)/) {
# not much to do
}
# SEND url.c:1901 send(83) = 83
elsif($_ =~ /^SEND ([^ ]*):(\d*) (.*)/) {
$sends++;
}
# RECV url.c:1901 recv(102400) = 256
elsif($_ =~ /^RECV ([^ ]*):(\d*) (.*)/) {
$recvs++;
}
# ADDR url.c:1282 getaddrinfo() = 0x5ddd
elsif($_ =~ /^ADDR ([^ ]*):(\d*) (.*)/) {
# generic match for the filename+linenumber
$source = $1;
$linenum = $2;
$function = $3;
if($function =~ /getaddrinfo\(\) = (\(nil\)|0x([0-9a-f]*))/) {
my $add = $2;
if($add eq "(nil)") {
;
}
else {
$addrinfo{$add}=1;
$addrinfofile{$add}="$source:$linenum";
$addrinfos++;
}
if($trace) {
printf("GETADDRINFO ($source:$linenum)\n");
}
}
# fclose(0x1026c8)
elsif($function =~ /freeaddrinfo\(0x([0-9a-f]*)\)/) {
if(!$addrinfo{$1}) {
print "freeaddrinfo() without getaddrinfo(): $line\n";
}
else {
$addrinfo{$1}=0;
$addrinfos--;
}
if($trace) {
printf("FREEADDRINFO ($source:$linenum)\n");
}
}
}
else {
print "Not recognized prefix line: $line\n";
}
}
close(FILE);
if($totalmem) {
print "Leak detected: memory still allocated: $totalmem bytes\n";
for(keys %sizeataddr) {
$addr = $_;
$size = $sizeataddr{$addr};
if($size > 0) {
print "At $addr, there's $size bytes.\n";
print " allocated by ".$getmem{$addr}."\n";
}
}
}
if($openfile) {
for(keys %filedes) {
if($filedes{$_} == 1) {
print "Open file descriptor created at ".$getfile{$_}."\n";
}
}
}
if($fopens) {
print "Open FILE handles left at:\n";
for(keys %fopen) {
if($fopen{$_} == 1) {
print "fopen() called at ".$fopenfile{$_}."\n";
}
}
}
if($addrinfos) {
print "IPv6-style name resolve data left at:\n";
for(keys %addrinfofile) {
if($addrinfo{$_} == 1) {
print "getaddrinfo() called at ".$addrinfofile{$_}."\n";
}
}
}
if($verbose) {
print "Mallocs: $mallocs\n",
"Reallocs: $reallocs\n",
"Callocs: $callocs\n",
"Strdups: $strdups\n",
"Wcsdups: $wcsdups\n",
"Frees: $frees\n",
"Sends: $sends\n",
"Recvs: $recvs\n",
"Sockets: $sockets\n",
"Allocations: ".($mallocs + $callocs + $reallocs + $strdups + $wcsdups)."\n",
"Operations: ".($mallocs + $callocs + $reallocs + $strdups + $wcsdups + $sends + $recvs + $sockets)."\n";
print "Maximum allocated: $maxmem\n";
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/http2-server.pl | #!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 2016 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
#***************************************************************************
# This script invokes nghttpx properly to have it serve HTTP/2 for us.
# nghttpx runs as a proxy in front of our "actual" HTTP/1 server.
my $pidfile = "log/nghttpx.pid";
my $logfile = "log/http2.log";
my $nghttpx = "nghttpx";
my $listenport = 9015;
my $connect = "127.0.0.1,8990";
#***************************************************************************
# Process command line options
#
while(@ARGV) {
if($ARGV[0] eq '--verbose') {
$verbose = 1;
}
elsif($ARGV[0] eq '--pidfile') {
if($ARGV[1]) {
$pidfile = $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--nghttpx') {
if($ARGV[1]) {
$nghttpx = $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--port') {
if($ARGV[1]) {
$listenport = $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--connect') {
if($ARGV[1]) {
$connect = $ARGV[1];
$connect =~ s/:/,/;
shift @ARGV;
}
}
elsif($ARGV[0] eq '--logfile') {
if($ARGV[1]) {
$logfile = $ARGV[1];
shift @ARGV;
}
}
else {
print STDERR "\nWarning: http2-server.pl unknown parameter: $ARGV[0]\n";
}
shift @ARGV;
}
my $cmdline="$nghttpx --backend=$connect ".
"--frontend=\"*,$listenport;no-tls\" ".
"--log-level=INFO ".
"--pid-file=$pidfile ".
"--errorlog-file=$logfile";
print "RUN: $cmdline\n" if($verbose);
system("$cmdline 2>/dev/null");
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/extern-scan.pl | #!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 2010 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
#
#
use strict;
use warnings;
# we may get the dir root pointed out
my $root=$ARGV[0] || ".";
my @incs = (
"$root/include/curl/curl.h",
"$root/include/curl/easy.h",
"$root/include/curl/mprintf.h",
"$root/include/curl/multi.h",
);
my $verbose=0;
my $summary=0;
my $misses=0;
my @syms;
my %doc;
my %rem;
sub scanheader {
my ($f)=@_;
open H, "<$f" || die;
while(<H>) {
if (/^(CURL_EXTERN.*)/) {
my $decl = $1;
$decl =~ s/\r$//;
print "$decl\n";
}
}
close H;
}
foreach my $i (@incs) {
scanheader($i);
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/dictserver.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 2008 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
#
""" DICT server """
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import argparse
import logging
import os
import sys
from util import ClosingFileHandler
try: # Python 2
import SocketServer as socketserver
except ImportError: # Python 3
import socketserver
log = logging.getLogger(__name__)
HOST = "localhost"
# The strings that indicate the test framework is checking our aliveness
VERIFIED_REQ = b"verifiedserver"
VERIFIED_RSP = "WE ROOLZ: {pid}"
def dictserver(options):
"""
Starts up a TCP server with a DICT handler and serves DICT requests
forever.
"""
if options.pidfile:
pid = os.getpid()
# see tests/server/util.c function write_pidfile
if os.name == "nt":
pid += 65536
with open(options.pidfile, "w") as f:
f.write(str(pid))
local_bind = (options.host, options.port)
log.info("[DICT] Listening on %s", local_bind)
# Need to set the allow_reuse on the class, not on the instance.
socketserver.TCPServer.allow_reuse_address = True
server = socketserver.TCPServer(local_bind, DictHandler)
server.serve_forever()
return ScriptRC.SUCCESS
class DictHandler(socketserver.BaseRequestHandler):
"""Handler class for DICT connections.
"""
def handle(self):
"""
Simple function which responds to all queries with a 552.
"""
try:
# First, send a response to allow the server to continue.
rsp = "220 dictserver <xnooptions> <msgid@msgid>\n"
self.request.sendall(rsp.encode("utf-8"))
# Receive the request.
data = self.request.recv(1024).strip()
log.debug("[DICT] Incoming data: %r", data)
if VERIFIED_REQ in data:
log.debug("[DICT] Received verification request from test "
"framework")
pid = os.getpid()
# see tests/server/util.c function write_pidfile
if os.name == "nt":
pid += 65536
response_data = VERIFIED_RSP.format(pid=pid)
else:
log.debug("[DICT] Received normal request")
response_data = "No matches"
# Send back a failure to find.
response = "552 {0}\n".format(response_data)
log.debug("[DICT] Responding with %r", response)
self.request.sendall(response.encode("utf-8"))
except IOError:
log.exception("[DICT] IOError hit during request")
def get_options():
parser = argparse.ArgumentParser()
parser.add_argument("--port", action="store", default=9016,
type=int, help="port to listen on")
parser.add_argument("--host", action="store", default=HOST,
help="host to listen on")
parser.add_argument("--verbose", action="store", type=int, default=0,
help="verbose output")
parser.add_argument("--pidfile", action="store",
help="file name for the PID")
parser.add_argument("--logfile", action="store",
help="file name for the log")
parser.add_argument("--srcdir", action="store", help="test directory")
parser.add_argument("--id", action="store", help="server ID")
parser.add_argument("--ipv4", action="store_true", default=0,
help="IPv4 flag")
return parser.parse_args()
def setup_logging(options):
"""
Set up logging from the command line options
"""
root_logger = logging.getLogger()
add_stdout = False
formatter = logging.Formatter("%(asctime)s %(levelname)-5.5s %(message)s")
# Write out to a logfile
if options.logfile:
handler = ClosingFileHandler(options.logfile)
handler.setFormatter(formatter)
handler.setLevel(logging.DEBUG)
root_logger.addHandler(handler)
else:
# The logfile wasn't specified. Add a stdout logger.
add_stdout = True
if options.verbose:
# Add a stdout logger as well in verbose mode
root_logger.setLevel(logging.DEBUG)
add_stdout = True
else:
root_logger.setLevel(logging.INFO)
if add_stdout:
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setFormatter(formatter)
stdout_handler.setLevel(logging.DEBUG)
root_logger.addHandler(stdout_handler)
class ScriptRC(object):
"""Enum for script return codes"""
SUCCESS = 0
FAILURE = 1
EXCEPTION = 2
class ScriptException(Exception):
pass
if __name__ == '__main__':
# Get the options from the user.
options = get_options()
# Setup logging using the user options
setup_logging(options)
# Run main script.
try:
rc = dictserver(options)
except Exception as e:
log.exception(e)
rc = ScriptRC.EXCEPTION
if options.pidfile and os.path.isfile(options.pidfile):
os.unlink(options.pidfile)
log.info("[DICT] Returning %d", rc)
sys.exit(rc)
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/negtelnetserver.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 2017 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
""" A telnet server which negotiates"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import argparse
import logging
import os
import sys
from util import ClosingFileHandler
if sys.version_info.major >= 3:
import socketserver
else:
import SocketServer as socketserver
log = logging.getLogger(__name__)
HOST = "localhost"
IDENT = "NTEL"
# The strings that indicate the test framework is checking our aliveness
VERIFIED_REQ = "verifiedserver"
VERIFIED_RSP = "WE ROOLZ: {pid}"
def telnetserver(options):
"""
Starts up a TCP server with a telnet handler and serves DICT requests
forever.
"""
if options.pidfile:
pid = os.getpid()
# see tests/server/util.c function write_pidfile
if os.name == "nt":
pid += 65536
with open(options.pidfile, "w") as f:
f.write(str(pid))
local_bind = (HOST, options.port)
log.info("Listening on %s", local_bind)
# Need to set the allow_reuse on the class, not on the instance.
socketserver.TCPServer.allow_reuse_address = True
server = socketserver.TCPServer(local_bind, NegotiatingTelnetHandler)
server.serve_forever()
return ScriptRC.SUCCESS
class NegotiatingTelnetHandler(socketserver.BaseRequestHandler):
"""Handler class for Telnet connections.
"""
def handle(self):
"""
Negotiates options before reading data.
"""
neg = Negotiator(self.request)
try:
# Send some initial negotiations.
neg.send_do("NEW_ENVIRON")
neg.send_will("NEW_ENVIRON")
neg.send_dont("NAWS")
neg.send_wont("NAWS")
# Get the data passed through the negotiator
data = neg.recv(1024)
log.debug("Incoming data: %r", data)
if VERIFIED_REQ.encode('utf-8') in data:
log.debug("Received verification request from test framework")
pid = os.getpid()
# see tests/server/util.c function write_pidfile
if os.name == "nt":
pid += 65536
response = VERIFIED_RSP.format(pid=pid)
response_data = response.encode('utf-8')
else:
log.debug("Received normal request - echoing back")
response_data = data.decode('utf-8').strip().encode('utf-8')
if response_data:
log.debug("Sending %r", response_data)
self.request.sendall(response_data)
except IOError:
log.exception("IOError hit during request")
class Negotiator(object):
NO_NEG = 0
START_NEG = 1
WILL = 2
WONT = 3
DO = 4
DONT = 5
def __init__(self, tcp):
self.tcp = tcp
self.state = self.NO_NEG
def recv(self, bytes):
"""
Read bytes from TCP, handling negotiation sequences
:param bytes: Number of bytes to read
:return: a buffer of bytes
"""
buffer = bytearray()
# If we keep receiving negotiation sequences, we won't fill the buffer.
# Keep looping while we can, and until we have something to give back
# to the caller.
while len(buffer) == 0:
data = self.tcp.recv(bytes)
if not data:
# TCP failed to give us any data. Break out.
break
for byte_int in bytearray(data):
if self.state == self.NO_NEG:
self.no_neg(byte_int, buffer)
elif self.state == self.START_NEG:
self.start_neg(byte_int)
elif self.state in [self.WILL, self.WONT, self.DO, self.DONT]:
self.handle_option(byte_int)
else:
# Received an unexpected byte. Stop negotiations
log.error("Unexpected byte %s in state %s",
byte_int,
self.state)
self.state = self.NO_NEG
return buffer
def no_neg(self, byte_int, buffer):
# Not negotiating anything thus far. Check to see if we
# should.
if byte_int == NegTokens.IAC:
# Start negotiation
log.debug("Starting negotiation (IAC)")
self.state = self.START_NEG
else:
# Just append the incoming byte to the buffer
buffer.append(byte_int)
def start_neg(self, byte_int):
# In a negotiation.
log.debug("In negotiation (%s)",
NegTokens.from_val(byte_int))
if byte_int == NegTokens.WILL:
# Client is confirming they are willing to do an option
log.debug("Client is willing")
self.state = self.WILL
elif byte_int == NegTokens.WONT:
# Client is confirming they are unwilling to do an
# option
log.debug("Client is unwilling")
self.state = self.WONT
elif byte_int == NegTokens.DO:
# Client is indicating they can do an option
log.debug("Client can do")
self.state = self.DO
elif byte_int == NegTokens.DONT:
# Client is indicating they can't do an option
log.debug("Client can't do")
self.state = self.DONT
else:
# Received an unexpected byte. Stop negotiations
log.error("Unexpected byte %s in state %s",
byte_int,
self.state)
self.state = self.NO_NEG
def handle_option(self, byte_int):
if byte_int in [NegOptions.BINARY,
NegOptions.CHARSET,
NegOptions.SUPPRESS_GO_AHEAD,
NegOptions.NAWS,
NegOptions.NEW_ENVIRON]:
log.debug("Option: %s", NegOptions.from_val(byte_int))
# No further negotiation of this option needed. Reset the state.
self.state = self.NO_NEG
else:
# Received an unexpected byte. Stop negotiations
log.error("Unexpected byte %s in state %s",
byte_int,
self.state)
self.state = self.NO_NEG
def send_message(self, message_ints):
self.tcp.sendall(bytearray(message_ints))
def send_iac(self, arr):
message = [NegTokens.IAC]
message.extend(arr)
self.send_message(message)
def send_do(self, option_str):
log.debug("Sending DO %s", option_str)
self.send_iac([NegTokens.DO, NegOptions.to_val(option_str)])
def send_dont(self, option_str):
log.debug("Sending DONT %s", option_str)
self.send_iac([NegTokens.DONT, NegOptions.to_val(option_str)])
def send_will(self, option_str):
log.debug("Sending WILL %s", option_str)
self.send_iac([NegTokens.WILL, NegOptions.to_val(option_str)])
def send_wont(self, option_str):
log.debug("Sending WONT %s", option_str)
self.send_iac([NegTokens.WONT, NegOptions.to_val(option_str)])
class NegBase(object):
@classmethod
def to_val(cls, name):
return getattr(cls, name)
@classmethod
def from_val(cls, val):
for k in cls.__dict__.keys():
if getattr(cls, k) == val:
return k
return "<unknown>"
class NegTokens(NegBase):
# The start of a negotiation sequence
IAC = 255
# Confirm willingness to negotiate
WILL = 251
# Confirm unwillingness to negotiate
WONT = 252
# Indicate willingness to negotiate
DO = 253
# Indicate unwillingness to negotiate
DONT = 254
# The start of sub-negotiation options.
SB = 250
# The end of sub-negotiation options.
SE = 240
class NegOptions(NegBase):
# Binary Transmission
BINARY = 0
# Suppress Go Ahead
SUPPRESS_GO_AHEAD = 3
# NAWS - width and height of client
NAWS = 31
# NEW-ENVIRON - environment variables on client
NEW_ENVIRON = 39
# Charset option
CHARSET = 42
def get_options():
parser = argparse.ArgumentParser()
parser.add_argument("--port", action="store", default=9019,
type=int, help="port to listen on")
parser.add_argument("--verbose", action="store", type=int, default=0,
help="verbose output")
parser.add_argument("--pidfile", action="store",
help="file name for the PID")
parser.add_argument("--logfile", action="store",
help="file name for the log")
parser.add_argument("--srcdir", action="store", help="test directory")
parser.add_argument("--id", action="store", help="server ID")
parser.add_argument("--ipv4", action="store_true", default=0,
help="IPv4 flag")
return parser.parse_args()
def setup_logging(options):
"""
Set up logging from the command line options
"""
root_logger = logging.getLogger()
add_stdout = False
formatter = logging.Formatter("%(asctime)s %(levelname)-5.5s "
"[{ident}] %(message)s"
.format(ident=IDENT))
# Write out to a logfile
if options.logfile:
handler = ClosingFileHandler(options.logfile)
handler.setFormatter(formatter)
handler.setLevel(logging.DEBUG)
root_logger.addHandler(handler)
else:
# The logfile wasn't specified. Add a stdout logger.
add_stdout = True
if options.verbose:
# Add a stdout logger as well in verbose mode
root_logger.setLevel(logging.DEBUG)
add_stdout = True
else:
root_logger.setLevel(logging.INFO)
if add_stdout:
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setFormatter(formatter)
stdout_handler.setLevel(logging.DEBUG)
root_logger.addHandler(stdout_handler)
class ScriptRC(object):
"""Enum for script return codes"""
SUCCESS = 0
FAILURE = 1
EXCEPTION = 2
class ScriptException(Exception):
pass
if __name__ == '__main__':
# Get the options from the user.
options = get_options()
# Setup logging using the user options
setup_logging(options)
# Run main script.
try:
rc = telnetserver(options)
except Exception as e:
log.exception(e)
rc = ScriptRC.EXCEPTION
if options.pidfile and os.path.isfile(options.pidfile):
os.unlink(options.pidfile)
log.info("Returning %d", rc)
sys.exit(rc)
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/ftpserver.pl | #!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
# This is a server designed for the curl test suite.
#
# In December 2009 we started remaking the server to support more protocols
# that are similar in spirit. Like POP3, IMAP and SMTP in addition to the FTP
# it already supported since a long time. Note that it still only supports one
# protocol per invoke. You need to start multiple servers to support multiple
# protocols simultaneously.
#
# It is meant to exercise curl, it is not meant to be a fully working
# or even very standard compliant server.
#
# You may optionally specify port on the command line, otherwise it'll
# default to port 8921.
#
# All socket/network/TCP related stuff is done by the 'sockfilt' program.
#
BEGIN {
push(@INC, $ENV{'srcdir'}) if(defined $ENV{'srcdir'});
push(@INC, ".");
# sub second timestamping needs Time::HiRes
eval {
no warnings "all";
require Time::HiRes;
import Time::HiRes qw( gettimeofday );
}
}
use strict;
use warnings;
use IPC::Open2;
use Digest::MD5;
require "getpart.pm";
require "ftp.pm";
require "directories.pm";
use serverhelp qw(
servername_str
server_pidfilename
server_logfilename
mainsockf_pidfilename
mainsockf_logfilename
datasockf_pidfilename
datasockf_logfilename
);
use sshhelp qw(
exe_ext
);
#**********************************************************************
# global vars...
#
my $verbose = 0; # set to 1 for debugging
my $idstr = ""; # server instance string
my $idnum = 1; # server instance number
my $ipvnum = 4; # server IPv number (4 or 6)
my $proto = 'ftp'; # default server protocol
my $srcdir; # directory where ftpserver.pl is located
my $srvrname; # server name for presentation purposes
my $cwd_testno; # test case numbers extracted from CWD command
my $testno = 0; # test case number (read from ftpserver.cmd)
my $path = '.';
my $logdir = $path .'/log';
#**********************************************************************
# global vars used for server address and primary listener port
#
my $port = 8921; # default primary listener port
my $listenaddr = '127.0.0.1'; # default address for listener port
#**********************************************************************
# global vars used for file names
#
my $pidfile; # server pid file name
my $portfile=".ftpserver.port"; # server port file name
my $logfile; # server log file name
my $mainsockf_pidfile; # pid file for primary connection sockfilt process
my $mainsockf_logfile; # log file for primary connection sockfilt process
my $datasockf_pidfile; # pid file for secondary connection sockfilt process
my $datasockf_logfile; # log file for secondary connection sockfilt process
#**********************************************************************
# global vars used for server logs advisor read lock handling
#
my $SERVERLOGS_LOCK = 'log/serverlogs.lock';
my $serverlogslocked = 0;
#**********************************************************************
# global vars used for child processes PID tracking
#
my $sfpid; # PID for primary connection sockfilt process
my $slavepid; # PID for secondary connection sockfilt process
#**********************************************************************
# global typeglob filehandle vars to read/write from/to sockfilters
#
local *SFREAD; # used to read from primary connection
local *SFWRITE; # used to write to primary connection
local *DREAD; # used to read from secondary connection
local *DWRITE; # used to write to secondary connection
my $sockfilt_timeout = 5; # default timeout for sockfilter eXsysreads
#**********************************************************************
# global vars which depend on server protocol selection
#
my %commandfunc; # protocol command specific function callbacks
my %displaytext; # text returned to client before callback runs
#**********************************************************************
# global vars customized for each test from the server commands file
#
my $ctrldelay; # set if server should throttle ctrl stream
my $datadelay; # set if server should throttle data stream
my $retrweirdo; # set if ftp server should use RETRWEIRDO
my $retrnosize; # set if ftp server should use RETRNOSIZE
my $pasvbadip; # set if ftp server should use PASVBADIP
my $nosave; # set if ftp server should not save uploaded data
my $nodataconn; # set if ftp srvr doesn't establish or accepts data channel
my $nodataconn425; # set if ftp srvr doesn't establish data ch and replies 425
my $nodataconn421; # set if ftp srvr doesn't establish data ch and replies 421
my $nodataconn150; # set if ftp srvr doesn't establish data ch and replies 150
my $storeresp;
my $postfetch;
my @capabilities; # set if server supports capability commands
my @auth_mechs; # set if server supports authentication commands
my %fulltextreply; #
my %commandreply; #
my %customcount; #
my %delayreply; #
#**********************************************************************
# global variables for to test ftp wildcardmatching or other test that
# need flexible LIST responses.. and corresponding files.
# $ftptargetdir is keeping the fake "name" of LIST directory.
#
my $ftplistparserstate;
my $ftptargetdir="";
#**********************************************************************
# global variables used when running a ftp server to keep state info
# relative to the secondary or data sockfilt process. Values of these
# variables should only be modified using datasockf_state() sub, given
# that they are closely related and relationship is a bit awkward.
#
my $datasockf_state = 'STOPPED'; # see datasockf_state() sub
my $datasockf_mode = 'none'; # ['none','active','passive']
my $datasockf_runs = 'no'; # ['no','yes']
my $datasockf_conn = 'no'; # ['no','yes']
#**********************************************************************
# global vars used for signal handling
#
my $got_exit_signal = 0; # set if program should finish execution ASAP
my $exit_signal; # first signal handled in exit_signal_handler
#**********************************************************************
# Mail related definitions
#
my $TEXT_PASSWORD = "secret";
my $POP3_TIMESTAMP = "<1972.987654321\@curl>";
#**********************************************************************
# exit_signal_handler will be triggered to indicate that the program
# should finish its execution in a controlled way as soon as possible.
# For now, program will also terminate from within this handler.
#
sub exit_signal_handler {
my $signame = shift;
# For now, simply mimic old behavior.
killsockfilters($proto, $ipvnum, $idnum, $verbose);
unlink($pidfile);
unlink($portfile);
if($serverlogslocked) {
$serverlogslocked = 0;
clear_advisor_read_lock($SERVERLOGS_LOCK);
}
exit;
}
#**********************************************************************
# logmsg is general message logging subroutine for our test servers.
#
sub logmsg {
my $now;
# sub second timestamping needs Time::HiRes
if($Time::HiRes::VERSION) {
my ($seconds, $usec) = gettimeofday();
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
localtime($seconds);
$now = sprintf("%02d:%02d:%02d.%06d ", $hour, $min, $sec, $usec);
}
else {
my $seconds = time();
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
localtime($seconds);
$now = sprintf("%02d:%02d:%02d ", $hour, $min, $sec);
}
if(open(LOGFILEFH, ">>$logfile")) {
print LOGFILEFH $now;
print LOGFILEFH @_;
close(LOGFILEFH);
}
}
sub ftpmsg {
# append to the server.input file
open(INPUT, ">>log/server$idstr.input") ||
logmsg "failed to open log/server$idstr.input\n";
print INPUT @_;
close(INPUT);
# use this, open->print->close system only to make the file
# open as little as possible, to make the test suite run
# better on windows/cygwin
}
#**********************************************************************
# eXsysread is a wrapper around perl's sysread() function. This will
# repeat the call to sysread() until it has actually read the complete
# number of requested bytes or an unrecoverable condition occurs.
# On success returns a positive value, the number of bytes requested.
# On failure or timeout returns zero.
#
sub eXsysread {
my $FH = shift;
my $scalar = shift;
my $nbytes = shift;
my $timeout = shift; # A zero timeout disables eXsysread() time limit
#
my $time_limited = 0;
my $timeout_rest = 0;
my $start_time = 0;
my $nread = 0;
my $rc;
$$scalar = "";
if((not defined $nbytes) || ($nbytes < 1)) {
logmsg "Error: eXsysread() failure: " .
"length argument must be positive\n";
return 0;
}
if((not defined $timeout) || ($timeout < 0)) {
logmsg "Error: eXsysread() failure: " .
"timeout argument must be zero or positive\n";
return 0;
}
if($timeout > 0) {
# caller sets eXsysread() time limit
$time_limited = 1;
$timeout_rest = $timeout;
$start_time = int(time());
}
while($nread < $nbytes) {
if($time_limited) {
eval {
local $SIG{ALRM} = sub { die "alarm\n"; };
alarm $timeout_rest;
$rc = sysread($FH, $$scalar, $nbytes - $nread, $nread);
alarm 0;
};
$timeout_rest = $timeout - (int(time()) - $start_time);
if($timeout_rest < 1) {
logmsg "Error: eXsysread() failure: timed out\n";
return 0;
}
}
else {
$rc = sysread($FH, $$scalar, $nbytes - $nread, $nread);
}
if($got_exit_signal) {
logmsg "Error: eXsysread() failure: signalled to die\n";
return 0;
}
if(not defined $rc) {
if($!{EINTR}) {
logmsg "Warning: retrying sysread() interrupted system call\n";
next;
}
if($!{EAGAIN}) {
logmsg "Warning: retrying sysread() due to EAGAIN\n";
next;
}
if($!{EWOULDBLOCK}) {
logmsg "Warning: retrying sysread() due to EWOULDBLOCK\n";
next;
}
logmsg "Error: sysread() failure: $!\n";
return 0;
}
if($rc < 0) {
logmsg "Error: sysread() failure: returned negative value $rc\n";
return 0;
}
if($rc == 0) {
logmsg "Error: sysread() failure: read zero bytes\n";
return 0;
}
$nread += $rc;
}
return $nread;
}
#**********************************************************************
# read_mainsockf attempts to read the given amount of output from the
# sockfilter which is in use for the main or primary connection. This
# reads untranslated sockfilt lingo which may hold data read from the
# main or primary socket. On success returns 1, otherwise zero.
#
sub read_mainsockf {
my $scalar = shift;
my $nbytes = shift;
my $timeout = shift; # Optional argument, if zero blocks indefinitely
my $FH = \*SFREAD;
if(not defined $timeout) {
$timeout = $sockfilt_timeout + ($nbytes >> 12);
}
if(eXsysread($FH, $scalar, $nbytes, $timeout) != $nbytes) {
my ($fcaller, $lcaller) = (caller)[1,2];
logmsg "Error: read_mainsockf() failure at $fcaller " .
"line $lcaller. Due to eXsysread() failure\n";
return 0;
}
return 1;
}
#**********************************************************************
# read_datasockf attempts to read the given amount of output from the
# sockfilter which is in use for the data or secondary connection. This
# reads untranslated sockfilt lingo which may hold data read from the
# data or secondary socket. On success returns 1, otherwise zero.
#
sub read_datasockf {
my $scalar = shift;
my $nbytes = shift;
my $timeout = shift; # Optional argument, if zero blocks indefinitely
my $FH = \*DREAD;
if(not defined $timeout) {
$timeout = $sockfilt_timeout + ($nbytes >> 12);
}
if(eXsysread($FH, $scalar, $nbytes, $timeout) != $nbytes) {
my ($fcaller, $lcaller) = (caller)[1,2];
logmsg "Error: read_datasockf() failure at $fcaller " .
"line $lcaller. Due to eXsysread() failure\n";
return 0;
}
return 1;
}
sub sysread_or_die {
my $FH = shift;
my $scalar = shift;
my $length = shift;
my $fcaller;
my $lcaller;
my $result;
$result = sysread($$FH, $$scalar, $length);
if(not defined $result) {
($fcaller, $lcaller) = (caller)[1,2];
logmsg "Failed to read input\n";
logmsg "Error: $srvrname server, sysread error: $!\n";
logmsg "Exited from sysread_or_die() at $fcaller " .
"line $lcaller. $srvrname server, sysread error: $!\n";
killsockfilters($proto, $ipvnum, $idnum, $verbose);
unlink($pidfile);
unlink($portfile);
if($serverlogslocked) {
$serverlogslocked = 0;
clear_advisor_read_lock($SERVERLOGS_LOCK);
}
exit;
}
elsif($result == 0) {
($fcaller, $lcaller) = (caller)[1,2];
logmsg "Failed to read input\n";
logmsg "Error: $srvrname server, read zero\n";
logmsg "Exited from sysread_or_die() at $fcaller " .
"line $lcaller. $srvrname server, read zero\n";
killsockfilters($proto, $ipvnum, $idnum, $verbose);
unlink($pidfile);
unlink($portfile);
if($serverlogslocked) {
$serverlogslocked = 0;
clear_advisor_read_lock($SERVERLOGS_LOCK);
}
exit;
}
return $result;
}
sub startsf {
my $mainsockfcmd = "./server/sockfilt".exe_ext('SRV')." " .
"--ipv$ipvnum --port $port " .
"--pidfile \"$mainsockf_pidfile\" " .
"--portfile \"$portfile\" " .
"--logfile \"$mainsockf_logfile\"";
$sfpid = open2(*SFREAD, *SFWRITE, $mainsockfcmd);
print STDERR "$mainsockfcmd\n" if($verbose);
print SFWRITE "PING\n";
my $pong;
sysread_or_die(\*SFREAD, \$pong, 5);
if($pong !~ /^PONG/) {
logmsg "Failed sockfilt command: $mainsockfcmd\n";
killsockfilters($proto, $ipvnum, $idnum, $verbose);
unlink($pidfile);
unlink($portfile);
if($serverlogslocked) {
$serverlogslocked = 0;
clear_advisor_read_lock($SERVERLOGS_LOCK);
}
die "Failed to start sockfilt!";
}
}
#**********************************************************************
# Returns the given test's reply data
#
sub getreplydata {
my ($num) = @_;
my $testpart = "";
$num =~ s/^([^0-9]*)//;
if($num > 10000) {
$testpart = $num % 10000;
}
my @data = getpart("reply", "data$testpart");
if((!@data) && ($testpart ne "")) {
@data = getpart("reply", "data");
}
return @data;
}
sub sockfilt {
my $l;
foreach $l (@_) {
printf SFWRITE "DATA\n%04x\n", length($l);
print SFWRITE $l;
}
}
sub sockfiltsecondary {
my $l;
foreach $l (@_) {
printf DWRITE "DATA\n%04x\n", length($l);
print DWRITE $l;
}
}
#**********************************************************************
# Send data to the client on the control stream, which happens to be plain
# stdout.
#
sub sendcontrol {
if(!$ctrldelay) {
# spit it all out at once
sockfilt @_;
}
else {
my $a = join("", @_);
my @a = split("", $a);
for(@a) {
sockfilt $_;
portable_sleep(0.01);
}
}
my $log;
foreach $log (@_) {
my $l = $log;
$l =~ s/\r/[CR]/g;
$l =~ s/\n/[LF]/g;
logmsg "> \"$l\"\n";
}
}
#**********************************************************************
# Send data to the FTP client on the data stream when data connection
# is actually established. Given that this sub should only be called
# when a data connection is supposed to be established, calling this
# without a data connection is an indication of weak logic somewhere.
#
sub senddata {
my $l;
if($datasockf_conn eq 'no') {
logmsg "WARNING: Detected data sending attempt without DATA channel\n";
foreach $l (@_) {
logmsg "WARNING: Data swallowed: $l\n"
}
return;
}
foreach $l (@_) {
if(!$datadelay) {
# spit it all out at once
sockfiltsecondary $l;
}
else {
# pause between each byte
for (split(//,$l)) {
sockfiltsecondary $_;
portable_sleep(0.01);
}
}
}
}
#**********************************************************************
# protocolsetup initializes the 'displaytext' and 'commandfunc' hashes
# for the given protocol. References to protocol command callbacks are
# stored in 'commandfunc' hash, and text which will be returned to the
# client before the command callback runs is stored in 'displaytext'.
#
sub protocolsetup {
my $proto = $_[0];
if($proto eq 'ftp') {
%commandfunc = (
'PORT' => \&PORT_ftp,
'EPRT' => \&PORT_ftp,
'LIST' => \&LIST_ftp,
'NLST' => \&NLST_ftp,
'PASV' => \&PASV_ftp,
'CWD' => \&CWD_ftp,
'PWD' => \&PWD_ftp,
'EPSV' => \&PASV_ftp,
'RETR' => \&RETR_ftp,
'SIZE' => \&SIZE_ftp,
'REST' => \&REST_ftp,
'STOR' => \&STOR_ftp,
'APPE' => \&STOR_ftp, # append looks like upload
'MDTM' => \&MDTM_ftp,
);
%displaytext = (
'USER' => '331 We are happy you popped in!',
'PASS' => '230 Welcome you silly person',
'PORT' => '200 You said PORT - I say FINE',
'TYPE' => '200 I modify TYPE as you wanted',
'LIST' => '150 here comes a directory',
'NLST' => '150 here comes a directory',
'CWD' => '250 CWD command successful.',
'SYST' => '215 UNIX Type: L8', # just fake something
'QUIT' => '221 bye bye baby', # just reply something
'MKD' => '257 Created your requested directory',
'REST' => '350 Yeah yeah we set it there for you',
'DELE' => '200 OK OK OK whatever you say',
'RNFR' => '350 Received your order. Please provide more',
'RNTO' => '250 Ok, thanks. File renaming completed.',
'NOOP' => '200 Yes, I\'m very good at doing nothing.',
'PBSZ' => '500 PBSZ not implemented',
'PROT' => '500 PROT not implemented',
'welcome' => join("",
'220- _ _ ____ _ '."\r\n",
'220- ___| | | | _ \| | '."\r\n",
'220- / __| | | | |_) | | '."\r\n",
'220- | (__| |_| | _ {| |___ '."\r\n",
'220 \___|\___/|_| \_\_____|'."\r\n")
);
}
elsif($proto eq 'pop3') {
%commandfunc = (
'APOP' => \&APOP_pop3,
'AUTH' => \&AUTH_pop3,
'CAPA' => \&CAPA_pop3,
'DELE' => \&DELE_pop3,
'LIST' => \&LIST_pop3,
'NOOP' => \&NOOP_pop3,
'PASS' => \&PASS_pop3,
'QUIT' => \&QUIT_pop3,
'RETR' => \&RETR_pop3,
'RSET' => \&RSET_pop3,
'STAT' => \&STAT_pop3,
'TOP' => \&TOP_pop3,
'UIDL' => \&UIDL_pop3,
'USER' => \&USER_pop3,
);
%displaytext = (
'welcome' => join("",
' _ _ ____ _ '."\r\n",
' ___| | | | _ \| | '."\r\n",
' / __| | | | |_) | | '."\r\n",
' | (__| |_| | _ {| |___ '."\r\n",
' \___|\___/|_| \_\_____|'."\r\n",
'+OK curl POP3 server ready to serve '."\r\n")
);
}
elsif($proto eq 'imap') {
%commandfunc = (
'APPEND' => \&APPEND_imap,
'CAPABILITY' => \&CAPABILITY_imap,
'CHECK' => \&CHECK_imap,
'CLOSE' => \&CLOSE_imap,
'COPY' => \©_imap,
'CREATE' => \&CREATE_imap,
'DELETE' => \&DELETE_imap,
'EXAMINE' => \&EXAMINE_imap,
'EXPUNGE' => \&EXPUNGE_imap,
'FETCH' => \&FETCH_imap,
'LIST' => \&LIST_imap,
'LSUB' => \&LSUB_imap,
'LOGIN' => \&LOGIN_imap,
'LOGOUT' => \&LOGOUT_imap,
'NOOP' => \&NOOP_imap,
'RENAME' => \&RENAME_imap,
'SEARCH' => \&SEARCH_imap,
'SELECT' => \&SELECT_imap,
'STATUS' => \&STATUS_imap,
'STORE' => \&STORE_imap,
'UID' => \&UID_imap,
'IDLE' => \&IDLE_imap,
);
%displaytext = (
'welcome' => join("",
' _ _ ____ _ '."\r\n",
' ___| | | | _ \| | '."\r\n",
' / __| | | | |_) | | '."\r\n",
' | (__| |_| | _ {| |___ '."\r\n",
' \___|\___/|_| \_\_____|'."\r\n",
'* OK curl IMAP server ready to serve'."\r\n")
);
}
elsif($proto eq 'smtp') {
%commandfunc = (
'DATA' => \&DATA_smtp,
'EHLO' => \&EHLO_smtp,
'EXPN' => \&EXPN_smtp,
'HELO' => \&HELO_smtp,
'HELP' => \&HELP_smtp,
'MAIL' => \&MAIL_smtp,
'NOOP' => \&NOOP_smtp,
'RSET' => \&RSET_smtp,
'RCPT' => \&RCPT_smtp,
'VRFY' => \&VRFY_smtp,
'QUIT' => \&QUIT_smtp,
);
%displaytext = (
'welcome' => join("",
'220- _ _ ____ _ '."\r\n",
'220- ___| | | | _ \| | '."\r\n",
'220- / __| | | | |_) | | '."\r\n",
'220- | (__| |_| | _ {| |___ '."\r\n",
'220 \___|\___/|_| \_\_____|'."\r\n")
);
}
}
sub close_dataconn {
my ($closed)=@_; # non-zero if already disconnected
my $datapid = processexists($datasockf_pidfile);
logmsg "=====> Closing $datasockf_mode DATA connection...\n";
if(!$closed) {
if($datapid > 0) {
logmsg "Server disconnects $datasockf_mode DATA connection\n";
print DWRITE "DISC\n";
my $i;
sysread DREAD, $i, 5;
logmsg "Server disconnected $datasockf_mode DATA connection\n";
}
else {
logmsg "Server finds $datasockf_mode DATA connection already ".
"disconnected\n";
}
}
else {
logmsg "Server knows $datasockf_mode DATA connection is already ".
"disconnected\n";
}
if($datapid > 0) {
logmsg "DATA sockfilt for $datasockf_mode data channel quits ".
"(pid $datapid)\n";
print DWRITE "QUIT\n";
pidwait($datapid, 0);
unlink($datasockf_pidfile) if(-f $datasockf_pidfile);
logmsg "DATA sockfilt for $datasockf_mode data channel quit ".
"(pid $datapid)\n";
}
else {
logmsg "DATA sockfilt for $datasockf_mode data channel already ".
"dead\n";
}
logmsg "=====> Closed $datasockf_mode DATA connection\n";
datasockf_state('STOPPED');
}
################
################ SMTP commands
################
# The type of server (SMTP or ESMTP)
my $smtp_type;
# The client (which normally contains the test number)
my $smtp_client;
sub EHLO_smtp {
my ($client) = @_;
my @data;
# TODO: Get the IP address of the client connection to use in the
# EHLO response when the client doesn't specify one but for now use
# 127.0.0.1
if(!$client) {
$client = "[127.0.0.1]";
}
# Set the server type to ESMTP
$smtp_type = "ESMTP";
# Calculate the EHLO response
push @data, "$smtp_type pingpong test server Hello $client";
if((@capabilities) || (@auth_mechs)) {
my $mechs;
for my $c (@capabilities) {
push @data, $c;
}
for my $am (@auth_mechs) {
if(!$mechs) {
$mechs = "$am";
}
else {
$mechs .= " $am";
}
}
if($mechs) {
push @data, "AUTH $mechs";
}
}
# Send the EHLO response
for(my $i = 0; $i < @data; $i++) {
my $d = $data[$i];
if($i < @data - 1) {
sendcontrol "250-$d\r\n";
}
else {
sendcontrol "250 $d\r\n";
}
}
# Store the client (as it may contain the test number)
$smtp_client = $client;
return 0;
}
sub HELO_smtp {
my ($client) = @_;
# TODO: Get the IP address of the client connection to use in the HELO
# response when the client doesn't specify one but for now use 127.0.0.1
if(!$client) {
$client = "[127.0.0.1]";
}
# Set the server type to SMTP
$smtp_type = "SMTP";
# Send the HELO response
sendcontrol "250 $smtp_type pingpong test server Hello $client\r\n";
# Store the client (as it may contain the test number)
$smtp_client = $client;
return 0;
}
sub MAIL_smtp {
my ($args) = @_;
logmsg "MAIL_smtp got $args\n";
if (!$args) {
sendcontrol "501 Unrecognized parameter\r\n";
}
else {
my $from;
my $size;
my $smtputf8 = grep /^SMTPUTF8$/, @capabilities;
my @elements = split(/ /, $args);
# Get the FROM and SIZE parameters
for my $e (@elements) {
if($e =~ /^FROM:(.*)$/) {
$from = $1;
}
elsif($e =~ /^SIZE=(\d+)$/) {
$size = $1;
}
}
# this server doesn't "validate" MAIL FROM addresses
if (length($from)) {
my @found;
my $valid = 1;
# Check the capabilities for SIZE and if the specified size is
# greater than the message size then reject it
if (@found = grep /^SIZE (\d+)$/, @capabilities) {
if ($found[0] =~ /^SIZE (\d+)$/) {
if ($size > $1) {
$valid = 0;
}
}
}
if(!$valid) {
sendcontrol "552 Message size too large\r\n";
}
else {
sendcontrol "250 Sender OK\r\n";
}
}
else {
sendcontrol "501 Invalid address\r\n";
}
}
return 0;
}
sub RCPT_smtp {
my ($args) = @_;
logmsg "RCPT_smtp got $args\n";
# Get the TO parameter
if($args !~ /^TO:(.*)/) {
sendcontrol "501 Unrecognized parameter\r\n";
}
else {
my $smtputf8 = grep /^SMTPUTF8$/, @capabilities;
my $to = $1;
# Validate the to address (only a valid email address inside <> is
# allowed, such as <[email protected]>)
if ((!$smtputf8 && $to =~
/^<([a-zA-Z0-9._%+-]+)\@(([a-zA-Z0-9-]+)\.)+([a-zA-Z]{2,4})>$/) ||
($smtputf8 && $to =~
/^<([a-zA-Z0-9\x{80}-\x{ff}._%+-]+)\@(([a-zA-Z0-9\x{80}-\x{ff}-]+)\.)+([a-zA-Z]{2,4})>$/)) {
sendcontrol "250 Recipient OK\r\n";
}
else {
sendcontrol "501 Invalid address\r\n";
}
}
return 0;
}
sub DATA_smtp {
my ($args) = @_;
if ($args) {
sendcontrol "501 Unrecognized parameter\r\n";
}
elsif ($smtp_client !~ /^(\d*)$/) {
sendcontrol "501 Invalid arguments\r\n";
}
else {
sendcontrol "354 Show me the mail\r\n";
my $testno = $smtp_client;
my $filename = "log/upload.$testno";
logmsg "Store test number $testno in $filename\n";
open(FILE, ">$filename") ||
return 0; # failed to open output
my $line;
my $ulsize=0;
my $disc=0;
my $raw;
while (5 == (sysread \*SFREAD, $line, 5)) {
if($line eq "DATA\n") {
my $i;
my $eob;
sysread \*SFREAD, $i, 5;
my $size = 0;
if($i =~ /^([0-9a-fA-F]{4})\n/) {
$size = hex($1);
}
read_mainsockf(\$line, $size);
$ulsize += $size;
print FILE $line if(!$nosave);
$raw .= $line;
if($raw =~ /(?:^|\x0d\x0a)\x2e\x0d\x0a/) {
# end of data marker!
$eob = 1;
}
logmsg "> Appending $size bytes to file\n";
if($eob) {
logmsg "Found SMTP EOB marker\n";
last;
}
}
elsif($line eq "DISC\n") {
# disconnect!
$disc=1;
last;
}
else {
logmsg "No support for: $line";
last;
}
}
if($nosave) {
print FILE "$ulsize bytes would've been stored here\n";
}
close(FILE);
logmsg "received $ulsize bytes upload\n";
sendcontrol "250 OK, data received!\r\n";
}
return 0;
}
sub NOOP_smtp {
my ($args) = @_;
if($args) {
sendcontrol "501 Unrecognized parameter\r\n";
}
else {
sendcontrol "250 OK\r\n";
}
return 0;
}
sub RSET_smtp {
my ($args) = @_;
if($args) {
sendcontrol "501 Unrecognized parameter\r\n";
}
else {
sendcontrol "250 Resetting\r\n";
}
return 0;
}
sub HELP_smtp {
my ($args) = @_;
# One argument is optional
if($args) {
logmsg "HELP_smtp got $args\n";
}
if($smtp_client eq "verifiedserver") {
# This is the secret command that verifies that this actually is
# the curl test server
sendcontrol "214 WE ROOLZ: $$\r\n";
if($verbose) {
print STDERR "FTPD: We returned proof we are the test server\n";
}
logmsg "return proof we are we\n";
}
else {
sendcontrol "214-This server supports the following commands:\r\n";
if(@auth_mechs) {
sendcontrol "214 HELO EHLO RCPT DATA RSET MAIL VRFY EXPN QUIT HELP AUTH\r\n";
}
else {
sendcontrol "214 HELO EHLO RCPT DATA RSET MAIL VRFY EXPN QUIT HELP\r\n";
}
}
return 0;
}
sub VRFY_smtp {
my ($args) = @_;
my ($username, $address) = split(/ /, $args, 2);
logmsg "VRFY_smtp got $args\n";
if($username eq "") {
sendcontrol "501 Unrecognized parameter\r\n";
}
else {
my $smtputf8 = grep /^SMTPUTF8$/, @capabilities;
# Validate the username (only a valid local or external username is
# allowed, such as user or [email protected])
if ((!$smtputf8 && $username =~
/^([a-zA-Z0-9._%+-]+)(\@(([a-zA-Z0-9-]+)\.)+([a-zA-Z]{2,4}))?$/) ||
($smtputf8 && $username =~
/^([a-zA-Z0-9\x{80}-\x{ff}._%+-]+)(\@(([a-zA-Z0-9\x{80}-\x{ff}-]+)\.)+([a-zA-Z]{2,4}))?$/)) {
my @data = getreplydata($smtp_client);
if(!@data) {
if ($username !~
/^([a-zA-Z0-9._%+-]+)\@(([a-zA-Z0-9-]+)\.)+([a-zA-Z]{2,4})$/) {
push @data, "250 <$username\@example.com>\r\n"
}
else {
push @data, "250 <$username>\r\n"
}
}
for my $d (@data) {
sendcontrol $d;
}
}
else {
sendcontrol "501 Invalid address\r\n";
}
}
return 0;
}
sub EXPN_smtp {
my ($list_name) = @_;
logmsg "EXPN_smtp got $list_name\n";
if(!$list_name) {
sendcontrol "501 Unrecognized parameter\r\n";
}
else {
my @data = getreplydata($smtp_client);
for my $d (@data) {
sendcontrol $d;
}
}
return 0;
}
sub QUIT_smtp {
sendcontrol "221 curl $smtp_type server signing off\r\n";
return 0;
}
# What was deleted by IMAP STORE / POP3 DELE commands
my @deleted;
################
################ IMAP commands
################
# global to allow the command functions to read it
my $cmdid;
# what was picked by SELECT
my $selected;
# Any IMAP parameter can come in escaped and in double quotes.
# This function is dumb (so far) and just removes the quotes if present.
sub fix_imap_params {
foreach (@_) {
$_ = $1 if /^"(.*)"$/;
}
}
sub CAPABILITY_imap {
if((!@capabilities) && (!@auth_mechs)) {
sendcontrol "$cmdid BAD Command\r\n";
}
else {
my $data;
# Calculate the CAPABILITY response
$data = "* CAPABILITY IMAP4";
for my $c (@capabilities) {
$data .= " $c";
}
for my $am (@auth_mechs) {
$data .= " AUTH=$am";
}
$data .= " pingpong test server\r\n";
# Send the CAPABILITY response
sendcontrol $data;
sendcontrol "$cmdid OK CAPABILITY completed\r\n";
}
return 0;
}
sub LOGIN_imap {
my ($args) = @_;
my ($user, $password) = split(/ /, $args, 2);
fix_imap_params($user, $password);
logmsg "LOGIN_imap got $args\n";
if ($user eq "") {
sendcontrol "$cmdid BAD Command Argument\r\n";
}
else {
sendcontrol "$cmdid OK LOGIN completed\r\n";
}
return 0;
}
sub SELECT_imap {
my ($mailbox) = @_;
fix_imap_params($mailbox);
logmsg "SELECT_imap got test $mailbox\n";
if($mailbox eq "") {
sendcontrol "$cmdid BAD Command Argument\r\n";
}
else {
# Example from RFC 3501, 6.3.1. SELECT Command
sendcontrol "* 172 EXISTS\r\n";
sendcontrol "* 1 RECENT\r\n";
sendcontrol "* OK [UNSEEN 12] Message 12 is first unseen\r\n";
sendcontrol "* OK [UIDVALIDITY 3857529045] UIDs valid\r\n";
sendcontrol "* OK [UIDNEXT 4392] Predicted next UID\r\n";
sendcontrol "* FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)\r\n";
sendcontrol "* OK [PERMANENTFLAGS (\\Deleted \\Seen \\*)] Limited\r\n";
sendcontrol "$cmdid OK [READ-WRITE] SELECT completed\r\n";
$selected = $mailbox;
}
return 0;
}
sub FETCH_imap {
my ($args) = @_;
my ($uid, $how) = split(/ /, $args, 2);
fix_imap_params($uid, $how);
logmsg "FETCH_imap got $args\n";
if ($selected eq "") {
sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
}
else {
my @data;
my $size;
if($selected eq "verifiedserver") {
# this is the secret command that verifies that this actually is
# the curl test server
my $response = "WE ROOLZ: $$\r\n";
if($verbose) {
print STDERR "FTPD: We returned proof we are the test server\n";
}
$data[0] = $response;
logmsg "return proof we are we\n";
}
else {
# send mail content
logmsg "retrieve a mail\n";
@data = getreplydata($selected);
}
for (@data) {
$size += length($_);
}
sendcontrol "* $uid FETCH ($how {$size}\r\n";
for my $d (@data) {
sendcontrol $d;
}
# Set the custom extra header content with POSTFETCH
sendcontrol "$postfetch)\r\n";
sendcontrol "$cmdid OK FETCH completed\r\n";
}
return 0;
}
sub APPEND_imap {
my ($args) = @_;
logmsg "APPEND_imap got $args\r\n";
$args =~ /^([^ ]+) [^{]*\{(\d+)\}$/;
my ($mailbox, $size) = ($1, $2);
fix_imap_params($mailbox);
if($mailbox eq "") {
sendcontrol "$cmdid BAD Command Argument\r\n";
}
else {
sendcontrol "+ Ready for literal data\r\n";
my $testno = $mailbox;
my $filename = "log/upload.$testno";
logmsg "Store test number $testno in $filename\n";
open(FILE, ">$filename") ||
return 0; # failed to open output
my $received = 0;
my $line;
while(5 == (sysread \*SFREAD, $line, 5)) {
if($line eq "DATA\n") {
sysread \*SFREAD, $line, 5;
my $chunksize = 0;
if($line =~ /^([0-9a-fA-F]{4})\n/) {
$chunksize = hex($1);
}
read_mainsockf(\$line, $chunksize);
my $left = $size - $received;
my $datasize = ($left > $chunksize) ? $chunksize : $left;
if($datasize > 0) {
logmsg "> Appending $datasize bytes to file\n";
print FILE substr($line, 0, $datasize) if(!$nosave);
$line = substr($line, $datasize);
$received += $datasize;
if($received == $size) {
logmsg "Received all data, waiting for final CRLF.\n";
}
}
if($received == $size && $line eq "\r\n") {
last;
}
}
elsif($line eq "DISC\n") {
logmsg "Unexpected disconnect!\n";
last;
}
else {
logmsg "No support for: $line";
last;
}
}
if($nosave) {
print FILE "$size bytes would've been stored here\n";
}
close(FILE);
logmsg "received $size bytes upload\n";
sendcontrol "$cmdid OK APPEND completed\r\n";
}
return 0;
}
sub STORE_imap {
my ($args) = @_;
my ($uid, $what, $value) = split(/ /, $args, 3);
fix_imap_params($uid);
logmsg "STORE_imap got $args\n";
if ($selected eq "") {
sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
}
elsif (($uid eq "") || ($what ne "+Flags") || ($value eq "")) {
sendcontrol "$cmdid BAD Command Argument\r\n";
}
else {
if($value eq "\\Deleted") {
push(@deleted, $uid);
}
sendcontrol "* $uid FETCH (FLAGS (\\Seen $value))\r\n";
sendcontrol "$cmdid OK STORE completed\r\n";
}
return 0;
}
sub LIST_imap {
my ($args) = @_;
my ($reference, $mailbox) = split(/ /, $args, 2);
fix_imap_params($reference, $mailbox);
logmsg "LIST_imap got $args\n";
if ($reference eq "") {
sendcontrol "$cmdid BAD Command Argument\r\n";
}
elsif ($reference eq "verifiedserver") {
# this is the secret command that verifies that this actually is
# the curl test server
sendcontrol "* LIST () \"/\" \"WE ROOLZ: $$\"\r\n";
sendcontrol "$cmdid OK LIST Completed\r\n";
if($verbose) {
print STDERR "FTPD: We returned proof we are the test server\n";
}
logmsg "return proof we are we\n";
}
else {
my @data = getreplydata($reference);
for my $d (@data) {
sendcontrol $d;
}
sendcontrol "$cmdid OK LIST Completed\r\n";
}
return 0;
}
sub LSUB_imap {
my ($args) = @_;
my ($reference, $mailbox) = split(/ /, $args, 2);
fix_imap_params($reference, $mailbox);
logmsg "LSUB_imap got $args\n";
if ($reference eq "") {
sendcontrol "$cmdid BAD Command Argument\r\n";
}
else {
my @data = getreplydata($reference);
for my $d (@data) {
sendcontrol $d;
}
sendcontrol "$cmdid OK LSUB Completed\r\n";
}
return 0;
}
sub EXAMINE_imap {
my ($mailbox) = @_;
fix_imap_params($mailbox);
logmsg "EXAMINE_imap got $mailbox\n";
if ($mailbox eq "") {
sendcontrol "$cmdid BAD Command Argument\r\n";
}
else {
my @data = getreplydata($mailbox);
for my $d (@data) {
sendcontrol $d;
}
sendcontrol "$cmdid OK [READ-ONLY] EXAMINE completed\r\n";
}
return 0;
}
sub STATUS_imap {
my ($args) = @_;
my ($mailbox, $what) = split(/ /, $args, 2);
fix_imap_params($mailbox);
logmsg "STATUS_imap got $args\n";
if ($mailbox eq "") {
sendcontrol "$cmdid BAD Command Argument\r\n";
}
else {
my @data = getreplydata($mailbox);
for my $d (@data) {
sendcontrol $d;
}
sendcontrol "$cmdid OK STATUS completed\r\n";
}
return 0;
}
sub SEARCH_imap {
my ($what) = @_;
fix_imap_params($what);
logmsg "SEARCH_imap got $what\n";
if ($selected eq "") {
sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
}
elsif ($what eq "") {
sendcontrol "$cmdid BAD Command Argument\r\n";
}
else {
my @data = getreplydata($selected);
for my $d (@data) {
sendcontrol $d;
}
sendcontrol "$cmdid OK SEARCH completed\r\n";
}
return 0;
}
sub CREATE_imap {
my ($args) = @_;
fix_imap_params($args);
logmsg "CREATE_imap got $args\n";
if ($args eq "") {
sendcontrol "$cmdid BAD Command Argument\r\n";
}
else {
sendcontrol "$cmdid OK CREATE completed\r\n";
}
return 0;
}
sub DELETE_imap {
my ($args) = @_;
fix_imap_params($args);
logmsg "DELETE_imap got $args\n";
if ($args eq "") {
sendcontrol "$cmdid BAD Command Argument\r\n";
}
else {
sendcontrol "$cmdid OK DELETE completed\r\n";
}
return 0;
}
sub RENAME_imap {
my ($args) = @_;
my ($from_mailbox, $to_mailbox) = split(/ /, $args, 2);
fix_imap_params($from_mailbox, $to_mailbox);
logmsg "RENAME_imap got $args\n";
if (($from_mailbox eq "") || ($to_mailbox eq "")) {
sendcontrol "$cmdid BAD Command Argument\r\n";
}
else {
sendcontrol "$cmdid OK RENAME completed\r\n";
}
return 0;
}
sub CHECK_imap {
if ($selected eq "") {
sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
}
else {
sendcontrol "$cmdid OK CHECK completed\r\n";
}
return 0;
}
sub CLOSE_imap {
if ($selected eq "") {
sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
}
elsif (!@deleted) {
sendcontrol "$cmdid BAD Command Argument\r\n";
}
else {
sendcontrol "$cmdid OK CLOSE completed\r\n";
@deleted = ();
}
return 0;
}
sub EXPUNGE_imap {
if ($selected eq "") {
sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
}
else {
if (!@deleted) {
# Report the number of existing messages as per the SELECT
# command
sendcontrol "* 172 EXISTS\r\n";
}
else {
# Report the message UIDs being deleted
for my $d (@deleted) {
sendcontrol "* $d EXPUNGE\r\n";
}
@deleted = ();
}
sendcontrol "$cmdid OK EXPUNGE completed\r\n";
}
return 0;
}
sub COPY_imap {
my ($args) = @_;
my ($uid, $mailbox) = split(/ /, $args, 2);
fix_imap_params($uid, $mailbox);
logmsg "COPY_imap got $args\n";
if (($uid eq "") || ($mailbox eq "")) {
sendcontrol "$cmdid BAD Command Argument\r\n";
}
else {
sendcontrol "$cmdid OK COPY completed\r\n";
}
return 0;
}
sub IDLE_imap {
logmsg "IDLE received\n";
sendcontrol "+ entering idle mode\r\n";
return 0;
}
sub UID_imap {
my ($args) = @_;
my ($command) = split(/ /, $args, 1);
fix_imap_params($command);
logmsg "UID_imap got $args\n";
if ($selected eq "") {
sendcontrol "$cmdid BAD Command received in Invalid state\r\n";
}
elsif (substr($command, 0, 5) eq "FETCH"){
my $func = $commandfunc{"FETCH"};
if($func) {
&$func($args, $command);
}
}
elsif (($command ne "COPY") &&
($command ne "STORE") && ($command ne "SEARCH")) {
sendcontrol "$cmdid BAD Command Argument\r\n";
}
else {
my @data = getreplydata($selected);
for my $d (@data) {
sendcontrol $d;
}
sendcontrol "$cmdid OK $command completed\r\n";
}
return 0;
}
sub NOOP_imap {
my ($args) = @_;
my @data = (
"* 22 EXPUNGE\r\n",
"* 23 EXISTS\r\n",
"* 3 RECENT\r\n",
"* 14 FETCH (FLAGS (\\Seen \\Deleted))\r\n",
);
if ($args) {
sendcontrol "$cmdid BAD Command Argument\r\n";
}
else {
for my $d (@data) {
sendcontrol $d;
}
sendcontrol "$cmdid OK NOOP completed\r\n";
}
return 0;
}
sub LOGOUT_imap {
sendcontrol "* BYE curl IMAP server signing off\r\n";
sendcontrol "$cmdid OK LOGOUT completed\r\n";
return 0;
}
################
################ POP3 commands
################
# Who is attempting to log in
my $username;
sub CAPA_pop3 {
my @list = ();
my $mechs;
# Calculate the capability list based on the specified capabilities
# (except APOP) and any authentication mechanisms
for my $c (@capabilities) {
push @list, "$c\r\n" unless $c eq "APOP";
}
for my $am (@auth_mechs) {
if(!$mechs) {
$mechs = "$am";
}
else {
$mechs .= " $am";
}
}
if($mechs) {
push @list, "SASL $mechs\r\n";
}
if(!@list) {
sendcontrol "-ERR Unrecognized command\r\n";
}
else {
my @data = ();
# Calculate the CAPA response
push @data, "+OK List of capabilities follows\r\n";
for my $l (@list) {
push @data, "$l\r\n";
}
push @data, "IMPLEMENTATION POP3 pingpong test server\r\n";
# Send the CAPA response
for my $d (@data) {
sendcontrol $d;
}
# End with the magic 3-byte end of listing marker
sendcontrol ".\r\n";
}
return 0;
}
sub APOP_pop3 {
my ($args) = @_;
my ($user, $secret) = split(/ /, $args, 2);
if (!grep /^APOP$/, @capabilities) {
sendcontrol "-ERR Unrecognized command\r\n";
}
elsif (($user eq "") || ($secret eq "")) {
sendcontrol "-ERR Protocol error\r\n";
}
else {
my $digest = Digest::MD5::md5_hex($POP3_TIMESTAMP, $TEXT_PASSWORD);
if ($secret ne $digest) {
sendcontrol "-ERR Login failure\r\n";
}
else {
sendcontrol "+OK Login successful\r\n";
}
}
return 0;
}
sub AUTH_pop3 {
if(!@auth_mechs) {
sendcontrol "-ERR Unrecognized command\r\n";
}
else {
my @data = ();
# Calculate the AUTH response
push @data, "+OK List of supported mechanisms follows\r\n";
for my $am (@auth_mechs) {
push @data, "$am\r\n";
}
# Send the AUTH response
for my $d (@data) {
sendcontrol $d;
}
# End with the magic 3-byte end of listing marker
sendcontrol ".\r\n";
}
return 0;
}
sub USER_pop3 {
my ($user) = @_;
logmsg "USER_pop3 got $user\n";
if (!$user) {
sendcontrol "-ERR Protocol error\r\n";
}
else {
$username = $user;
sendcontrol "+OK\r\n";
}
return 0;
}
sub PASS_pop3 {
my ($password) = @_;
logmsg "PASS_pop3 got $password\n";
sendcontrol "+OK Login successful\r\n";
return 0;
}
sub RETR_pop3 {
my ($msgid) = @_;
my @data;
if($msgid =~ /^verifiedserver$/) {
# this is the secret command that verifies that this actually is
# the curl test server
my $response = "WE ROOLZ: $$\r\n";
if($verbose) {
print STDERR "FTPD: We returned proof we are the test server\n";
}
$data[0] = $response;
logmsg "return proof we are we\n";
}
else {
# send mail content
logmsg "retrieve a mail\n";
@data = getreplydata($msgid);
}
sendcontrol "+OK Mail transfer starts\r\n";
for my $d (@data) {
sendcontrol $d;
}
# end with the magic 3-byte end of mail marker, assumes that the
# mail body ends with a CRLF!
sendcontrol ".\r\n";
return 0;
}
sub LIST_pop3 {
# This is a built-in fake-message list
my @data = (
"1 100\r\n",
"2 4294967400\r\n", # > 4 GB
"3 200\r\n",
);
logmsg "retrieve a message list\n";
sendcontrol "+OK Listing starts\r\n";
for my $d (@data) {
sendcontrol $d;
}
# End with the magic 3-byte end of listing marker
sendcontrol ".\r\n";
return 0;
}
sub DELE_pop3 {
my ($msgid) = @_;
logmsg "DELE_pop3 got $msgid\n";
if (!$msgid) {
sendcontrol "-ERR Protocol error\r\n";
}
else {
push (@deleted, $msgid);
sendcontrol "+OK\r\n";
}
return 0;
}
sub STAT_pop3 {
my ($args) = @_;
if ($args) {
sendcontrol "-ERR Protocol error\r\n";
}
else {
# Send statistics for the built-in fake message list as
# detailed in the LIST_pop3 function above
sendcontrol "+OK 3 4294967800\r\n";
}
return 0;
}
sub NOOP_pop3 {
my ($args) = @_;
if ($args) {
sendcontrol "-ERR Protocol error\r\n";
}
else {
sendcontrol "+OK\r\n";
}
return 0;
}
sub UIDL_pop3 {
# This is a built-in fake-message UID list
my @data = (
"1 1\r\n",
"2 2\r\n",
"3 4\r\n", # Note that UID 3 is a simulated "deleted" message
);
if (!grep /^UIDL$/, @capabilities) {
sendcontrol "-ERR Unrecognized command\r\n";
}
else {
logmsg "retrieve a message UID list\n";
sendcontrol "+OK Listing starts\r\n";
for my $d (@data) {
sendcontrol $d;
}
# End with the magic 3-byte end of listing marker
sendcontrol ".\r\n";
}
return 0;
}
sub TOP_pop3 {
my ($args) = @_;
my ($msgid, $lines) = split(/ /, $args, 2);
logmsg "TOP_pop3 got $args\n";
if (!grep /^TOP$/, @capabilities) {
sendcontrol "-ERR Unrecognized command\r\n";
}
elsif (($msgid eq "") || ($lines eq "")) {
sendcontrol "-ERR Protocol error\r\n";
}
else {
if ($lines == "0") {
logmsg "retrieve header of mail\n";
}
else {
logmsg "retrieve top $lines lines of mail\n";
}
my @data = getreplydata($msgid);
sendcontrol "+OK Mail transfer starts\r\n";
# Send mail content
for my $d (@data) {
sendcontrol $d;
}
# End with the magic 3-byte end of mail marker, assumes that the
# mail body ends with a CRLF!
sendcontrol ".\r\n";
}
return 0;
}
sub RSET_pop3 {
my ($args) = @_;
if ($args) {
sendcontrol "-ERR Protocol error\r\n";
}
else {
if (@deleted) {
logmsg "resetting @deleted message(s)\n";
@deleted = ();
}
sendcontrol "+OK\r\n";
}
return 0;
}
sub QUIT_pop3 {
if(@deleted) {
logmsg "deleting @deleted message(s)\n";
@deleted = ();
}
sendcontrol "+OK curl POP3 server signing off\r\n";
return 0;
}
################
################ FTP commands
################
my $rest=0;
sub REST_ftp {
$rest = $_[0];
logmsg "Set REST position to $rest\n"
}
sub switch_directory_goto {
my $target_dir = $_;
if(!$ftptargetdir) {
$ftptargetdir = "/";
}
if($target_dir eq "") {
$ftptargetdir = "/";
}
elsif($target_dir eq "..") {
if($ftptargetdir eq "/") {
$ftptargetdir = "/";
}
else {
$ftptargetdir =~ s/[[:alnum:]]+\/$//;
}
}
else {
$ftptargetdir .= $target_dir . "/";
}
}
sub switch_directory {
my $target_dir = $_[0];
if($target_dir =~ /^test-(\d+)/) {
$cwd_testno = $1;
}
elsif($target_dir eq "/") {
$ftptargetdir = "/";
}
else {
my @dirs = split("/", $target_dir);
for(@dirs) {
switch_directory_goto($_);
}
}
}
sub CWD_ftp {
my ($folder, $fullcommand) = $_[0];
switch_directory($folder);
if($ftptargetdir =~ /^\/fully_simulated/) {
$ftplistparserstate = "enabled";
}
else {
undef $ftplistparserstate;
}
}
sub PWD_ftp {
my $mydir;
$mydir = $ftptargetdir ? $ftptargetdir : "/";
if($mydir ne "/") {
$mydir =~ s/\/$//;
}
sendcontrol "257 \"$mydir\" is current directory\r\n";
}
sub LIST_ftp {
# print "150 ASCII data connection for /bin/ls (193.15.23.1,59196) (0 bytes)\r\n";
# this is a built-in fake-dir ;-)
my @ftpdir=("total 20\r\n",
"drwxr-xr-x 8 98 98 512 Oct 22 13:06 .\r\n",
"drwxr-xr-x 8 98 98 512 Oct 22 13:06 ..\r\n",
"drwxr-xr-x 2 98 98 512 May 2 1996 .NeXT\r\n",
"-r--r--r-- 1 0 1 35 Jul 16 1996 README\r\n",
"lrwxrwxrwx 1 0 1 7 Dec 9 1999 bin -> usr/bin\r\n",
"dr-xr-xr-x 2 0 1 512 Oct 1 1997 dev\r\n",
"drwxrwxrwx 2 98 98 512 May 29 16:04 download.html\r\n",
"dr-xr-xr-x 2 0 1 512 Nov 30 1995 etc\r\n",
"drwxrwxrwx 2 98 1 512 Oct 30 14:33 pub\r\n",
"dr-xr-xr-x 5 0 1 512 Oct 1 1997 usr\r\n");
if($datasockf_conn eq 'no') {
if($nodataconn425) {
sendcontrol "150 Opening data connection\r\n";
sendcontrol "425 Can't open data connection\r\n";
}
elsif($nodataconn421) {
sendcontrol "150 Opening data connection\r\n";
sendcontrol "421 Connection timed out\r\n";
}
elsif($nodataconn150) {
sendcontrol "150 Opening data connection\r\n";
# client shall timeout
}
else {
# client shall timeout
}
return 0;
}
if($ftplistparserstate) {
@ftpdir = ftp_contentlist($ftptargetdir);
}
logmsg "pass LIST data on data connection\n";
if($cwd_testno) {
loadtest("$logdir/test$cwd_testno");
my @data = getpart("reply", "data");
for(@data) {
my $send = $_;
# convert all \n to \r\n for ASCII transfer
$send =~ s/\r\n/\n/g;
$send =~ s/\n/\r\n/g;
logmsg "send $send as data\n";
senddata $send;
}
$cwd_testno = 0; # forget it again
}
else {
# old hard-coded style
for(@ftpdir) {
senddata $_;
}
}
close_dataconn(0);
sendcontrol "226 ASCII transfer complete\r\n";
return 0;
}
sub NLST_ftp {
my @ftpdir=("file", "with space", "fake", "..", " ..", "funny", "README");
if($datasockf_conn eq 'no') {
if($nodataconn425) {
sendcontrol "150 Opening data connection\r\n";
sendcontrol "425 Can't open data connection\r\n";
}
elsif($nodataconn421) {
sendcontrol "150 Opening data connection\r\n";
sendcontrol "421 Connection timed out\r\n";
}
elsif($nodataconn150) {
sendcontrol "150 Opening data connection\r\n";
# client shall timeout
}
else {
# client shall timeout
}
return 0;
}
logmsg "pass NLST data on data connection\n";
for(@ftpdir) {
senddata "$_\r\n";
}
close_dataconn(0);
sendcontrol "226 ASCII transfer complete\r\n";
return 0;
}
sub MDTM_ftp {
my $testno = $_[0];
my $testpart = "";
if ($testno > 10000) {
$testpart = $testno % 10000;
$testno = int($testno / 10000);
}
loadtest("$logdir/test$testno");
my @data = getpart("reply", "mdtm");
my $reply = $data[0];
chomp $reply if($reply);
if($reply && ($reply =~ /^[+-]?\d+$/) && ($reply < 0)) {
sendcontrol "550 $testno: no such file.\r\n";
}
elsif($reply) {
sendcontrol "$reply\r\n";
}
else {
sendcontrol "500 MDTM: no such command.\r\n";
}
return 0;
}
sub SIZE_ftp {
my $testno = $_[0];
if($ftplistparserstate) {
my $size = wildcard_filesize($ftptargetdir, $testno);
if($size == -1) {
sendcontrol "550 $testno: No such file or directory.\r\n";
}
else {
sendcontrol "213 $size\r\n";
}
return 0;
}
if($testno =~ /^verifiedserver$/) {
my $response = "WE ROOLZ: $$\r\n";
my $size = length($response);
sendcontrol "213 $size\r\n";
return 0;
}
if($testno =~ /(\d+)\/?$/) {
$testno = $1;
}
else {
print STDERR "SIZE_ftp: invalid test number: $testno\n";
return 1;
}
my $testpart = "";
if($testno > 10000) {
$testpart = $testno % 10000;
$testno = int($testno / 10000);
}
loadtest("$logdir/test$testno");
my @data = getpart("reply", "size");
my $size = $data[0];
if($size) {
if($size > -1) {
sendcontrol "213 $size\r\n";
}
else {
sendcontrol "550 $testno: No such file or directory.\r\n";
}
}
else {
$size=0;
@data = getpart("reply", "data$testpart");
for(@data) {
$size += length($_);
}
if($size) {
sendcontrol "213 $size\r\n";
}
else {
sendcontrol "550 $testno: No such file or directory.\r\n";
}
}
return 0;
}
sub RETR_ftp {
my ($testno) = @_;
if($datasockf_conn eq 'no') {
if($nodataconn425) {
sendcontrol "150 Opening data connection\r\n";
sendcontrol "425 Can't open data connection\r\n";
}
elsif($nodataconn421) {
sendcontrol "150 Opening data connection\r\n";
sendcontrol "421 Connection timed out\r\n";
}
elsif($nodataconn150) {
sendcontrol "150 Opening data connection\r\n";
# client shall timeout
}
else {
# client shall timeout
}
return 0;
}
if($ftplistparserstate) {
my @content = wildcard_getfile($ftptargetdir, $testno);
if($content[0] == -1) {
#file not found
}
else {
my $size = length $content[1];
sendcontrol "150 Binary data connection for $testno ($size bytes).\r\n",
senddata $content[1];
close_dataconn(0);
sendcontrol "226 File transfer complete\r\n";
}
return 0;
}
if($testno =~ /^verifiedserver$/) {
# this is the secret command that verifies that this actually is
# the curl test server
my $response = "WE ROOLZ: $$\r\n";
my $len = length($response);
sendcontrol "150 Binary junk ($len bytes).\r\n";
senddata "WE ROOLZ: $$\r\n";
close_dataconn(0);
sendcontrol "226 File transfer complete\r\n";
if($verbose) {
print STDERR "FTPD: We returned proof we are the test server\n";
}
return 0;
}
$testno =~ s/^([^0-9]*)//;
my $testpart = "";
if ($testno > 10000) {
$testpart = $testno % 10000;
$testno = int($testno / 10000);
}
loadtest("$logdir/test$testno");
my @data = getpart("reply", "data$testpart");
my $size=0;
for(@data) {
$size += length($_);
}
my %hash = getpartattr("reply", "data$testpart");
if($size || $hash{'sendzero'}) {
if($rest) {
# move read pointer forward
$size -= $rest;
logmsg "REST $rest was removed from size, makes $size left\n";
$rest = 0; # reset REST offset again
}
if($retrweirdo) {
sendcontrol "150 Binary data connection for $testno () ($size bytes).\r\n",
"226 File transfer complete\r\n";
for(@data) {
my $send = $_;
senddata $send;
}
close_dataconn(0);
$retrweirdo=0; # switch off the weirdo again!
}
else {
my $sz = "($size bytes)";
if($retrnosize) {
$sz = "size?";
}
sendcontrol "150 Binary data connection for $testno () $sz.\r\n";
for(@data) {
my $send = $_;
senddata $send;
}
close_dataconn(0);
sendcontrol "226 File transfer complete\r\n";
}
}
else {
sendcontrol "550 $testno: No such file or directory.\r\n";
}
return 0;
}
sub STOR_ftp {
my $testno=$_[0];
my $filename = "log/upload.$testno";
if($datasockf_conn eq 'no') {
if($nodataconn425) {
sendcontrol "150 Opening data connection\r\n";
sendcontrol "425 Can't open data connection\r\n";
}
elsif($nodataconn421) {
sendcontrol "150 Opening data connection\r\n";
sendcontrol "421 Connection timed out\r\n";
}
elsif($nodataconn150) {
sendcontrol "150 Opening data connection\r\n";
# client shall timeout
}
else {
# client shall timeout
}
return 0;
}
logmsg "STOR test number $testno in $filename\n";
sendcontrol "125 Gimme gimme gimme!\r\n";
open(FILE, ">$filename") ||
return 0; # failed to open output
my $line;
my $ulsize=0;
my $disc=0;
while (5 == (sysread DREAD, $line, 5)) {
if($line eq "DATA\n") {
my $i;
sysread DREAD, $i, 5;
my $size = 0;
if($i =~ /^([0-9a-fA-F]{4})\n/) {
$size = hex($1);
}
read_datasockf(\$line, $size);
#print STDERR " GOT: $size bytes\n";
$ulsize += $size;
print FILE $line if(!$nosave);
logmsg "> Appending $size bytes to file\n";
}
elsif($line eq "DISC\n") {
# disconnect!
$disc=1;
last;
}
else {
logmsg "No support for: $line";
last;
}
if($storeresp) {
# abort early
last;
}
}
if($nosave) {
print FILE "$ulsize bytes would've been stored here\n";
}
close(FILE);
close_dataconn($disc);
logmsg "received $ulsize bytes upload\n";
if($storeresp) {
sendcontrol "$storeresp\r\n";
}
else {
sendcontrol "226 File transfer complete\r\n";
}
return 0;
}
sub PASV_ftp {
my ($arg, $cmd)=@_;
my $pasvport;
my $bindonly = ($nodataconn) ? '--bindonly' : '';
# kill previous data connection sockfilt when alive
if($datasockf_runs eq 'yes') {
killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
logmsg "DATA sockfilt for $datasockf_mode data channel killed\n";
}
datasockf_state('STOPPED');
logmsg "====> Passive DATA channel requested by client\n";
logmsg "DATA sockfilt for passive data channel starting...\n";
# We fire up a new sockfilt to do the data transfer for us.
my $datasockfcmd = "./server/sockfilt".exe_ext('SRV')." " .
"--ipv$ipvnum $bindonly --port 0 " .
"--pidfile \"$datasockf_pidfile\" " .
"--logfile \"$datasockf_logfile\"";
$slavepid = open2(\*DREAD, \*DWRITE, $datasockfcmd);
if($nodataconn) {
datasockf_state('PASSIVE_NODATACONN');
}
else {
datasockf_state('PASSIVE');
}
print STDERR "$datasockfcmd\n" if($verbose);
print DWRITE "PING\n";
my $pong;
sysread_or_die(\*DREAD, \$pong, 5);
if($pong =~ /^FAIL/) {
logmsg "DATA sockfilt said: FAIL\n";
logmsg "DATA sockfilt for passive data channel failed\n";
logmsg "DATA sockfilt not running\n";
datasockf_state('STOPPED');
sendcontrol "500 no free ports!\r\n";
return;
}
elsif($pong !~ /^PONG/) {
logmsg "DATA sockfilt unexpected response: $pong\n";
logmsg "DATA sockfilt for passive data channel failed\n";
logmsg "DATA sockfilt killed now\n";
killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
logmsg "DATA sockfilt not running\n";
datasockf_state('STOPPED');
sendcontrol "500 no free ports!\r\n";
return;
}
logmsg "DATA sockfilt for passive data channel started (pid $slavepid)\n";
# Find out on what port we listen on or have bound
my $i;
print DWRITE "PORT\n";
# READ the response code
sysread_or_die(\*DREAD, \$i, 5);
# READ the response size
sysread_or_die(\*DREAD, \$i, 5);
my $size = 0;
if($i =~ /^([0-9a-fA-F]{4})\n/) {
$size = hex($1);
}
# READ the response data
read_datasockf(\$i, $size);
# The data is in the format
# IPvX/NNN
if($i =~ /IPv(\d)\/(\d+)/) {
# FIX: deal with IP protocol version
$pasvport = $2;
}
if(!$pasvport) {
logmsg "DATA sockfilt unknown listener port\n";
logmsg "DATA sockfilt for passive data channel failed\n";
logmsg "DATA sockfilt killed now\n";
killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
logmsg "DATA sockfilt not running\n";
datasockf_state('STOPPED');
sendcontrol "500 no free ports!\r\n";
return;
}
if($nodataconn) {
my $str = nodataconn_str();
logmsg "DATA sockfilt for passive data channel ($str) bound on port ".
"$pasvport\n";
}
else {
logmsg "DATA sockfilt for passive data channel listens on port ".
"$pasvport\n";
}
if($cmd ne "EPSV") {
# PASV reply
my $p=$listenaddr;
$p =~ s/\./,/g;
if($pasvbadip) {
$p="1,2,3,4";
}
sendcontrol sprintf("227 Entering Passive Mode ($p,%d,%d)\n",
int($pasvport/256), int($pasvport%256));
}
else {
# EPSV reply
sendcontrol sprintf("229 Entering Passive Mode (|||%d|)\n", $pasvport);
}
logmsg "Client has been notified that DATA conn ".
"will be accepted on port $pasvport\n";
if($nodataconn) {
my $str = nodataconn_str();
logmsg "====> Client fooled ($str)\n";
return;
}
eval {
local $SIG{ALRM} = sub { die "alarm\n" };
# assume swift operations unless explicitly slow
alarm ($datadelay?20:10);
# Wait for 'CNCT'
my $input;
# FIX: Monitor ctrl conn for disconnect
while(sysread(DREAD, $input, 5)) {
if($input !~ /^CNCT/) {
# we wait for a connected client
logmsg "Odd, we got $input from client\n";
next;
}
logmsg "Client connects to port $pasvport\n";
last;
}
alarm 0;
};
if ($@) {
# timed out
logmsg "$srvrname server timed out awaiting data connection ".
"on port $pasvport\n";
logmsg "accept failed or connection not even attempted\n";
logmsg "DATA sockfilt killed now\n";
killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
logmsg "DATA sockfilt not running\n";
datasockf_state('STOPPED');
return;
}
else {
logmsg "====> Client established passive DATA connection ".
"on port $pasvport\n";
}
return;
}
#
# Support both PORT and EPRT here.
#
sub PORT_ftp {
my ($arg, $cmd) = @_;
my $port;
my $addr;
# kill previous data connection sockfilt when alive
if($datasockf_runs eq 'yes') {
killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
logmsg "DATA sockfilt for $datasockf_mode data channel killed\n";
}
datasockf_state('STOPPED');
logmsg "====> Active DATA channel requested by client\n";
# We always ignore the given IP and use localhost.
if($cmd eq "PORT") {
if($arg !~ /(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)/) {
logmsg "DATA sockfilt for active data channel not started ".
"(bad PORT-line: $arg)\n";
sendcontrol "500 silly you, go away\r\n";
return;
}
$port = ($5<<8)+$6;
$addr = "$1.$2.$3.$4";
}
# EPRT |2|::1|49706|
elsif($cmd eq "EPRT") {
if($arg !~ /(\d+)\|([^\|]+)\|(\d+)/) {
logmsg "DATA sockfilt for active data channel not started ".
"(bad EPRT-line: $arg)\n";
sendcontrol "500 silly you, go away\r\n";
return;
}
sendcontrol "200 Thanks for dropping by. We contact you later\r\n";
$port = $3;
$addr = $2;
}
else {
logmsg "DATA sockfilt for active data channel not started ".
"(invalid command: $cmd)\n";
sendcontrol "500 we don't like $cmd now\r\n";
return;
}
if(!$port || $port > 65535) {
logmsg "DATA sockfilt for active data channel not started ".
"(illegal PORT number: $port)\n";
return;
}
if($nodataconn) {
my $str = nodataconn_str();
logmsg "DATA sockfilt for active data channel not started ($str)\n";
datasockf_state('ACTIVE_NODATACONN');
logmsg "====> Active DATA channel not established\n";
return;
}
logmsg "DATA sockfilt for active data channel starting...\n";
# We fire up a new sockfilt to do the data transfer for us.
my $datasockfcmd = "./server/sockfilt".exe_ext('SRV')." " .
"--ipv$ipvnum --connect $port --addr \"$addr\" " .
"--pidfile \"$datasockf_pidfile\" " .
"--logfile \"$datasockf_logfile\"";
$slavepid = open2(\*DREAD, \*DWRITE, $datasockfcmd);
datasockf_state('ACTIVE');
print STDERR "$datasockfcmd\n" if($verbose);
print DWRITE "PING\n";
my $pong;
sysread_or_die(\*DREAD, \$pong, 5);
if($pong =~ /^FAIL/) {
logmsg "DATA sockfilt said: FAIL\n";
logmsg "DATA sockfilt for active data channel failed\n";
logmsg "DATA sockfilt not running\n";
datasockf_state('STOPPED');
# client shall timeout awaiting connection from server
return;
}
elsif($pong !~ /^PONG/) {
logmsg "DATA sockfilt unexpected response: $pong\n";
logmsg "DATA sockfilt for active data channel failed\n";
logmsg "DATA sockfilt killed now\n";
killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
logmsg "DATA sockfilt not running\n";
datasockf_state('STOPPED');
# client shall timeout awaiting connection from server
return;
}
logmsg "DATA sockfilt for active data channel started (pid $slavepid)\n";
logmsg "====> Active DATA channel connected to client port $port\n";
return;
}
#**********************************************************************
# datasockf_state is used to change variables that keep state info
# relative to the FTP secondary or data sockfilt process as soon as
# one of the five possible stable states is reached. Variables that
# are modified by this sub may be checked independently but should
# not be changed except by calling this sub.
#
sub datasockf_state {
my $state = $_[0];
if($state eq 'STOPPED') {
# Data sockfilter initial state, not running,
# not connected and not used.
$datasockf_state = $state;
$datasockf_mode = 'none';
$datasockf_runs = 'no';
$datasockf_conn = 'no';
}
elsif($state eq 'PASSIVE') {
# Data sockfilter accepted connection from client.
$datasockf_state = $state;
$datasockf_mode = 'passive';
$datasockf_runs = 'yes';
$datasockf_conn = 'yes';
}
elsif($state eq 'ACTIVE') {
# Data sockfilter has connected to client.
$datasockf_state = $state;
$datasockf_mode = 'active';
$datasockf_runs = 'yes';
$datasockf_conn = 'yes';
}
elsif($state eq 'PASSIVE_NODATACONN') {
# Data sockfilter bound port without listening,
# client won't be able to establish data connection.
$datasockf_state = $state;
$datasockf_mode = 'passive';
$datasockf_runs = 'yes';
$datasockf_conn = 'no';
}
elsif($state eq 'ACTIVE_NODATACONN') {
# Data sockfilter does not even run,
# client awaits data connection from server in vain.
$datasockf_state = $state;
$datasockf_mode = 'active';
$datasockf_runs = 'no';
$datasockf_conn = 'no';
}
else {
die "Internal error. Unknown datasockf state: $state!";
}
}
#**********************************************************************
# nodataconn_str returns string of effective nodataconn command. Notice
# that $nodataconn may be set alone or in addition to a $nodataconnXXX.
#
sub nodataconn_str {
my $str;
# order matters
$str = 'NODATACONN' if($nodataconn);
$str = 'NODATACONN425' if($nodataconn425);
$str = 'NODATACONN421' if($nodataconn421);
$str = 'NODATACONN150' if($nodataconn150);
return "$str";
}
#**********************************************************************
# customize configures test server operation for each curl test, reading
# configuration commands/parameters from server commands file each time
# a new client control connection is established with the test server.
# On success returns 1, otherwise zero.
#
sub customize {
$ctrldelay = 0; # default is no throttling of the ctrl stream
$datadelay = 0; # default is no throttling of the data stream
$retrweirdo = 0; # default is no use of RETRWEIRDO
$retrnosize = 0; # default is no use of RETRNOSIZE
$pasvbadip = 0; # default is no use of PASVBADIP
$nosave = 0; # default is to actually save uploaded data to file
$nodataconn = 0; # default is to establish or accept data channel
$nodataconn425 = 0; # default is to not send 425 without data channel
$nodataconn421 = 0; # default is to not send 421 without data channel
$nodataconn150 = 0; # default is to not send 150 without data channel
$storeresp = ""; # send as ultimate STOR response
$postfetch = ""; # send as header after a FETCH response
@capabilities = (); # default is to not support capability commands
@auth_mechs = (); # default is to not support authentication commands
%fulltextreply = ();#
%commandreply = (); #
%customcount = (); #
%delayreply = (); #
open(CUSTOM, "<log/ftpserver.cmd") ||
return 1;
logmsg "FTPD: Getting commands from log/ftpserver.cmd\n";
while(<CUSTOM>) {
if($_ =~ /REPLY \"([A-Z]+ [A-Za-z0-9+-\/=\*. ]+)\" (.*)/) {
$fulltextreply{$1}=eval "qq{$2}";
logmsg "FTPD: set custom reply for $1\n";
}
elsif($_ =~ /REPLY(LF|) ([A-Za-z0-9+\/=\*]*) (.*)/) {
$commandreply{$2}=eval "qq{$3}";
if($1 ne "LF") {
$commandreply{$2}.="\r\n";
}
else {
$commandreply{$2}.="\n";
}
if($2 eq "") {
logmsg "FTPD: set custom reply for empty command\n";
}
else {
logmsg "FTPD: set custom reply for $2 command\n";
}
}
elsif($_ =~ /COUNT ([A-Z]+) (.*)/) {
# we blank the custom reply for this command when having
# been used this number of times
$customcount{$1}=$2;
logmsg "FTPD: blank custom reply for $1 command after $2 uses\n";
}
elsif($_ =~ /DELAY ([A-Z]+) (\d*)/) {
$delayreply{$1}=$2;
logmsg "FTPD: delay reply for $1 with $2 seconds\n";
}
elsif($_ =~ /POSTFETCH (.*)/) {
logmsg "FTPD: read POSTFETCH header data\n";
$postfetch = $1;
}
elsif($_ =~ /SLOWDOWN/) {
$ctrldelay=1;
$datadelay=1;
logmsg "FTPD: send response with 0.01 sec delay between each byte\n";
}
elsif($_ =~ /RETRWEIRDO/) {
logmsg "FTPD: instructed to use RETRWEIRDO\n";
$retrweirdo=1;
}
elsif($_ =~ /RETRNOSIZE/) {
logmsg "FTPD: instructed to use RETRNOSIZE\n";
$retrnosize=1;
}
elsif($_ =~ /PASVBADIP/) {
logmsg "FTPD: instructed to use PASVBADIP\n";
$pasvbadip=1;
}
elsif($_ =~ /NODATACONN425/) {
# applies to both active and passive FTP modes
logmsg "FTPD: instructed to use NODATACONN425\n";
$nodataconn425=1;
$nodataconn=1;
}
elsif($_ =~ /NODATACONN421/) {
# applies to both active and passive FTP modes
logmsg "FTPD: instructed to use NODATACONN421\n";
$nodataconn421=1;
$nodataconn=1;
}
elsif($_ =~ /NODATACONN150/) {
# applies to both active and passive FTP modes
logmsg "FTPD: instructed to use NODATACONN150\n";
$nodataconn150=1;
$nodataconn=1;
}
elsif($_ =~ /NODATACONN/) {
# applies to both active and passive FTP modes
logmsg "FTPD: instructed to use NODATACONN\n";
$nodataconn=1;
}
elsif($_ =~ /^STOR (.*)/) {
$storeresp=$1;
logmsg "FTPD: instructed to use respond to STOR with '$storeresp'\n";
}
elsif($_ =~ /CAPA (.*)/) {
logmsg "FTPD: instructed to support CAPABILITY command\n";
@capabilities = split(/ (?!(?:[^" ]|[^"] [^"])+")/, $1);
foreach (@capabilities) {
$_ = $1 if /^"(.*)"$/;
}
}
elsif($_ =~ /AUTH (.*)/) {
logmsg "FTPD: instructed to support AUTHENTICATION command\n";
@auth_mechs = split(/ /, $1);
}
elsif($_ =~ /NOSAVE/) {
# don't actually store the file we upload - to be used when
# uploading insanely huge amounts
$nosave = 1;
logmsg "FTPD: NOSAVE prevents saving of uploaded data\n";
}
elsif($_ =~ /^Testnum (\d+)/){
$testno = $1;
logmsg "FTPD: run test case number: $testno\n";
}
}
close(CUSTOM);
}
#----------------------------------------------------------------------
#----------------------------------------------------------------------
#--------------------------- END OF SUBS ----------------------------
#----------------------------------------------------------------------
#----------------------------------------------------------------------
#**********************************************************************
# Parse command line options
#
# Options:
#
# --verbose # verbose
# --srcdir # source directory
# --id # server instance number
# --proto # server protocol
# --pidfile # server pid file
# --portfile # server port file
# --logfile # server log file
# --ipv4 # server IP version 4
# --ipv6 # server IP version 6
# --port # server listener port
# --addr # server address for listener port binding
#
while(@ARGV) {
if($ARGV[0] eq '--verbose') {
$verbose = 1;
}
elsif($ARGV[0] eq '--srcdir') {
if($ARGV[1]) {
$srcdir = $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--id') {
if($ARGV[1] && ($ARGV[1] =~ /^(\d+)$/)) {
$idnum = $1 if($1 > 0);
shift @ARGV;
}
}
elsif($ARGV[0] eq '--proto') {
if($ARGV[1] && ($ARGV[1] =~ /^(ftp|imap|pop3|smtp)$/)) {
$proto = $1;
shift @ARGV;
}
else {
die "unsupported protocol $ARGV[1]";
}
}
elsif($ARGV[0] eq '--pidfile') {
if($ARGV[1]) {
$pidfile = $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--portfile') {
if($ARGV[1]) {
$portfile = $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--logfile') {
if($ARGV[1]) {
$logfile = $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--ipv4') {
$ipvnum = 4;
$listenaddr = '127.0.0.1' if($listenaddr eq '::1');
}
elsif($ARGV[0] eq '--ipv6') {
$ipvnum = 6;
$listenaddr = '::1' if($listenaddr eq '127.0.0.1');
}
elsif($ARGV[0] eq '--port') {
if($ARGV[1] =~ /^(\d+)$/) {
$port = $1;
shift @ARGV;
}
}
elsif($ARGV[0] eq '--addr') {
if($ARGV[1]) {
my $tmpstr = $ARGV[1];
if($tmpstr =~ /^(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)$/) {
$listenaddr = "$1.$2.$3.$4" if($ipvnum == 4);
}
elsif($ipvnum == 6) {
$listenaddr = $tmpstr;
$listenaddr =~ s/^\[(.*)\]$/$1/;
}
shift @ARGV;
}
}
else {
print STDERR "\nWarning: ftpserver.pl unknown parameter: $ARGV[0]\n";
}
shift @ARGV;
}
#***************************************************************************
# Initialize command line option dependent variables
#
if(!$srcdir) {
$srcdir = $ENV{'srcdir'} || '.';
}
if(!$pidfile) {
$pidfile = "$path/". server_pidfilename($proto, $ipvnum, $idnum);
}
if(!$logfile) {
$logfile = server_logfilename($logdir, $proto, $ipvnum, $idnum);
}
$mainsockf_pidfile = "$path/".
mainsockf_pidfilename($proto, $ipvnum, $idnum);
$mainsockf_logfile =
mainsockf_logfilename($logdir, $proto, $ipvnum, $idnum);
if($proto eq 'ftp') {
$datasockf_pidfile = "$path/".
datasockf_pidfilename($proto, $ipvnum, $idnum);
$datasockf_logfile =
datasockf_logfilename($logdir, $proto, $ipvnum, $idnum);
}
$srvrname = servername_str($proto, $ipvnum, $idnum);
$idstr = "$idnum" if($idnum > 1);
protocolsetup($proto);
$SIG{INT} = \&exit_signal_handler;
$SIG{TERM} = \&exit_signal_handler;
startsf();
# actual port
if($portfile && !$port) {
my $aport;
open(P, "<$portfile");
$aport = <P>;
close(P);
$port = 0 + $aport;
}
logmsg sprintf("%s server listens on port IPv${ipvnum}/${port}\n", uc($proto));
open(PID, ">$pidfile");
print PID $$."\n";
close(PID);
logmsg("logged pid $$ in $pidfile\n");
while(1) {
# kill previous data connection sockfilt when alive
if($datasockf_runs eq 'yes') {
killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data');
logmsg "DATA sockfilt for $datasockf_mode data channel killed now\n";
}
datasockf_state('STOPPED');
#
# We read 'sockfilt' commands.
#
my $input;
logmsg "Awaiting input\n";
sysread_or_die(\*SFREAD, \$input, 5);
if($input !~ /^CNCT/) {
# we wait for a connected client
logmsg "MAIN sockfilt said: $input";
next;
}
logmsg "====> Client connect\n";
set_advisor_read_lock($SERVERLOGS_LOCK);
$serverlogslocked = 1;
# flush data:
$| = 1;
&customize(); # read test control instructions
loadtest("$logdir/test$testno");
my $welcome = $commandreply{"welcome"};
if(!$welcome) {
$welcome = $displaytext{"welcome"};
}
else {
# clear it after use
$commandreply{"welcome"}="";
if($welcome !~ /\r\n\z/) {
$welcome .= "\r\n";
}
}
sendcontrol $welcome;
#remove global variables from last connection
if($ftplistparserstate) {
undef $ftplistparserstate;
}
if($ftptargetdir) {
$ftptargetdir = "";
}
if($verbose) {
print STDERR "OUT: $welcome";
}
my $full = "";
while(1) {
my $i;
# Now we expect to read DATA\n[hex size]\n[prot], where the [prot]
# part only is FTP lingo.
# COMMAND
sysread_or_die(\*SFREAD, \$i, 5);
if($i !~ /^DATA/) {
logmsg "MAIN sockfilt said $i";
if($i =~ /^DISC/) {
# disconnect
last;
}
next;
}
# SIZE of data
sysread_or_die(\*SFREAD, \$i, 5);
my $size = 0;
if($i =~ /^([0-9a-fA-F]{4})\n/) {
$size = hex($1);
}
# data
read_mainsockf(\$input, $size);
ftpmsg $input;
$full .= $input;
# Loop until command completion
next unless($full =~ /\r\n$/);
# Remove trailing CRLF.
$full =~ s/[\n\r]+$//;
my $FTPCMD;
my $FTPARG;
if($proto eq "imap") {
# IMAP is different with its identifier first on the command line
if(($full =~ /^([^ ]+) ([^ ]+) (.*)/) ||
($full =~ /^([^ ]+) ([^ ]+)/)) {
$cmdid=$1; # set the global variable
$FTPCMD=$2;
$FTPARG=$3;
}
# IMAP authentication cancellation
elsif($full =~ /^\*$/) {
# Command id has already been set
$FTPCMD="*";
$FTPARG="";
}
# IMAP long "commands" are base64 authentication data
elsif($full =~ /^[A-Z0-9+\/]*={0,2}$/i) {
# Command id has already been set
$FTPCMD=$full;
$FTPARG="";
}
else {
sendcontrol "$full BAD Command\r\n";
last;
}
}
elsif($full =~ /^([A-Z]{3,4})(\s(.*))?$/i) {
$FTPCMD=$1;
$FTPARG=$3;
}
elsif($proto eq "pop3") {
# POP3 authentication cancellation
if($full =~ /^\*$/) {
$FTPCMD="*";
$FTPARG="";
}
# POP3 long "commands" are base64 authentication data
elsif($full =~ /^[A-Z0-9+\/]*={0,2}$/i) {
$FTPCMD=$full;
$FTPARG="";
}
else {
sendcontrol "-ERR Unrecognized command\r\n";
last;
}
}
elsif($proto eq "smtp") {
# SMTP authentication cancellation
if($full =~ /^\*$/) {
$FTPCMD="*";
$FTPARG="";
}
# SMTP long "commands" are base64 authentication data
elsif($full =~ /^[A-Z0-9+\/]{0,512}={0,2}$/i) {
$FTPCMD=$full;
$FTPARG="";
}
else {
sendcontrol "500 Unrecognized command\r\n";
last;
}
}
else {
sendcontrol "500 Unrecognized command\r\n";
last;
}
logmsg "< \"$full\"\n";
if($verbose) {
print STDERR "IN: $full\n";
}
$full = "";
my $delay = $delayreply{$FTPCMD};
if($delay) {
# just go sleep this many seconds!
logmsg("Sleep for $delay seconds\n");
my $twentieths = $delay * 20;
while($twentieths--) {
portable_sleep(0.05) unless($got_exit_signal);
}
}
my $check = 1; # no response yet
# See if there is a custom reply for the full text
my $fulltext = $FTPARG ? $FTPCMD . " " . $FTPARG : $FTPCMD;
my $text = $fulltextreply{$fulltext};
if($text && ($text ne "")) {
sendcontrol "$text\r\n";
$check = 0;
}
else {
# See if there is a custom reply for the command
$text = $commandreply{$FTPCMD};
if($text && ($text ne "")) {
if($customcount{$FTPCMD} && (!--$customcount{$FTPCMD})) {
# used enough times so blank the custom command reply
$commandreply{$FTPCMD}="";
}
sendcontrol $text;
$check = 0;
}
else {
# See if there is any display text for the command
$text = $displaytext{$FTPCMD};
if($text && ($text ne "")) {
if($proto eq 'imap') {
sendcontrol "$cmdid $text\r\n";
}
else {
sendcontrol "$text\r\n";
}
$check = 0;
}
# only perform this if we're not faking a reply
my $func = $commandfunc{uc($FTPCMD)};
if($func) {
&$func($FTPARG, $FTPCMD);
$check = 0;
}
}
}
if($check) {
logmsg "$FTPCMD wasn't handled!\n";
if($proto eq 'pop3') {
sendcontrol "-ERR $FTPCMD is not dealt with!\r\n";
}
elsif($proto eq 'imap') {
sendcontrol "$cmdid BAD $FTPCMD is not dealt with!\r\n";
}
else {
sendcontrol "500 $FTPCMD is not dealt with!\r\n";
}
}
} # while(1)
logmsg "====> Client disconnected\n";
if($serverlogslocked) {
$serverlogslocked = 0;
clear_advisor_read_lock($SERVERLOGS_LOCK);
}
}
killsockfilters($proto, $ipvnum, $idnum, $verbose);
unlink($pidfile);
if($serverlogslocked) {
$serverlogslocked = 0;
clear_advisor_read_lock($SERVERLOGS_LOCK);
}
exit;
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/FILEFORMAT.md | # curl test suite file format
The curl test suite's file format is very simple and extensible, closely
resembling XML. All data for a single test case resides in a single ASCII
file. Labels mark the beginning and the end of all sections, and each label
must be written in its own line. Comments are either XML-style (enclosed with
`<!--` and `-->`) or shell script style (beginning with `#`) and must appear
on their own lines and not alongside actual test data. Most test data files
are syntactically valid XML, although a few files are not (lack of support for
character entities and the preservation of CR/LF characters at the end of
lines are the biggest differences).
Each test case source exists as a file matching the format
`tests/data/testNUM`, where NUM is the unique test number, and must begin with
a 'testcase' tag, which encompasses the remainder of the file.
# Preprocessing
When a test is to be executed, the source file is first preprocessed and
variables are substituted by the their respective contents and the output
version of the test file is stored as `log/testNUM`. That version is what will
be read and used by the test servers.
## Base64 Encoding
In the preprocess stage, a special instruction can be used to have runtests.pl
base64 encode a certain section and insert in the generated output file. This
is in particular good for test cases where the test tool is expected to pass
in base64 encoded content that might use dynamic information that is unique
for this particular test invocation, like the server port number.
To insert a base64 encoded string into the output, use this syntax:
%b64[ data to encode ]b64%
The data to encode can then use any of the existing variables mentioned below,
or even percent-encoded individual bytes. As an example, insert the HTTP
server's port number (in ASCII) followed by a space and the hexadecimal byte
9a:
%b64[%HTTPPORT %9a]b64%
## Hexadecimal decoding
In the preprocess stage, a special instruction can be used to have runtests.pl
generate a sequence of binary bytes.
To insert a sequence of bytes from a hex encoded string, use this syntax:
%hex[ %XX-encoded data to decode ]hex%
For example, to insert the binary octets 0, 1 and 255 into the test file:
%hex[ %00%01%FF ]hex%
## Repeat content
In the preprocess stage, a special instruction can be used to have runtests.pl
generate a repetetive sequence of bytes.
To insert a sequence of repeat bytes, use this syntax to make the `<string>`
get repeated `<number>` of times. The number has to be 1 or large and the
string may contain `%HH` hexadecimal codes:
%repeat[<number> x <string>]%
For example, to insert the word hello a 100 times:
%repeat[100 x hello]%
## Conditional lines
Lines in the test file can be made to appear conditionally on a specific
feature (see the "features" section below) being set or not set. If the
specific feature is present, the following lines will be output, otherwise it
outputs nothing, until a following else or endif clause. Like this:
%if brotli
Accept-Encoding
%endif
It can also check for the inversed condition, so if the feature us *not* set by
the use of an exclamation mark:
%if !brotli
Accept-Encoding: not-brotli
%endif
You can also make an "else" clause to get output for the opposite condition,
like:
%if brotli
Accept-Encoding: brotli
%else
Accept-Encoding: nothing
%endif
**Note** that there can be no nested conditions. You can only do one
conditional at a time and you can only check for a single feature in it.
# Variables
When the test is preprocessed, a range of "variables" in the test file will be
replaced by their content at that time.
Available substitute variables include:
- `%CLIENT6IP` - IPv6 address of the client running curl
- `%CLIENTIP` - IPv4 address of the client running curl
- `%CURL` - Path to the curl executable
- `%FILE_PWD` - Current directory, on windows prefixed with a slash
- `%FTP6PORT` - IPv6 port number of the FTP server
- `%FTPPORT` - Port number of the FTP server
- `%FTPSPORT` - Port number of the FTPS server
- `%FTPTIME2` - Timeout in seconds that should be just sufficient to receive a
response from the test FTP server
- `%FTPTIME3` - Even longer than %FTPTIME2
- `%GOPHER6PORT` - IPv6 port number of the Gopher server
- `%GOPHERPORT` - Port number of the Gopher server
- `%GOPHERSPORT` - Port number of the Gophers server
- `%HOST6IP` - IPv6 address of the host running this test
- `%HOSTIP` - IPv4 address of the host running this test
- `%HTTP6PORT` - IPv6 port number of the HTTP server
- `%HTTPPORT` - Port number of the HTTP server
- `%HTTP2PORT` - Port number of the HTTP/2 server
- `%HTTPSPORT` - Port number of the HTTPS server
- `%HTTPSPROXYPORT` - Port number of the HTTPS-proxy
- `%HTTPTLS6PORT` - IPv6 port number of the HTTP TLS server
- `%HTTPTLSPORT` - Port number of the HTTP TLS server
- `%HTTPUNIXPATH` - Path to the Unix socket of the HTTP server
- `%IMAP6PORT` - IPv6 port number of the IMAP server
- `%IMAPPORT` - Port number of the IMAP server
- `%MQTTPORT` - Port number of the MQTT server
- `%TELNETPORT` - Port number of the telnet server
- `%NOLISTENPORT` - Port number where no service is listening
- `%POP36PORT` - IPv6 port number of the POP3 server
- `%POP3PORT` - Port number of the POP3 server
- `%POSIX_PWD` - Current directory somewhat mingw friendly
- `%PROXYPORT` - Port number of the HTTP proxy
- `%PWD` - Current directory
- `%RTSP6PORT` - IPv6 port number of the RTSP server
- `%RTSPPORT` - Port number of the RTSP server
- `%SMBPORT` - Port number of the SMB server
- `%SMBSPORT` - Port number of the SMBS server
- `%SMTP6PORT` - IPv6 port number of the SMTP server
- `%SMTPPORT` - Port number of the SMTP server
- `%SOCKSPORT` - Port number of the SOCKS4/5 server
- `%SRCDIR` - Full path to the source dir
- `%SSHPORT` - Port number of the SCP/SFTP server
- `%SSHSRVMD5` - MD5 of SSH server's public key
- `%SSHSRVSHA256` - SHA256 of SSH server's public key
- `%SSH_PWD` - Current directory friendly for the SSH server
- `%TESTNUMBER` - Number of the test case
- `%TFTP6PORT` - IPv6 port number of the TFTP server
- `%TFTPPORT` - Port number of the TFTP server
- `%USER` - Login ID of the user running the test
- `%VERSION` - the full version number of the tested curl
# `<testcase>`
Each test is always specified entirely within the testcase tag. Each test case
is split up in four main sections: `info`, `reply`, `client` and `verify`.
- **info** provides information about the test case
- **reply** is used for the server to know what to send as a reply for the
requests curl sends
- **client** defines how the client should behave
- **verify** defines how to verify that the data stored after a command has
been run ended up correctly
Each main section has a number of available subsections that can be specified,
that will be checked/used if specified.
## `<info>`
### `<keywords>`
A newline-separated list of keywords describing what this test case uses and
tests. Try to use already used keywords. These keywords will be used for
statistical/informational purposes and for choosing or skipping classes of
tests. "Keywords" must begin with an alphabetic character, "-", "[" or "{"
and may actually consist of multiple words separated by spaces which are
treated together as a single identifier.
When using curl built with Hyper, the keywords must include HTTP or HTTPS for
'hyper mode' to kick in and make line ending checks work for tests.
## `<reply>`
### `<data [nocheck="yes"] [sendzero="yes"] [base64="yes"] [hex="yes"]>`
data to be sent to the client on its request and later verified that it
arrived safely. Set `nocheck="yes"` to prevent the test script from verifying
the arrival of this data.
If the data contains `swsclose` anywhere within the start and end tag, and
this is a HTTP test, then the connection will be closed by the server after
this response is sent. If not, the connection will be kept persistent.
If the data contains `swsbounce` anywhere within the start and end tag, the
HTTP server will detect if this is a second request using the same test and
part number and will then increase the part number with one. This is useful
for auth tests and similar.
`sendzero=yes` means that the (FTP) server will "send" the data even if the
size is zero bytes. Used to verify curl's behavior on zero bytes transfers.
`base64=yes` means that the data provided in the test-file is a chunk of data
encoded with base64. It is the only way a test case can contain binary
data. (This attribute can in fact be used on any section, but it doesn't make
much sense for other sections than "data").
`hex=yes` means that the data is a sequence of hex pairs. It will get decoded
and used as "raw" data.
For FTP file listings, the `<data>` section will be used *only* if you make
sure that there has been a CWD done first to a directory named `test-[num]`
where [num] is the test case number. Otherwise the ftp server can't know from
which test file to load the list content.
### `<dataNUM>`
Send back this contents instead of the <data> one. The num is set by:
- The test number in the request line is >10000 and this is the remainder
of [test case number]%10000.
- The request was HTTP and included digest details, which adds 1000 to NUM
- If a HTTP request is NTLM type-1, it adds 1001 to num
- If a HTTP request is NTLM type-3, it adds 1002 to num
- If a HTTP request is Basic and num is already >=1000, it adds 1 to num
- If a HTTP request is Negotiate, num gets incremented by one for each
request with Negotiate authorization header on the same test case.
Dynamically changing num in this way allows the test harness to be used to
test authentication negotiation where several different requests must be sent
to complete a transfer. The response to each request is found in its own data
section. Validating the entire negotiation sequence can be done by specifying
a datacheck section.
### `<connect>`
The connect section is used instead of the 'data' for all CONNECT
requests. The remainder of the rules for the data section then apply but with
a connect prefix.
### `<datacheck [mode="text"] [nonewline="yes"]>`
if the data is sent but this is what should be checked afterwards. If
`nonewline=yes` is set, runtests will cut off the trailing newline from the
data before comparing with the one actually received by the client.
Use the `mode="text"` attribute if the output is in text mode on platforms
that have a text/binary difference.
### `<datacheckNUM [nonewline="yes"] [mode="text"]>`
The contents of numbered datacheck sections are appended to the non-numbered
one.
### `<size>`
number to return on a ftp SIZE command (set to -1 to make this command fail)
### `<mdtm>`
what to send back if the client sends a (FTP) MDTM command, set to -1 to
have it return that the file doesn't exist
### `<postcmd>`
special purpose server-command to control its behavior *after* the
reply is sent
For HTTP/HTTPS, these are supported:
`wait [secs]` - Pause for the given time
### `<servercmd>`
Special-commands for the server.
The first line of this file will always be set to `Testnum [number]` by the
test script, to allow servers to read that to know what test the client is
about to issue.
#### For FTP/SMTP/POP/IMAP
- `REPLY [command] [return value] [response string]` - Changes how the server
responds to the [command]. [response string] is evaluated as a perl string,
so it can contain embedded \r\n, for example. There's a special [command]
named "welcome" (without quotes) which is the string sent immediately on
connect as a welcome.
- `REPLYLF` (like above but sends the response terminated with LF-only and not
CRLF)
- `COUNT [command] [num]` - Do the `REPLY` change for `[command]` only `[num]`
times and then go back to the built-in approach
- `DELAY [command] [secs]` - Delay responding to this command for the given
time
- `RETRWEIRDO` - Enable the "weirdo" RETR case when multiple response lines
appear at once when a file is transferred
- `RETRNOSIZE` - Make sure the RETR response doesn't contain the size of the
file
- `NOSAVE` - Don't actually save what is received
- `SLOWDOWN` - Send FTP responses with 0.01 sec delay between each byte
- `PASVBADIP` - makes PASV send back an illegal IP in its 227 response
- `CAPA [capabilities]` - Enables support for and specifies a list of space
separated capabilities to return to the client for the IMAP `CAPABILITY`,
POP3 `CAPA` and SMTP `EHLO` commands
- `AUTH [mechanisms]` - Enables support for SASL authentication and specifies
a list of space separated mechanisms for IMAP, POP3 and SMTP
- `STOR [msg]` respond with this instead of default after `STOR`
#### For HTTP/HTTPS
- `auth_required` if this is set and a POST/PUT is made without auth, the
server will NOT wait for the full request body to get sent
- `idle` - do nothing after receiving the request, just "sit idle"
- `stream` - continuously send data to the client, never-ending
- `writedelay: [secs]` delay this amount between reply packets
- `skip: [num]` - instructs the server to ignore reading this many bytes from
a PUT or POST request
- `rtp: part [num] channel [num] size [num]` - stream a fake RTP packet for
the given part on a chosen channel with the given payload size
- `connection-monitor` - When used, this will log `[DISCONNECT]` to the
`server.input` log when the connection is disconnected.
- `upgrade` - when an HTTP upgrade header is found, the server will upgrade to
http2
- `swsclose` - instruct server to close connection after response
- `no-expect` - don't read the request body if Expect: is present
#### For TFTP
`writedelay: [secs]` delay this amount between reply packets (each packet
being 512 bytes payload)
## `<client>`
### `<server>`
What server(s) this test case requires/uses. Available servers:
- `file`
- `ftp-ipv6`
- `ftp`
- `ftps`
- `gopher`
- `gophers`
- `http-ipv6`
- `http-proxy`
- `http-unix`
- `http/2`
- `http`
- `https`
- `httptls+srp-ipv6`
- `httptls+srp`
- `imap`
- `mqtt`
- `none`
- `pop3`
- `rtsp-ipv6`
- `rtsp`
- `scp`
- `sftp`
- `smtp`
- `socks4`
- `socks5`
Give only one per line. This subsection is mandatory.
### `<features>`
A list of features that MUST be present in the client/library for this test to
be able to run. If a required feature is not present then the test will be
SKIPPED.
Alternatively a feature can be prefixed with an exclamation mark to indicate a
feature is NOT required. If the feature is present then the test will be
SKIPPED.
Features testable here are:
- `alt-svc`
- `c-ares`
- `cookies`
- `crypto`
- `debug`
- `DoH`
- `getrlimit`
- `GnuTLS`
- `GSS-API`
- `HSTS`
- `HTTP-auth`
- `http/2`
- `hyper`
- `idn`
- `ipv6`
- `Kerberos`
- `large_file`
- `ld_preload`
- `libz`
- `manual`
- `Mime`
- `netrc`
- `NSS`
- `NTLM`
- `OpenSSL`
- `parsedate`
- `proxy`
- `PSL`
- `Schannel`
- `sectransp`
- `shuffle-dns`
- `socks`
- `SPNEGO`
- `SSL`
- `SSLpinning`
- `SSPI`
- `threaded-resolver`
- `TLS-SRP`
- `TrackMemory`
- `typecheck`
- `Unicode`
- `unittest`
- `unix-sockets`
- `verbose-strings`
- `wakeup`
- `win32`
as well as each protocol that curl supports. A protocol only needs to be
specified if it is different from the server (useful when the server
is `none`).
### `<killserver>`
Using the same syntax as in `<server>` but when mentioned here these servers
are explicitly KILLED when this test case is completed. Only use this if there
is no other alternatives. Using this of course requires subsequent tests to
restart servers.
### `<precheck>`
A command line that if set gets run by the test script before the test. If an
output is displayed by the command or if the return code is non-zero, the test
will be skipped and the (single-line) output will be displayed as reason for
not running the test.
### `<postcheck>`
A command line that if set gets run by the test script after the test. If
the command exists with a non-zero status code, the test will be considered
to have failed.
### `<tool>`
Name of tool to invoke instead of "curl". This tool must be built and exist
either in the libtest/ directory (if the tool name starts with 'lib') or in
the unit/ directory (if the tool name starts with 'unit').
### `<name>`
Brief test case description, shown when the test runs.
### `<setenv>`
variable1=contents1
variable2=contents2
Set the given environment variables to the specified value before the actual
command is run. They are cleared again after the command has been run.
### `<command [option="no-output/no-include/force-output/binary-trace"] [timeout="secs"][delay="secs"][type="perl/shell"]>`
Command line to run.
Note that the URL that gets passed to the server actually controls what data
that is returned. The last slash in the URL must be followed by a number. That
number (N) will be used by the test-server to load test case N and return the
data that is defined within the `<reply><data></data></reply>` section.
If there's no test number found above, the HTTP test server will use the
number following the last dot in the given hostname (made so that a CONNECT
can still pass on test number) so that "foo.bar.123" gets treated as test case
123. Alternatively, if an IPv6 address is provided to CONNECT, the last
hexadecimal group in the address will be used as the test number! For example
the address "[1234::ff]" would be treated as test case 255.
Set `type="perl"` to write the test case as a perl script. It implies that
there's no memory debugging and valgrind gets shut off for this test.
Set `type="shell"` to write the test case as a shell script. It implies that
there's no memory debugging and valgrind gets shut off for this test.
Set `option="no-output"` to prevent the test script to slap on the `--output`
argument that directs the output to a file. The `--output` is also not added
if the verify/stdout section is used.
Set `option="force-output"` to make use of `--output` even when the test is
otherwise written to verify stdout.
Set `option="no-include"` to prevent the test script to slap on the
`--include` argument.
Set `option="binary-trace"` to use `--trace` instead of `--trace-ascii` for
tracing. Suitable for binary-oriented protocols such as MQTT.
Set `timeout="secs"` to override default server logs advisor read lock
timeout. This timeout is used by the test harness, once that the command has
completed execution, to wait for the test server to write out server side log
files and remove the lock that advised not to read them. The "secs" parameter
is the not negative integer number of seconds for the timeout. This `timeout`
attribute is documented for completeness sake, but is deep test harness stuff
and only needed for very singular and specific test cases. Avoid using it.
Set `delay="secs"` to introduce a time delay once that the command has
completed execution and before the `<postcheck>` section runs. The "secs"
parameter is the not negative integer number of seconds for the delay. This
'delay' attribute is intended for very specific test cases, and normally not
needed.
### `<file name="log/filename" [nonewline="yes"]>`
This creates the named file with this content before the test case is run,
which is useful if the test case needs a file to act on.
If 'nonewline="yes"` is used, the created file will have the final newline
stripped off.
### `<stdin [nonewline="yes"]>`
Pass this given data on stdin to the tool.
If 'nonewline' is set, we will cut off the trailing newline of this given data
before comparing with the one actually received by the client
## `<verify>`
### `<errorcode>`
numerical error code curl is supposed to return. Specify a list of accepted
error codes by separating multiple numbers with comma. See test 237 for an
example.
### `<strip>`
One regex per line that is removed from the protocol dumps before the
comparison is made. This is very useful to remove dependencies on dynamically
changing protocol data such as port numbers or user-agent strings.
### `<strippart>`
One perl op per line that operates on the protocol dump. This is pretty
advanced. Example: `s/^EPRT .*/EPRT stripped/`.
### `<protocol [nonewline="yes"]>`
the protocol dump curl should transmit, if 'nonewline' is set, we will cut off
the trailing newline of this given data before comparing with the one actually
sent by the client The `<strip>` and `<strippart>` rules are applied before
comparisons are made.
### `<proxy [nonewline="yes"]>`
The protocol dump curl should transmit to a HTTP proxy (when the http-proxy
server is used), if 'nonewline' is set, we will cut off the trailing newline
of this given data before comparing with the one actually sent by the client
The `<strip>` and `<strippart>` rules are applied before comparisons are made.
### `<stderr [mode="text"] [nonewline="yes"]>`
This verifies that this data was passed to stderr.
Use the mode="text" attribute if the output is in text mode on platforms that
have a text/binary difference.
If 'nonewline' is set, we will cut off the trailing newline of this given data
before comparing with the one actually received by the client
### `<stdout [mode="text"] [nonewline="yes"]>`
This verifies that this data was passed to stdout.
Use the mode="text" attribute if the output is in text mode on platforms that
have a text/binary difference.
If 'nonewline' is set, we will cut off the trailing newline of this given data
before comparing with the one actually received by the client
### `<file name="log/filename" [mode="text"]>`
The file's contents must be identical to this after the test is complete. Use
the mode="text" attribute if the output is in text mode on platforms that have
a text/binary difference.
### `<file1>`
1 to 4 can be appended to 'file' to compare more files.
### `<file2>`
### `<file3>`
### `<file4>`
### `<stripfile>`
One perl op per line that operates on the output file or stdout before being
compared with what is stored in the test file. This is pretty
advanced. Example: "s/^EPRT .*/EPRT stripped/"
### `<stripfile1>`
1 to 4 can be appended to 'stripfile' to strip the corresponding <fileN>
content
### `<stripfile2>`
### `<stripfile3>`
### `<stripfile4>`
### `<upload>`
the contents of the upload data curl should have sent
### `<valgrind>`
disable - disables the valgrind log check for this test
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/keywords.pl | #!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
use strict;
push(@INC, $ENV{'srcdir'}) if(defined $ENV{'srcdir'});
push(@INC, ".");
require "getpart.pm"; # array functions
my $srcdir = $ENV{'srcdir'} || '.';
my $TESTDIR="$srcdir/data";
# Get all commands and find out their test numbers
opendir(DIR, $TESTDIR) || die "can't opendir $TESTDIR: $!";
my @cmds = grep { /^test([0-9]+)$/ && -f "$TESTDIR/$_" } readdir(DIR);
closedir DIR;
my $TESTCASES; # start with no test cases
# cut off everything but the digits
for(@cmds) {
$_ =~ s/[a-z\/\.]*//g;
}
# the numbers from low to high
for(sort { $a <=> $b } @cmds) {
$TESTCASES .= " $_";
}
my $t;
my %k; # keyword count
my %t; # keyword to test case mapping
my @miss; # test cases without keywords set
my $count;
my %errors;
for $t (split(/ /, $TESTCASES)) {
if(loadtest("${TESTDIR}/test${t}")) {
# bad case
next;
}
my @ec = getpart("verify", "errorcode");
if($ec[0]) {
# count number of check error codes
$errors{ 0 + $ec[0] } ++;
}
my @what = getpart("info", "keywords");
if(!$what[0]) {
push @miss, $t;
next;
}
for(@what) {
chomp;
#print "Test $t: $_\n";
$k{$_}++;
$t{$_} .= "$t ";
}
$count++;
}
sub show {
my ($list)=@_;
my @a = split(" ", $list);
my $ret;
my $c;
my @l = sort {rand(100) - 50} @a;
my @ll;
for(1 .. 11) {
my $v = shift @l;
if($v) {
push @ll, $v;
}
}
for (sort {$a <=> $b} @ll) {
if($c++ == 10) {
$ret .= "...";
last;
}
$ret .= "$_ ";
}
return $ret;
}
# sort alphabetically
my @mtest = reverse sort { lc($b) cmp lc($a) } keys %k;
print <<TOP
<table><tr><th>Num</th><th>Keyword</th><th>Test Cases</th></tr>
TOP
;
for $t (@mtest) {
printf "<tr><td>%d</td><td>$t</td><td>%s</td></tr>\n", $k{$t},
show($t{$t});
}
printf "</table><p> $count out of %d tests (%d lack keywords)\n",
scalar(@miss) + $count,
scalar(@miss);
for(@miss) {
print "$_ ";
}
print "\n";
printf "<p> %d different error codes tested for:<br>\n",
scalar(keys %errors);
# numerically on amount, or alphebetically if same amount
my @etest = sort { $a <=> $b} keys %errors;
for(@etest) {
print "$_ ";
}
print "\n";
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/httpserver.pl | #!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
#***************************************************************************
BEGIN {
push(@INC, $ENV{'srcdir'}) if(defined $ENV{'srcdir'});
push(@INC, ".");
}
use strict;
use warnings;
use serverhelp qw(
server_pidfilename
server_logfilename
);
use sshhelp qw(
exe_ext
);
my $verbose = 0; # set to 1 for debugging
my $port = 8990; # just a default
my $unix_socket; # location to place a listening Unix socket
my $ipvnum = 4; # default IP version of http server
my $idnum = 1; # default http server instance number
my $proto = 'http'; # protocol the http server speaks
my $pidfile; # pid file
my $portfile; # port number file
my $logfile; # log file
my $connect; # IP to connect to on CONNECT
my $srcdir;
my $gopher = 0;
my $flags = "";
my $path = '.';
my $logdir = $path .'/log';
while(@ARGV) {
if($ARGV[0] eq '--pidfile') {
if($ARGV[1]) {
$pidfile = $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--portfile') {
if($ARGV[1]) {
$portfile = $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--logfile') {
if($ARGV[1]) {
$logfile = $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--srcdir') {
if($ARGV[1]) {
$srcdir = $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--ipv4') {
$ipvnum = 4;
}
elsif($ARGV[0] eq '--ipv6') {
$ipvnum = 6;
}
elsif($ARGV[0] eq '--unix-socket') {
$ipvnum = 'unix';
if($ARGV[1]) {
$unix_socket = $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--gopher') {
$gopher = 1;
}
elsif($ARGV[0] eq '--port') {
if($ARGV[1] =~ /^(\d+)$/) {
$port = $1;
shift @ARGV;
}
}
elsif($ARGV[0] eq '--connect') {
if($ARGV[1]) {
$connect = $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--id') {
if($ARGV[1] =~ /^(\d+)$/) {
$idnum = $1 if($1 > 0);
shift @ARGV;
}
}
elsif($ARGV[0] eq '--verbose') {
$verbose = 1;
}
else {
print STDERR "\nWarning: httpserver.pl unknown parameter: $ARGV[0]\n";
}
shift @ARGV;
}
if(!$srcdir) {
$srcdir = $ENV{'srcdir'} || '.';
}
if(!$pidfile) {
$pidfile = "$path/". server_pidfilename($proto, $ipvnum, $idnum);
}
if(!$portfile) {
$portfile = "$path/". server_portfilename($proto, $ipvnum, $idnum);
}
if(!$logfile) {
$logfile = server_logfilename($logdir, $proto, $ipvnum, $idnum);
}
$flags .= "--pidfile \"$pidfile\" ".
"--logfile \"$logfile\" ".
"--portfile \"$portfile\" ";
$flags .= "--gopher " if($gopher);
$flags .= "--connect $connect " if($connect);
if($ipvnum eq 'unix') {
$flags .= "--unix-socket '$unix_socket' ";
} else {
$flags .= "--ipv$ipvnum --port $port ";
}
$flags .= "--srcdir \"$srcdir\"";
if($verbose) {
print STDERR "RUN: server/sws".exe_ext('SRV')." $flags\n";
}
$| = 1;
exec("exec server/sws".exe_ext('SRV')." $flags");
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/symbol-scan.pl | #!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 2010 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
#
# This script grew out of help from Przemyslaw Iskra and Balint Szilakszi
# a late evening in the #curl IRC channel.
#
use strict;
use warnings;
use vars qw($Cpreprocessor);
#
# configurehelp perl module is generated by configure script
#
my $rc = eval {
require configurehelp;
configurehelp->import(qw(
$Cpreprocessor
));
1;
};
# Set default values if configure has not generated a configurehelp.pm file.
# This is the case with cmake.
if (!$rc) {
$Cpreprocessor = 'cpp';
}
# we may get the dir root pointed out
my $root=$ARGV[0] || ".";
# need an include directory when building out-of-tree
my $i = ($ARGV[1]) ? "-I$ARGV[1] " : '';
my $h = "$root/include/curl/curl.h";
my $mh = "$root/include/curl/multi.h";
my $ua = "$root/include/curl/urlapi.h";
my $verbose=0;
my $summary=0;
my $misses=0;
my @syms;
my %doc;
my %rem;
open H_IN, "-|", "$Cpreprocessor $i$h" || die "Cannot preprocess curl.h";
while ( <H_IN> ) {
if ( /enum\s+(\S+\s+)?{/ .. /}/ ) {
s/^\s+//;
next unless /^CURL/;
chomp;
s/[,\s].*//;
push @syms, $_;
}
}
close H_IN || die "Error preprocessing curl.h";
sub scanheader {
my ($f)=@_;
open H, "<$f";
while(<H>) {
if (/^#define (CURL[A-Za-z0-9_]*)/) {
push @syms, $1;
}
}
close H;
}
scanheader($h);
scanheader($mh);
scanheader($ua);
open S, "<$root/docs/libcurl/symbols-in-versions";
while(<S>) {
if(/(^CURL[^ \n]*) *(.*)/) {
my ($sym, $rest)=($1, $2);
if($doc{$sym}) {
print "Detected duplicate symbol: $sym\n";
$misses++;
next;
}
$doc{$sym}=$sym;
my @a=split(/ +/, $rest);
if($a[2]) {
# this symbol is documented to have been present the last time
# in this release
$rem{$sym}=$a[2];
}
}
}
close S;
my $ignored=0;
for my $e (sort @syms) {
# OBSOLETE - names that are just placeholders for a position where we
# previously had a name, that is now removed. The OBSOLETE names should
# never be used for anything.
#
# CURL_EXTERN - is a define used for libcurl functions that are external,
# public. No app or other code should ever use it.
#
# CURLINC_ - defines for header dual-include prevention, ignore those.
#
# *_LAST and *_LASTENTRY are just prefix for the placeholders used for the
# last entry in many enum series.
#
if($e =~ /(OBSOLETE|^CURL_EXTERN|^CURLINC_|_LAST\z|_LASTENTRY\z)/) {
$ignored++;
next;
}
if($doc{$e}) {
if($verbose) {
print $e."\n";
}
$doc{$e}="used";
next;
}
else {
print $e."\n";
$misses++;
}
}
#
# now scan through all symbols that were present in the symbols-in-versions
# but not in the headers
#
# If the symbols were marked 'removed' in symbols-in-versions we don't output
# anything about it since that is perfectly fine.
#
my $anyremoved;
for my $e (sort keys %doc) {
if(($doc{$e} ne "used") && !$rem{$e}) {
if(!$anyremoved++) {
print "Missing symbols mentioned in symbols-in-versions\n";
print "Add them to a header, or mark them as removed.\n";
}
print "$e\n";
$misses++;
}
}
if($summary) {
print "Summary:\n";
printf "%d symbols in headers (out of which %d are ignored)\n", scalar(@syms),
$ignored;
printf "%d symbols in headers are interesting\n",
scalar(@syms)- $ignored;
printf "%d symbols are listed in symbols-in-versions\n (out of which %d are listed as removed)\n", scalar(keys %doc), scalar(keys %rem);
printf "%d symbols in symbols-in-versions should match the ones in headers\n", scalar(keys %doc) - scalar(keys %rem);
}
if($misses) {
exit 0; # there are stuff to attend to!
}
else {
print "OK\n";
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/error-codes.pl | #!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 2010 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
#
#
use strict;
use warnings;
# we may get the dir root pointed out
my $root=$ARGV[0] || ".";
my %error; # from the include file
my %docs; # from libcurl-errors.3
sub getdocserrors {
open(F, "<$root/docs/libcurl/libcurl-errors.3");
while(<F>) {
if($_ =~ /^.IP \"(CURL[EM]_[^ \t\"]*)/) {
my ($symbol) = ($1);
if($symbol =~ /OBSOLETE/) {
;
}
else {
$docs{$symbol}=1;
}
}
}
close(F);
}
sub getincludeerrors {
open(F, "<$root/docs/libcurl/symbols-in-versions");
while(<F>) {
if($_ =~ /^(CURL[EM]_[^ \t]*)[ \t]*([0-9.]+)[ \t]*(.*)/) {
my ($symbol, $added, $rest) = ($1,$2,$3);
if($rest =~ /^([0-9.]+)/) {
# removed!
}
else {
$error{$symbol}=$added;
}
}
}
close(F);
}
getincludeerrors();
getdocserrors();
for(sort keys %error) {
if($error{$_} && !$docs{$_}) {
print "$_ is not in libcurl-errors.3\n";
}
}
for(sort keys %docs) {
if($docs{$_} && !$error{$_}) {
print "$_ is not in symbols-in-versions\n";
}
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/rtspserver.pl | #!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
#***************************************************************************
BEGIN {
push(@INC, $ENV{'srcdir'}) if(defined $ENV{'srcdir'});
push(@INC, ".");
}
use strict;
use warnings;
use serverhelp qw(
server_pidfilename
server_logfilename
);
use sshhelp qw(
exe_ext
);
my $verbose = 0; # set to 1 for debugging
my $port = 8990; # just a default
my $ipvnum = 4; # default IP version of rtsp server
my $idnum = 1; # default rtsp server instance number
my $proto = 'rtsp'; # protocol the rtsp server speaks
my $pidfile; # rtsp server pid file
my $portfile;
my $logfile; # rtsp server log file
my $srcdir;
my $flags = "";
my $path = '.';
my $logdir = $path .'/log';
while(@ARGV) {
if($ARGV[0] eq '--pidfile') {
if($ARGV[1]) {
$pidfile = $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--portfile') {
if($ARGV[1]) {
$portfile = $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--logfile') {
if($ARGV[1]) {
$logfile = $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--srcdir') {
if($ARGV[1]) {
$srcdir = $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--ipv4') {
$ipvnum = 4;
}
elsif($ARGV[0] eq '--ipv6') {
$ipvnum = 6;
}
elsif($ARGV[0] eq '--port') {
if($ARGV[1] =~ /^(\d+)$/) {
$port = $1;
shift @ARGV;
}
}
elsif($ARGV[0] eq '--id') {
if($ARGV[1] =~ /^(\d+)$/) {
$idnum = $1 if($1 > 0);
shift @ARGV;
}
}
elsif($ARGV[0] eq '--verbose') {
$verbose = 1;
}
else {
print STDERR "\nWarning: rtspserver.pl unknown parameter: $ARGV[0]\n";
}
shift @ARGV;
}
if(!$srcdir) {
$srcdir = $ENV{'srcdir'} || '.';
}
if(!$pidfile) {
$pidfile = "$path/". server_pidfilename($proto, $ipvnum, $idnum);
}
if(!$logfile) {
$logfile = server_logfilename($logdir, $proto, $ipvnum, $idnum);
}
$flags .= "--pidfile \"$pidfile\" ".
"--portfile \"$portfile\" ".
"--logfile \"$logfile\" ";
$flags .= "--ipv$ipvnum --port $port --srcdir \"$srcdir\"";
$| = 1;
exec("exec server/rtspd".exe_ext('SRV')." $flags");
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/valgrind.supp | {
zstd_decompression-1.3.3-on-Ubuntu-18.04_with_hyper
Memcheck:Cond
fun:ZSTD_decompressStream
fun:zstd_unencode_write
fun:Curl_unencode_write
fun:hyper_body_chunk
}
{
zstd_decompression-1.3.3-on-Ubuntu-18.04
Memcheck:Cond
fun:ZSTD_decompressStream
fun:zstd_unencode_write
fun:Curl_unencode_write
fun:readwrite_data
fun:Curl_readwrite
fun:multi_runsingle
fun:curl_multi_perform
fun:easy_transfer
fun:easy_perform
fun:curl_easy_perform
fun:serial_transfers
fun:run_all_transfers
fun:operate
fun:main
}
{
zstd_decompression-1.3.3-on-Ubuntu-18.04-nondebug
Memcheck:Cond
fun:ZSTD_decompressStream
fun:zstd_unencode_write
fun:Curl_readwrite
fun:multi_runsingle
fun:curl_multi_perform
fun:curl_easy_perform
fun:operate
fun:main
}
{
libidn-idna_to_ascii-error
Memcheck:Addr4
fun:idna_to_ascii_4z
fun:idna_to_ascii_8z
fun:idna_to_ascii_lz
fun:fix_hostname
fun:resolve_server
fun:create_conn
fun:Curl_connect
fun:multi_runsingle
fun:curl_multi_perform
fun:easy_transfer
fun:easy_perform
fun:curl_easy_perform
fun:operate_do
fun:operate
fun:main
}
{
libidn-idna_to_ascii-error-eventbased
Memcheck:Addr4
fun:idna_to_ascii_4z
fun:idna_to_ascii_8z
fun:idna_to_ascii_lz
fun:fix_hostname
fun:resolve_server
fun:create_conn
fun:Curl_connect
fun:multi_runsingle
fun:multi_socket
fun:curl_multi_socket_action
fun:wait_or_timeout
fun:easy_events
fun:easy_perform
fun:curl_easy_perform_ev
fun:operate_do
fun:operate
fun:main
}
{
libidn-idna_to_ascii-error-inlined-functions
Memcheck:Addr4
fun:idna_to_ascii_4z
fun:idna_to_ascii_8z
fun:idna_to_ascii_lz
fun:fix_hostname
fun:Curl_connect
fun:multi_runsingle
fun:curl_multi_perform
fun:easy_perform.part.4
fun:operate_do
fun:operate
fun:main
}
{
libidn-idna_to_ascii-error-inlined-functions-alt
Memcheck:Addr4
fun:idna_to_ascii_4z
fun:idna_to_ascii_8z
fun:idna_to_ascii_lz
fun:fix_hostname
fun:Curl_connect
fun:multi_runsingle
fun:curl_multi_perform
fun:easy_perform
fun:operate_do.isra.0
fun:operate
fun:main
}
{
libidn-idna_to_ascii-error-inlined-functions-alt2
Memcheck:Addr4
fun:idna_to_ascii_4z
fun:idna_to_ascii_8z
fun:idna_to_ascii_lz
fun:fix_hostname
fun:Curl_connect
fun:multi_runsingle
fun:curl_multi_perform
fun:easy_perform
fun:operate_do
fun:operate
fun:main
}
{
openssl-1.0.1-error-as-seen-on-travis
Memcheck:Cond
fun:ASN1_STRING_set
fun:ASN1_mbstring_ncopy
fun:ASN1_mbstring_copy
fun:ASN1_STRING_to_UTF8
obj:/lib/x86_64-linux-gnu/libcrypto.so.1.0.0
obj:/lib/x86_64-linux-gnu/libcrypto.so.1.0.0
fun:ASN1_item_ex_d2i
obj:/lib/x86_64-linux-gnu/libcrypto.so.1.0.0
obj:/lib/x86_64-linux-gnu/libcrypto.so.1.0.0
fun:ASN1_item_ex_d2i
obj:/lib/x86_64-linux-gnu/libcrypto.so.1.0.0
obj:/lib/x86_64-linux-gnu/libcrypto.so.1.0.0
fun:ASN1_item_ex_d2i
fun:ASN1_item_d2i
fun:PEM_X509_INFO_read_bio
fun:X509_load_cert_crl_file
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/CMakeLists.txt | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
add_custom_target(testdeps)
add_subdirectory(data)
add_subdirectory(libtest)
add_subdirectory(server)
add_subdirectory(unit)
function(add_runtests targetname test_flags)
# Use a special '$TFLAGS' placeholder as last argument which will be
# replaced by the contents of the environment variable in runtests.pl.
# This is a workaround for CMake's limitation where commands executed by
# 'make' or 'ninja' cannot portably reference environment variables.
string(REPLACE " " ";" test_flags_list "${test_flags}")
add_custom_target(${targetname}
COMMAND
"${PERL_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/runtests.pl"
${test_flags_list}
"\$TFLAGS"
DEPENDS testdeps
VERBATIM USES_TERMINAL
)
endfunction()
add_runtests(test-quiet "-a -s")
add_runtests(test-am "-a -am")
add_runtests(test-full "-a -p -r")
# !flaky means that it'll skip all tests using the flaky keyword
add_runtests(test-nonflaky "-a -p !flaky")
add_runtests(test-ci "-a -p !flaky -r -rm")
add_runtests(test-torture "-a -t")
add_runtests(test-event "-a -e")
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/runtests.pl | #!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
# Experimental hooks are available to run tests remotely on machines that
# are able to run curl but are unable to run the test harness.
# The following sections need to be modified:
#
# $HOSTIP, $HOST6IP - Set to the address of the host running the test suite
# $CLIENTIP, $CLIENT6IP - Set to the address of the host running curl
# runclient, runclientoutput - Modify to copy all the files in the log/
# directory to the system running curl, run the given command remotely
# and save the return code or returned stdout (respectively), then
# copy all the files from the remote system's log/ directory back to
# the host running the test suite. This can be done a few ways, such
# as using scp & ssh, rsync & telnet, or using a NFS shared directory
# and ssh.
#
# 'make && make test' needs to be done on both machines before making the
# above changes and running runtests.pl manually. In the shared NFS case,
# the contents of the tests/server/ directory must be from the host
# running the test suite, while the rest must be from the host running curl.
#
# Note that even with these changes a number of tests will still fail (mainly
# to do with cookies, those that set environment variables, or those that
# do more than touch the file system in a <precheck> or <postcheck>
# section). These can be added to the $TESTCASES line below,
# e.g. $TESTCASES="!8 !31 !63 !cookies..."
#
# Finally, to properly support -g and -n, checktestcmd needs to change
# to check the remote system's PATH, and the places in the code where
# the curl binary is read directly to determine its type also need to be
# fixed. As long as the -g option is never given, and the -n is always
# given, this won't be a problem.
# These should be the only variables that might be needed to get edited:
BEGIN {
# Define srcdir to the location of the tests source directory. This is
# usually set by the Makefile, but for out-of-tree builds with direct
# invocation of runtests.pl, it may not be set.
if(!defined $ENV{'srcdir'}) {
use File::Basename;
$ENV{'srcdir'} = dirname(__FILE__);
}
push(@INC, $ENV{'srcdir'});
# run time statistics needs Time::HiRes
eval {
no warnings "all";
require Time::HiRes;
import Time::HiRes qw( time );
}
}
use strict;
use warnings;
use Cwd;
use Digest::MD5 qw(md5);
use MIME::Base64;
# Subs imported from serverhelp module
use serverhelp qw(
serverfactors
servername_id
servername_str
servername_canon
server_pidfilename
server_portfilename
server_logfilename
);
# Variables and subs imported from sshhelp module
use sshhelp qw(
$sshdexe
$sshexe
$sftpexe
$sshconfig
$sftpconfig
$sshdlog
$sshlog
$sftplog
$sftpcmds
display_sshdconfig
display_sshconfig
display_sftpconfig
display_sshdlog
display_sshlog
display_sftplog
exe_ext
find_sshd
find_ssh
find_sftp
find_httptlssrv
sshversioninfo
);
use pathhelp;
require "getpart.pm"; # array functions
require "valgrind.pm"; # valgrind report parser
require "ftp.pm";
require "azure.pm";
require "appveyor.pm";
my $HOSTIP="127.0.0.1"; # address on which the test server listens
my $HOST6IP="[::1]"; # address on which the test server listens
my $CLIENTIP="127.0.0.1"; # address which curl uses for incoming connections
my $CLIENT6IP="[::1]"; # address which curl uses for incoming connections
my $noport="[not running]";
my $NOLISTENPORT=47; # port number we use for a local non-listening service
my $MQTTPORT=$noport; # MQTT server port
my $HTTPPORT=$noport; # HTTP server port
my $HTTP6PORT=$noport; # HTTP IPv6 server port
my $HTTPSPORT=$noport; # HTTPS (stunnel) server port
my $HTTPSPROXYPORT = $noport; # HTTPS-proxy (stunnel) port
my $FTPPORT=$noport; # FTP server port
my $FTPSPORT=$noport; # FTPS (stunnel) server port
my $FTP6PORT=$noport; # FTP IPv6 server port
my $TFTPPORT=$noport; # TFTP
my $TFTP6PORT=$noport; # TFTP
my $SSHPORT=$noport; # SCP/SFTP
my $SOCKSPORT=$noport; # SOCKS4/5 port
my $POP3PORT=$noport; # POP3
my $POP36PORT=$noport; # POP3 IPv6 server port
my $IMAPPORT=$noport; # IMAP
my $IMAP6PORT=$noport; # IMAP IPv6 server port
my $SMTPPORT=$noport; # SMTP
my $SMTP6PORT=$noport; # SMTP IPv6 server port
my $RTSPPORT=$noport; # RTSP
my $RTSP6PORT=$noport; # RTSP IPv6 server port
my $GOPHERPORT=$noport; # Gopher
my $GOPHERSPORT=$noport; # Gophers
my $GOPHER6PORT=$noport; # Gopher IPv6 server port
my $HTTPTLSPORT=$noport; # HTTP TLS (non-stunnel) server port
my $HTTPTLS6PORT=$noport; # HTTP TLS (non-stunnel) IPv6 server port
my $HTTPPROXYPORT=$noport; # HTTP proxy port, when using CONNECT
my $HTTP2PORT=$noport; # HTTP/2 server port
my $DICTPORT=$noport; # DICT server port
my $SMBPORT=$noport; # SMB server port
my $SMBSPORT=$noport; # SMBS server port
my $TELNETPORT=$noport; # TELNET server port with negotiation
my $HTTPUNIXPATH; # HTTP server Unix domain socket path
my $use_external_proxy = 0;
my $proxy_address;
my %custom_skip_reasons;
my $SSHSRVMD5 = "[uninitialized]"; # MD5 of ssh server public key
my $SSHSRVSHA256 = "[uninitialized]"; # SHA256 of ssh server public key
my $VERSION=""; # curl's reported version number
my $srcdir = $ENV{'srcdir'} || '.';
my $CURL="../src/curl".exe_ext('TOOL'); # what curl executable to run on the tests
my $VCURL=$CURL; # what curl binary to use to verify the servers with
# VCURL is handy to set to the system one when the one you
# just built hangs or crashes and thus prevent verification
my $DBGCURL=$CURL; #"../src/.libs/curl"; # alternative for debugging
my $LOGDIR="log";
my $TESTDIR="$srcdir/data";
my $LIBDIR="./libtest";
my $UNITDIR="./unit";
# TODO: change this to use server_inputfilename()
my $SERVERIN="$LOGDIR/server.input"; # what curl sent the server
my $SERVER2IN="$LOGDIR/server2.input"; # what curl sent the second server
my $PROXYIN="$LOGDIR/proxy.input"; # what curl sent the proxy
my $CURLLOG="commands.log"; # all command lines run
my $FTPDCMD="$LOGDIR/ftpserver.cmd"; # copy server instructions here
my $SERVERLOGS_LOCK="$LOGDIR/serverlogs.lock"; # server logs advisor read lock
my $CURLCONFIG="../curl-config"; # curl-config from current build
# Normally, all test cases should be run, but at times it is handy to
# simply run a particular one:
my $TESTCASES="all";
# To run specific test cases, set them like:
# $TESTCASES="1 2 3 7 8";
#######################################################################
# No variables below this point should need to be modified
#
# invoke perl like this:
my $perl="perl -I$srcdir";
my $server_response_maxtime=13;
my $debug_build=0; # built debug enabled (--enable-debug)
my $has_memory_tracking=0; # built with memory tracking (--enable-curldebug)
my $libtool;
my $repeat = 0;
# name of the file that the memory debugging creates:
my $memdump="$LOGDIR/memdump";
# the path to the script that analyzes the memory debug output file:
my $memanalyze="$perl $srcdir/memanalyze.pl";
my $pwd = getcwd(); # current working directory
my $posix_pwd = $pwd;
my $start;
my $ftpchecktime=1; # time it took to verify our test FTP server
my $scrambleorder;
my $stunnel = checkcmd("stunnel4") || checkcmd("tstunnel") || checkcmd("stunnel");
my $valgrind = checktestcmd("valgrind");
my $valgrind_logfile="--logfile";
my $valgrind_tool;
my $gdb = checktestcmd("gdb");
my $httptlssrv = find_httptlssrv();
my $uname_release = `uname -r`;
my $is_wsl = $uname_release =~ /Microsoft$/;
my $has_ssl; # set if libcurl is built with SSL support
my $has_largefile; # set if libcurl is built with large file support
my $has_idn; # set if libcurl is built with IDN support
my $http_ipv6; # set if HTTP server has IPv6 support
my $http_unix; # set if HTTP server has Unix sockets support
my $ftp_ipv6; # set if FTP server has IPv6 support
my $tftp_ipv6; # set if TFTP server has IPv6 support
my $gopher_ipv6; # set if Gopher server has IPv6 support
my $has_ipv6; # set if libcurl is built with IPv6 support
my $has_unix; # set if libcurl is built with Unix sockets support
my $has_libz; # set if libcurl is built with libz support
my $has_brotli; # set if libcurl is built with brotli support
my $has_zstd; # set if libcurl is built with zstd support
my $has_getrlimit; # set if system has getrlimit()
my $has_ntlm; # set if libcurl is built with NTLM support
my $has_ntlm_wb; # set if libcurl is built with NTLM delegation to winbind
my $has_sspi; # set if libcurl is built with Windows SSPI
my $has_gssapi; # set if libcurl is built with a GSS-API library
my $has_kerberos; # set if libcurl is built with Kerberos support
my $has_spnego; # set if libcurl is built with SPNEGO support
my $has_charconv; # set if libcurl is built with CharConv support
my $has_tls_srp; # set if libcurl is built with TLS-SRP support
my $has_http2; # set if libcurl is built with HTTP2 support
my $has_httpsproxy; # set if libcurl is built with HTTPS-proxy support
my $has_crypto; # set if libcurl is built with cryptographic support
my $has_cares; # set if built with c-ares
my $has_threadedres;# set if built with threaded resolver
my $has_psl; # set if libcurl is built with PSL support
my $has_altsvc; # set if libcurl is built with alt-svc support
my $has_hsts; # set if libcurl is built with HSTS support
my $has_ldpreload; # set if built for systems supporting LD_PRELOAD
my $has_multissl; # set if build with MultiSSL support
my $has_manual; # set if built with built-in manual
my $has_win32; # set if built for Windows
my $has_mingw; # set if built with MinGW (as opposed to MinGW-w64)
my $has_hyper = 0; # set if built with Hyper
my $has_unicode; # set if libcurl is built with Unicode support
# this version is decided by the particular nghttp2 library that is being used
my $h2cver = "h2c";
my $has_openssl; # built with a lib using an OpenSSL-like API
my $has_gnutls; # built with GnuTLS
my $has_nss; # built with NSS
my $has_wolfssl; # built with wolfSSL
my $has_schannel; # built with Schannel
my $has_sectransp; # built with Secure Transport
my $has_boringssl; # built with BoringSSL
my $has_libressl; # built with libressl
my $has_mbedtls; # built with mbedTLS
my $has_mesalink; # built with MesaLink
my $has_sslpinning; # built with a TLS backend that supports pinning
my $has_shared = "unknown"; # built shared
my $resolver; # name of the resolver backend (for human presentation)
my $has_textaware; # set if running on a system that has a text mode concept
# on files. Windows for example
my @protocols; # array of lowercase supported protocol servers
my $skipped=0; # number of tests skipped; reported in main loop
my %skipped; # skipped{reason}=counter, reasons for skip
my @teststat; # teststat[testnum]=reason, reasons for skip
my %disabled_keywords; # key words of tests to skip
my %ignored_keywords; # key words of tests to ignore results
my %enabled_keywords; # key words of tests to run
my %disabled; # disabled test cases
my %ignored; # ignored results of test cases
my $sshdid; # for socks server, ssh daemon version id
my $sshdvernum; # for socks server, ssh daemon version number
my $sshdverstr; # for socks server, ssh daemon version string
my $sshderror; # for socks server, ssh daemon version error
my $defserverlogslocktimeout = 2; # timeout to await server logs lock removal
my $defpostcommanddelay = 0; # delay between command and postcheck sections
my $timestats; # time stamping and stats generation
my $fullstats; # show time stats for every single test
my %timeprepini; # timestamp for each test preparation start
my %timesrvrini; # timestamp for each test required servers verification start
my %timesrvrend; # timestamp for each test required servers verification end
my %timetoolini; # timestamp for each test command run starting
my %timetoolend; # timestamp for each test command run stopping
my %timesrvrlog; # timestamp for each test server logs lock removal
my %timevrfyend; # timestamp for each test result verification end
my $testnumcheck; # test number, set in singletest sub.
my %oldenv;
my %feature; # array of enabled features
my %keywords; # array of keywords from the test spec
#######################################################################
# variables that command line options may set
#
my $short;
my $automakestyle;
my $verbose;
my $debugprotocol;
my $anyway;
my $gdbthis; # run test case with gdb debugger
my $gdbxwin; # use windowed gdb when using gdb
my $keepoutfiles; # keep stdout and stderr files after tests
my $clearlocks; # force removal of files by killing locking processes
my $listonly; # only list the tests
my $postmortem; # display detailed info about failed tests
my $err_unexpected; # error instead of warning on server unexpectedly alive
my $run_event_based; # run curl with --test-event to test the event API
my $run_disabeled; # run the specific tests even if listed in DISABLED
my %run; # running server
my %doesntrun; # servers that don't work, identified by pidfile
my %serverpidfile;# all server pid file names, identified by server id
my %serverportfile;# all server port file names, identified by server id
my %runcert; # cert file currently in use by an ssl running server
# torture test variables
my $torture;
my $tortnum;
my $tortalloc;
my $shallow;
my $randseed = 0;
# Azure Pipelines specific variables
my $AZURE_RUN_ID = 0;
my $AZURE_RESULT_ID = 0;
#######################################################################
# logmsg is our general message logging subroutine.
#
sub logmsg {
for(@_) {
my $line = $_;
if ($is_wsl) {
# use \r\n for WSL shell
$line =~ s/\r?\n$/\r\n/g;
}
print "$line";
}
}
# get the name of the current user
my $USER = $ENV{USER}; # Linux
if (!$USER) {
$USER = $ENV{USERNAME}; # Windows
if (!$USER) {
$USER = $ENV{LOGNAME}; # Some Unix (I think)
}
}
# enable memory debugging if curl is compiled with it
$ENV{'CURL_MEMDEBUG'} = $memdump;
$ENV{'CURL_ENTROPY'}="12345678";
$ENV{'CURL_FORCETIME'}=1; # for debug NTLM magic
$ENV{'CURL_GLOBAL_INIT'}=1; # debug curl_global_init/cleanup use
$ENV{'HOME'}=$pwd;
$ENV{'CURL_HOME'}=$ENV{'HOME'};
$ENV{'XDG_CONFIG_HOME'}=$ENV{'HOME'};
$ENV{'COLUMNS'}=79; # screen width!
sub catch_zap {
my $signame = shift;
logmsg "runtests.pl received SIG$signame, exiting\n";
stopservers($verbose);
die "Somebody sent me a SIG$signame";
}
$SIG{INT} = \&catch_zap;
$SIG{TERM} = \&catch_zap;
##########################################################################
# Clear all possible '*_proxy' environment variables for various protocols
# to prevent them to interfere with our testing!
my $protocol;
foreach $protocol (('ftp', 'http', 'ftps', 'https', 'no', 'all')) {
my $proxy = "${protocol}_proxy";
# clear lowercase version
delete $ENV{$proxy} if($ENV{$proxy});
# clear uppercase version
delete $ENV{uc($proxy)} if($ENV{uc($proxy)});
}
# make sure we don't get affected by other variables that control our
# behavior
delete $ENV{'SSL_CERT_DIR'} if($ENV{'SSL_CERT_DIR'});
delete $ENV{'SSL_CERT_PATH'} if($ENV{'SSL_CERT_PATH'});
delete $ENV{'CURL_CA_BUNDLE'} if($ENV{'CURL_CA_BUNDLE'});
#######################################################################
# Load serverpidfile and serverportfile hashes with file names for all
# possible servers.
#
sub init_serverpidfile_hash {
for my $proto (('ftp', 'gopher', 'http', 'imap', 'pop3', 'smtp', 'http/2')) {
for my $ssl (('', 's')) {
for my $ipvnum ((4, 6)) {
for my $idnum ((1, 2, 3)) {
my $serv = servername_id("$proto$ssl", $ipvnum, $idnum);
my $pidf = server_pidfilename("$proto$ssl", $ipvnum, $idnum);
$serverpidfile{$serv} = $pidf;
my $portf = server_portfilename("$proto$ssl", $ipvnum, $idnum);
$serverportfile{$serv} = $portf;
}
}
}
}
for my $proto (('tftp', 'sftp', 'socks', 'ssh', 'rtsp', 'httptls',
'dict', 'smb', 'smbs', 'telnet', 'mqtt')) {
for my $ipvnum ((4, 6)) {
for my $idnum ((1, 2)) {
my $serv = servername_id($proto, $ipvnum, $idnum);
my $pidf = server_pidfilename($proto, $ipvnum, $idnum);
$serverpidfile{$serv} = $pidf;
my $portf = server_portfilename($proto, $ipvnum, $idnum);
$serverportfile{$serv} = $portf;
}
}
}
for my $proto (('http', 'imap', 'pop3', 'smtp', 'http/2')) {
for my $ssl (('', 's')) {
my $serv = servername_id("$proto$ssl", "unix", 1);
my $pidf = server_pidfilename("$proto$ssl", "unix", 1);
$serverpidfile{$serv} = $pidf;
my $portf = server_portfilename("$proto$ssl", "unix", 1);
$serverportfile{$serv} = $portf;
}
}
}
#######################################################################
# Check if a given child process has just died. Reaps it if so.
#
sub checkdied {
use POSIX ":sys_wait_h";
my $pid = $_[0];
if((not defined $pid) || $pid <= 0) {
return 0;
}
my $rc = pidwait($pid, &WNOHANG);
return ($rc == $pid)?1:0;
}
#######################################################################
# Start a new thread/process and run the given command line in there.
# Return the pids (yes plural) of the new child process to the parent.
#
sub startnew {
my ($cmd, $pidfile, $timeout, $fake)=@_;
logmsg "startnew: $cmd\n" if ($verbose);
my $child = fork();
my $pid2 = 0;
if(not defined $child) {
logmsg "startnew: fork() failure detected\n";
return (-1,-1);
}
if(0 == $child) {
# Here we are the child. Run the given command.
# Flush output.
$| = 1;
# Put an "exec" in front of the command so that the child process
# keeps this child's process ID.
exec("exec $cmd") || die "Can't exec() $cmd: $!";
# exec() should never return back here to this process. We protect
# ourselves by calling die() just in case something goes really bad.
die "error: exec() has returned";
}
# Ugly hack but ssh client and gnutls-serv don't support pid files
if ($fake) {
if(open(OUT, ">$pidfile")) {
print OUT $child . "\n";
close(OUT);
logmsg "startnew: $pidfile faked with pid=$child\n" if($verbose);
}
else {
logmsg "startnew: failed to write fake $pidfile with pid=$child\n";
}
# could/should do a while connect fails sleep a bit and loop
portable_sleep($timeout);
if (checkdied($child)) {
logmsg "startnew: child process has failed to start\n" if($verbose);
return (-1,-1);
}
}
my $count = $timeout;
while($count--) {
if(-f $pidfile && -s $pidfile && open(PID, "<$pidfile")) {
$pid2 = 0 + <PID>;
close(PID);
if(($pid2 > 0) && pidexists($pid2)) {
# if $pid2 is valid, then make sure this pid is alive, as
# otherwise it is just likely to be the _previous_ pidfile or
# similar!
last;
}
# invalidate $pid2 if not actually alive
$pid2 = 0;
}
if (checkdied($child)) {
logmsg "startnew: child process has died, server might start up\n"
if($verbose);
# We can't just abort waiting for the server with a
# return (-1,-1);
# because the server might have forked and could still start
# up normally. Instead, just reduce the amount of time we remain
# waiting.
$count >>= 2;
}
sleep(1);
}
# Return two PIDs, the one for the child process we spawned and the one
# reported by the server itself (in case it forked again on its own).
# Both (potentially) need to be killed at the end of the test.
return ($child, $pid2);
}
#######################################################################
# Check for a command in the PATH of the test server.
#
sub checkcmd {
my ($cmd)=@_;
my @paths=(split(":", $ENV{'PATH'}), "/usr/sbin", "/usr/local/sbin",
"/sbin", "/usr/bin", "/usr/local/bin",
"$LIBDIR/.libs", "$LIBDIR");
for(@paths) {
if( -x "$_/$cmd" && ! -d "$_/$cmd") {
# executable bit but not a directory!
return "$_/$cmd";
}
}
}
#######################################################################
# Get the list of tests that the tests/data/Makefile.am knows about!
#
my $disttests;
sub get_disttests {
open(D, "<$TESTDIR/Makefile.inc");
while(<D>) {
chomp $_;
if(($_ =~ /^#/) ||($_ !~ /test/)) {
next;
}
$disttests .= $_;
}
close(D);
}
#######################################################################
# Check for a command in the PATH of the machine running curl.
#
sub checktestcmd {
my ($cmd)=@_;
return checkcmd($cmd);
}
#######################################################################
# Run the application under test and return its return code
#
sub runclient {
my ($cmd)=@_;
my $ret = system($cmd);
print "CMD ($ret): $cmd\n" if($verbose && !$torture);
return $ret;
# This is one way to test curl on a remote machine
# my $out = system("ssh $CLIENTIP cd \'$pwd\' \\; \'$cmd\'");
# sleep 2; # time to allow the NFS server to be updated
# return $out;
}
#######################################################################
# Run the application under test and return its stdout
#
sub runclientoutput {
my ($cmd)=@_;
return `$cmd`;
# This is one way to test curl on a remote machine
# my @out = `ssh $CLIENTIP cd \'$pwd\' \\; \'$cmd\'`;
# sleep 2; # time to allow the NFS server to be updated
# return @out;
}
#######################################################################
# Memory allocation test and failure torture testing.
#
sub torture {
my ($testcmd, $testnum, $gdbline) = @_;
# remove memdump first to be sure we get a new nice and clean one
unlink($memdump);
# First get URL from test server, ignore the output/result
runclient($testcmd);
logmsg " CMD: $testcmd\n" if($verbose);
# memanalyze -v is our friend, get the number of allocations made
my $count=0;
my @out = `$memanalyze -v $memdump`;
for(@out) {
if(/^Operations: (\d+)/) {
$count = $1;
last;
}
}
if(!$count) {
logmsg " found no functions to make fail\n";
return 0;
}
my @ttests = (1 .. $count);
if($shallow && ($shallow < $count)) {
my $discard = scalar(@ttests) - $shallow;
my $percent = sprintf("%.2f%%", $shallow * 100 / scalar(@ttests));;
logmsg " $count functions found, but only fail $shallow ($percent)\n";
while($discard) {
my $rm;
do {
# find a test to discard
$rm = rand(scalar(@ttests));
} while(!$ttests[$rm]);
$ttests[$rm] = undef;
$discard--;
}
}
else {
logmsg " $count functions to make fail\n";
}
for (@ttests) {
my $limit = $_;
my $fail;
my $dumped_core;
if(!defined($limit)) {
# --shallow can undefine them
next;
}
if($tortalloc && ($tortalloc != $limit)) {
next;
}
if($verbose) {
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
localtime(time());
my $now = sprintf("%02d:%02d:%02d ", $hour, $min, $sec);
logmsg "Fail function no: $limit at $now\r";
}
# make the memory allocation function number $limit return failure
$ENV{'CURL_MEMLIMIT'} = $limit;
# remove memdump first to be sure we get a new nice and clean one
unlink($memdump);
my $cmd = $testcmd;
if($valgrind && !$gdbthis) {
my @valgrindoption = getpart("verify", "valgrind");
if((!@valgrindoption) || ($valgrindoption[0] !~ /disable/)) {
my $valgrindcmd = "$valgrind ";
$valgrindcmd .= "$valgrind_tool " if($valgrind_tool);
$valgrindcmd .= "--quiet --leak-check=yes ";
$valgrindcmd .= "--suppressions=$srcdir/valgrind.supp ";
# $valgrindcmd .= "--gen-suppressions=all ";
$valgrindcmd .= "--num-callers=16 ";
$valgrindcmd .= "${valgrind_logfile}=$LOGDIR/valgrind$testnum";
$cmd = "$valgrindcmd $testcmd";
}
}
logmsg "*** Function number $limit is now set to fail ***\n" if($gdbthis);
my $ret = 0;
if($gdbthis) {
runclient($gdbline);
}
else {
$ret = runclient($cmd);
}
#logmsg "$_ Returned " . ($ret >> 8) . "\n";
# Now clear the variable again
delete $ENV{'CURL_MEMLIMIT'} if($ENV{'CURL_MEMLIMIT'});
if(-r "core") {
# there's core file present now!
logmsg " core dumped\n";
$dumped_core = 1;
$fail = 2;
}
if($valgrind) {
my @e = valgrindparse("$LOGDIR/valgrind$testnum");
if(@e && $e[0]) {
if($automakestyle) {
logmsg "FAIL: torture $testnum - valgrind\n";
}
else {
logmsg " valgrind ERROR ";
logmsg @e;
}
$fail = 1;
}
}
# verify that it returns a proper error code, doesn't leak memory
# and doesn't core dump
if(($ret & 255) || ($ret >> 8) >= 128) {
logmsg " system() returned $ret\n";
$fail=1;
}
else {
my @memdata=`$memanalyze $memdump`;
my $leak=0;
for(@memdata) {
if($_ ne "") {
# well it could be other memory problems as well, but
# we call it leak for short here
$leak=1;
}
}
if($leak) {
logmsg "** MEMORY FAILURE\n";
logmsg @memdata;
logmsg `$memanalyze -l $memdump`;
$fail = 1;
}
}
if($fail) {
logmsg " Failed on function number $limit in test.\n",
" invoke with \"-t$limit\" to repeat this single case.\n";
stopservers($verbose);
return 1;
}
}
logmsg "torture OK\n";
return 0;
}
#######################################################################
# Stop a test server along with pids which aren't in the %run hash yet.
# This also stops all servers which are relative to the given one.
#
sub stopserver {
my ($server, $pidlist) = @_;
#
# kill sockfilter processes for pingpong relative server
#
if($server =~ /^(ftp|imap|pop3|smtp)s?(\d*)(-ipv6|)$/) {
my $proto = $1;
my $idnum = ($2 && ($2 > 1)) ? $2 : 1;
my $ipvnum = ($3 && ($3 =~ /6$/)) ? 6 : 4;
killsockfilters($proto, $ipvnum, $idnum, $verbose);
}
#
# All servers relative to the given one must be stopped also
#
my @killservers;
if($server =~ /^(ftp|http|imap|pop3|smtp)s((\d*)(-ipv6|-unix|))$/) {
# given a stunnel based ssl server, also kill non-ssl underlying one
push @killservers, "${1}${2}";
}
elsif($server =~ /^(ftp|http|imap|pop3|smtp)((\d*)(-ipv6|-unix|))$/) {
# given a non-ssl server, also kill stunnel based ssl piggybacking one
push @killservers, "${1}s${2}";
}
elsif($server =~ /^(socks)((\d*)(-ipv6|))$/) {
# given a socks server, also kill ssh underlying one
push @killservers, "ssh${2}";
}
elsif($server =~ /^(ssh)((\d*)(-ipv6|))$/) {
# given a ssh server, also kill socks piggybacking one
push @killservers, "socks${2}";
}
if($server eq "http") {
# since the http2 server is a proxy that needs to know about the
# dynamic http port it too needs to get restarted when the http server
# is killed
push @killservers, "http/2";
}
push @killservers, $server;
#
# kill given pids and server relative ones clearing them in %run hash
#
foreach my $server (@killservers) {
if($run{$server}) {
# we must prepend a space since $pidlist may already contain a pid
$pidlist .= " $run{$server}";
$run{$server} = 0;
}
$runcert{$server} = 0 if($runcert{$server});
}
killpid($verbose, $pidlist);
#
# cleanup server pid files
#
my $result = 0;
foreach my $server (@killservers) {
my $pidfile = $serverpidfile{$server};
my $pid = processexists($pidfile);
if($pid > 0) {
if($err_unexpected) {
logmsg "ERROR: ";
$result = -1;
}
else {
logmsg "Warning: ";
}
logmsg "$server server unexpectedly alive\n";
killpid($verbose, $pid);
}
unlink($pidfile) if(-f $pidfile);
}
return $result;
}
#######################################################################
# Return flags to let curl use an external HTTP proxy
#
sub getexternalproxyflags {
return " --proxy $proxy_address ";
}
#######################################################################
# Verify that the server that runs on $ip, $port is our server. This also
# implies that we can speak with it, as there might be occasions when the
# server runs fine but we cannot talk to it ("Failed to connect to ::1: Can't
# assign requested address")
#
sub verifyhttp {
my ($proto, $ipvnum, $idnum, $ip, $port_or_path) = @_;
my $server = servername_id($proto, $ipvnum, $idnum);
my $pid = 0;
my $bonus="";
# $port_or_path contains a path for Unix sockets, sws ignores the port
my $port = ($ipvnum eq "unix") ? 80 : $port_or_path;
my $verifyout = "$LOGDIR/".
servername_canon($proto, $ipvnum, $idnum) .'_verify.out';
unlink($verifyout) if(-f $verifyout);
my $verifylog = "$LOGDIR/".
servername_canon($proto, $ipvnum, $idnum) .'_verify.log';
unlink($verifylog) if(-f $verifylog);
if($proto eq "gopher") {
# gopher is funny
$bonus="1/";
}
my $flags = "--max-time $server_response_maxtime ";
$flags .= "--output $verifyout ";
$flags .= "--silent ";
$flags .= "--verbose ";
$flags .= "--globoff ";
$flags .= "--unix-socket '$port_or_path' " if $ipvnum eq "unix";
$flags .= "--insecure " if($proto eq 'https');
if($use_external_proxy) {
$flags .= getexternalproxyflags();
}
$flags .= "\"$proto://$ip:$port/${bonus}verifiedserver\"";
my $cmd = "$VCURL $flags 2>$verifylog";
# verify if our/any server is running on this port
logmsg "RUN: $cmd\n" if($verbose);
my $res = runclient($cmd);
$res >>= 8; # rotate the result
if($res & 128) {
logmsg "RUN: curl command died with a coredump\n";
return -1;
}
if($res && $verbose) {
logmsg "RUN: curl command returned $res\n";
if(open(FILE, "<$verifylog")) {
while(my $string = <FILE>) {
logmsg "RUN: $string" if($string !~ /^([ \t]*)$/);
}
close(FILE);
}
}
my $data;
if(open(FILE, "<$verifyout")) {
while(my $string = <FILE>) {
$data = $string;
last; # only want first line
}
close(FILE);
}
if($data && ($data =~ /WE ROOLZ: (\d+)/)) {
$pid = 0+$1;
}
elsif($res == 6) {
# curl: (6) Couldn't resolve host '::1'
logmsg "RUN: failed to resolve host ($proto://$ip:$port/verifiedserver)\n";
return -1;
}
elsif($data || ($res && ($res != 7))) {
logmsg "RUN: Unknown server on our $server port: $port ($res)\n";
return -1;
}
return $pid;
}
#######################################################################
# Verify that the server that runs on $ip, $port is our server. This also
# implies that we can speak with it, as there might be occasions when the
# server runs fine but we cannot talk to it ("Failed to connect to ::1: Can't
# assign requested address")
#
sub verifyftp {
my ($proto, $ipvnum, $idnum, $ip, $port) = @_;
my $server = servername_id($proto, $ipvnum, $idnum);
my $pid = 0;
my $time=time();
my $extra="";
my $verifylog = "$LOGDIR/".
servername_canon($proto, $ipvnum, $idnum) .'_verify.log';
unlink($verifylog) if(-f $verifylog);
if($proto eq "ftps") {
$extra .= "--insecure --ftp-ssl-control ";
}
my $flags = "--max-time $server_response_maxtime ";
$flags .= "--silent ";
$flags .= "--verbose ";
$flags .= "--globoff ";
$flags .= $extra;
if($use_external_proxy) {
$flags .= getexternalproxyflags();
}
$flags .= "\"$proto://$ip:$port/verifiedserver\"";
my $cmd = "$VCURL $flags 2>$verifylog";
# check if this is our server running on this port:
logmsg "RUN: $cmd\n" if($verbose);
my @data = runclientoutput($cmd);
my $res = $? >> 8; # rotate the result
if($res & 128) {
logmsg "RUN: curl command died with a coredump\n";
return -1;
}
foreach my $line (@data) {
if($line =~ /WE ROOLZ: (\d+)/) {
# this is our test server with a known pid!
$pid = 0+$1;
last;
}
}
if($pid <= 0 && @data && $data[0]) {
# this is not a known server
logmsg "RUN: Unknown server on our $server port: $port\n";
return 0;
}
# we can/should use the time it took to verify the FTP server as a measure
# on how fast/slow this host/FTP is.
my $took = int(0.5+time()-$time);
if($verbose) {
logmsg "RUN: Verifying our test $server server took $took seconds\n";
}
$ftpchecktime = $took>=1?$took:1; # make sure it never is below 1
return $pid;
}
#######################################################################
# Verify that the server that runs on $ip, $port is our server. This also
# implies that we can speak with it, as there might be occasions when the
# server runs fine but we cannot talk to it ("Failed to connect to ::1: Can't
# assign requested address")
#
sub verifyrtsp {
my ($proto, $ipvnum, $idnum, $ip, $port) = @_;
my $server = servername_id($proto, $ipvnum, $idnum);
my $pid = 0;
my $verifyout = "$LOGDIR/".
servername_canon($proto, $ipvnum, $idnum) .'_verify.out';
unlink($verifyout) if(-f $verifyout);
my $verifylog = "$LOGDIR/".
servername_canon($proto, $ipvnum, $idnum) .'_verify.log';
unlink($verifylog) if(-f $verifylog);
my $flags = "--max-time $server_response_maxtime ";
$flags .= "--output $verifyout ";
$flags .= "--silent ";
$flags .= "--verbose ";
$flags .= "--globoff ";
if($use_external_proxy) {
$flags .= getexternalproxyflags();
}
# currently verification is done using http
$flags .= "\"http://$ip:$port/verifiedserver\"";
my $cmd = "$VCURL $flags 2>$verifylog";
# verify if our/any server is running on this port
logmsg "RUN: $cmd\n" if($verbose);
my $res = runclient($cmd);
$res >>= 8; # rotate the result
if($res & 128) {
logmsg "RUN: curl command died with a coredump\n";
return -1;
}
if($res && $verbose) {
logmsg "RUN: curl command returned $res\n";
if(open(FILE, "<$verifylog")) {
while(my $string = <FILE>) {
logmsg "RUN: $string" if($string !~ /^([ \t]*)$/);
}
close(FILE);
}
}
my $data;
if(open(FILE, "<$verifyout")) {
while(my $string = <FILE>) {
$data = $string;
last; # only want first line
}
close(FILE);
}
if($data && ($data =~ /RTSP_SERVER WE ROOLZ: (\d+)/)) {
$pid = 0+$1;
}
elsif($res == 6) {
# curl: (6) Couldn't resolve host '::1'
logmsg "RUN: failed to resolve host ($proto://$ip:$port/verifiedserver)\n";
return -1;
}
elsif($data || ($res != 7)) {
logmsg "RUN: Unknown server on our $server port: $port\n";
return -1;
}
return $pid;
}
#######################################################################
# Verify that the ssh server has written out its pidfile, recovering
# the pid from the file and returning it if a process with that pid is
# actually alive.
#
sub verifyssh {
my ($proto, $ipvnum, $idnum, $ip, $port) = @_;
my $server = servername_id($proto, $ipvnum, $idnum);
my $pidfile = server_pidfilename($proto, $ipvnum, $idnum);
my $pid = 0;
if(open(FILE, "<$pidfile")) {
$pid=0+<FILE>;
close(FILE);
}
if($pid > 0) {
# if we have a pid it is actually our ssh server,
# since runsshserver() unlinks previous pidfile
if(!pidexists($pid)) {
logmsg "RUN: SSH server has died after starting up\n";
checkdied($pid);
unlink($pidfile);
$pid = -1;
}
}
return $pid;
}
#######################################################################
# Verify that we can connect to the sftp server, properly authenticate
# with generated config and key files and run a simple remote pwd.
#
sub verifysftp {
my ($proto, $ipvnum, $idnum, $ip, $port) = @_;
my $server = servername_id($proto, $ipvnum, $idnum);
my $verified = 0;
# Find out sftp client canonical file name
my $sftp = find_sftp();
if(!$sftp) {
logmsg "RUN: SFTP server cannot find $sftpexe\n";
return -1;
}
# Find out ssh client canonical file name
my $ssh = find_ssh();
if(!$ssh) {
logmsg "RUN: SFTP server cannot find $sshexe\n";
return -1;
}
# Connect to sftp server, authenticate and run a remote pwd
# command using our generated configuration and key files
my $cmd = "\"$sftp\" -b $sftpcmds -F $sftpconfig -S \"$ssh\" $ip > $sftplog 2>&1";
my $res = runclient($cmd);
# Search for pwd command response in log file
if(open(SFTPLOGFILE, "<$sftplog")) {
while(<SFTPLOGFILE>) {
if(/^Remote working directory: /) {
$verified = 1;
last;
}
}
close(SFTPLOGFILE);
}
return $verified;
}
#######################################################################
# Verify that the non-stunnel HTTP TLS extensions capable server that runs
# on $ip, $port is our server. This also implies that we can speak with it,
# as there might be occasions when the server runs fine but we cannot talk
# to it ("Failed to connect to ::1: Can't assign requested address")
#
sub verifyhttptls {
my ($proto, $ipvnum, $idnum, $ip, $port) = @_;
my $server = servername_id($proto, $ipvnum, $idnum);
my $pidfile = server_pidfilename($proto, $ipvnum, $idnum);
my $pid = 0;
my $verifyout = "$LOGDIR/".
servername_canon($proto, $ipvnum, $idnum) .'_verify.out';
unlink($verifyout) if(-f $verifyout);
my $verifylog = "$LOGDIR/".
servername_canon($proto, $ipvnum, $idnum) .'_verify.log';
unlink($verifylog) if(-f $verifylog);
my $flags = "--max-time $server_response_maxtime ";
$flags .= "--output $verifyout ";
$flags .= "--verbose ";
$flags .= "--globoff ";
$flags .= "--insecure ";
$flags .= "--tlsauthtype SRP ";
$flags .= "--tlsuser jsmith ";
$flags .= "--tlspassword abc ";
if($use_external_proxy) {
$flags .= getexternalproxyflags();
}
$flags .= "\"https://$ip:$port/verifiedserver\"";
my $cmd = "$VCURL $flags 2>$verifylog";
# verify if our/any server is running on this port
logmsg "RUN: $cmd\n" if($verbose);
my $res = runclient($cmd);
$res >>= 8; # rotate the result
if($res & 128) {
logmsg "RUN: curl command died with a coredump\n";
return -1;
}
if($res && $verbose) {
logmsg "RUN: curl command returned $res\n";
if(open(FILE, "<$verifylog")) {
while(my $string = <FILE>) {
logmsg "RUN: $string" if($string !~ /^([ \t]*)$/);
}
close(FILE);
}
}
my $data;
if(open(FILE, "<$verifyout")) {
while(my $string = <FILE>) {
$data .= $string;
}
close(FILE);
}
if($data && ($data =~ /(GNUTLS|GnuTLS)/) && open(FILE, "<$pidfile")) {
$pid=0+<FILE>;
close(FILE);
if($pid > 0) {
# if we have a pid it is actually our httptls server,
# since runhttptlsserver() unlinks previous pidfile
if(!pidexists($pid)) {
logmsg "RUN: $server server has died after starting up\n";
checkdied($pid);
unlink($pidfile);
$pid = -1;
}
}
return $pid;
}
elsif($res == 6) {
# curl: (6) Couldn't resolve host '::1'
logmsg "RUN: failed to resolve host (https://$ip:$port/verifiedserver)\n";
return -1;
}
elsif($data || ($res && ($res != 7))) {
logmsg "RUN: Unknown server on our $server port: $port ($res)\n";
return -1;
}
return $pid;
}
#######################################################################
# STUB for verifying socks
#
sub verifysocks {
my ($proto, $ipvnum, $idnum, $ip, $port) = @_;
my $server = servername_id($proto, $ipvnum, $idnum);
my $pidfile = server_pidfilename($proto, $ipvnum, $idnum);
my $pid = 0;
if(open(FILE, "<$pidfile")) {
$pid=0+<FILE>;
close(FILE);
}
if($pid > 0) {
# if we have a pid it is actually our socks server,
# since runsocksserver() unlinks previous pidfile
if(!pidexists($pid)) {
logmsg "RUN: SOCKS server has died after starting up\n";
checkdied($pid);
unlink($pidfile);
$pid = -1;
}
}
return $pid;
}
#######################################################################
# Verify that the server that runs on $ip, $port is our server. This also
# implies that we can speak with it, as there might be occasions when the
# server runs fine but we cannot talk to it ("Failed to connect to ::1: Can't
# assign requested address")
#
sub verifysmb {
my ($proto, $ipvnum, $idnum, $ip, $port) = @_;
my $server = servername_id($proto, $ipvnum, $idnum);
my $pid = 0;
my $time=time();
my $extra="";
my $verifylog = "$LOGDIR/".
servername_canon($proto, $ipvnum, $idnum) .'_verify.log';
unlink($verifylog) if(-f $verifylog);
my $flags = "--max-time $server_response_maxtime ";
$flags .= "--silent ";
$flags .= "--verbose ";
$flags .= "--globoff ";
$flags .= "-u 'curltest:curltest' ";
$flags .= $extra;
$flags .= "\"$proto://$ip:$port/SERVER/verifiedserver\"";
my $cmd = "$VCURL $flags 2>$verifylog";
# check if this is our server running on this port:
logmsg "RUN: $cmd\n" if($verbose);
my @data = runclientoutput($cmd);
my $res = $? >> 8; # rotate the result
if($res & 128) {
logmsg "RUN: curl command died with a coredump\n";
return -1;
}
foreach my $line (@data) {
if($line =~ /WE ROOLZ: (\d+)/) {
# this is our test server with a known pid!
$pid = 0+$1;
last;
}
}
if($pid <= 0 && @data && $data[0]) {
# this is not a known server
logmsg "RUN: Unknown server on our $server port: $port\n";
return 0;
}
# we can/should use the time it took to verify the server as a measure
# on how fast/slow this host is.
my $took = int(0.5+time()-$time);
if($verbose) {
logmsg "RUN: Verifying our test $server server took $took seconds\n";
}
$ftpchecktime = $took>=1?$took:1; # make sure it never is below 1
return $pid;
}
#######################################################################
# Verify that the server that runs on $ip, $port is our server. This also
# implies that we can speak with it, as there might be occasions when the
# server runs fine but we cannot talk to it ("Failed to connect to ::1: Can't
# assign requested address")
#
sub verifytelnet {
my ($proto, $ipvnum, $idnum, $ip, $port) = @_;
my $server = servername_id($proto, $ipvnum, $idnum);
my $pid = 0;
my $time=time();
my $extra="";
my $verifylog = "$LOGDIR/".
servername_canon($proto, $ipvnum, $idnum) .'_verify.log';
unlink($verifylog) if(-f $verifylog);
my $flags = "--max-time $server_response_maxtime ";
$flags .= "--silent ";
$flags .= "--verbose ";
$flags .= "--globoff ";
$flags .= "--upload-file - ";
$flags .= $extra;
$flags .= "\"$proto://$ip:$port\"";
my $cmd = "echo 'verifiedserver' | $VCURL $flags 2>$verifylog";
# check if this is our server running on this port:
logmsg "RUN: $cmd\n" if($verbose);
my @data = runclientoutput($cmd);
my $res = $? >> 8; # rotate the result
if($res & 128) {
logmsg "RUN: curl command died with a coredump\n";
return -1;
}
foreach my $line (@data) {
if($line =~ /WE ROOLZ: (\d+)/) {
# this is our test server with a known pid!
$pid = 0+$1;
last;
}
}
if($pid <= 0 && @data && $data[0]) {
# this is not a known server
logmsg "RUN: Unknown server on our $server port: $port\n";
return 0;
}
# we can/should use the time it took to verify the server as a measure
# on how fast/slow this host is.
my $took = int(0.5+time()-$time);
if($verbose) {
logmsg "RUN: Verifying our test $server server took $took seconds\n";
}
return $pid;
}
#######################################################################
# Verify that the server that runs on $ip, $port is our server.
# Retry over several seconds before giving up. The ssh server in
# particular can take a long time to start if it needs to generate
# keys on a slow or loaded host.
#
# Just for convenience, test harness uses 'https' and 'httptls' literals
# as values for 'proto' variable in order to differentiate different
# servers. 'https' literal is used for stunnel based https test servers,
# and 'httptls' is used for non-stunnel https test servers.
#
my %protofunc = ('http' => \&verifyhttp,
'https' => \&verifyhttp,
'rtsp' => \&verifyrtsp,
'ftp' => \&verifyftp,
'pop3' => \&verifyftp,
'imap' => \&verifyftp,
'smtp' => \&verifyftp,
'ftps' => \&verifyftp,
'tftp' => \&verifyftp,
'ssh' => \&verifyssh,
'socks' => \&verifysocks,
'gopher' => \&verifyhttp,
'httptls' => \&verifyhttptls,
'dict' => \&verifyftp,
'smb' => \&verifysmb,
'telnet' => \&verifytelnet);
sub verifyserver {
my ($proto, $ipvnum, $idnum, $ip, $port) = @_;
my $count = 30; # try for this many seconds
my $pid;
while($count--) {
my $fun = $protofunc{$proto};
$pid = &$fun($proto, $ipvnum, $idnum, $ip, $port);
if($pid > 0) {
last;
}
elsif($pid < 0) {
# a real failure, stop trying and bail out
return 0;
}
sleep(1);
}
return $pid;
}
#######################################################################
# Single shot server responsiveness test. This should only be used
# to verify that a server present in %run hash is still functional
#
sub responsiveserver {
my ($proto, $ipvnum, $idnum, $ip, $port) = @_;
my $prev_verbose = $verbose;
$verbose = 0;
my $fun = $protofunc{$proto};
my $pid = &$fun($proto, $ipvnum, $idnum, $ip, $port);
$verbose = $prev_verbose;
if($pid > 0) {
return 1; # responsive
}
my $srvrname = servername_str($proto, $ipvnum, $idnum);
logmsg " server precheck FAILED (unresponsive $srvrname server)\n";
return 0;
}
#######################################################################
# start the http2 server
#
sub runhttp2server {
my ($verbose) = @_;
my $server;
my $srvrname;
my $pidfile;
my $logfile;
my $flags = "";
my $proto="http/2";
my $ipvnum = 4;
my $idnum = 0;
my $exe = "$perl $srcdir/http2-server.pl";
my $verbose_flag = "--verbose ";
$server = servername_id($proto, $ipvnum, $idnum);
$pidfile = $serverpidfile{$server};
# don't retry if the server doesn't work
if ($doesntrun{$pidfile}) {
return (0, 0, 0);
}
my $pid = processexists($pidfile);
if($pid > 0) {
stopserver($server, "$pid");
}
unlink($pidfile) if(-f $pidfile);
$srvrname = servername_str($proto, $ipvnum, $idnum);
$logfile = server_logfilename($LOGDIR, $proto, $ipvnum, $idnum);
$flags .= "--pidfile \"$pidfile\" --logfile \"$logfile\" ";
$flags .= "--connect $HOSTIP:$HTTPPORT ";
$flags .= $verbose_flag if($debugprotocol);
my ($http2pid, $pid2);
my $port = 23113;
for(1 .. 10) {
$port += int(rand(900));
my $aflags = "--port $port $flags";
my $cmd = "$exe $aflags";
($http2pid, $pid2) = startnew($cmd, $pidfile, 15, 0);
if($http2pid <= 0 || !pidexists($http2pid)) {
# it is NOT alive
stopserver($server, "$pid2");
$doesntrun{$pidfile} = 1;
$http2pid = $pid2 = 0;
next;
}
$doesntrun{$pidfile} = 0;
if($verbose) {
logmsg "RUN: $srvrname server PID $http2pid port $port\n";
}
last;
}
logmsg "RUN: failed to start the $srvrname server\n" if(!$http2pid);
return ($http2pid, $pid2, $port);
}
#######################################################################
# start the http server
#
sub runhttpserver {
my ($proto, $verbose, $alt, $port_or_path) = @_;
my $ip = $HOSTIP;
my $ipvnum = 4;
my $idnum = 1;
my $server;
my $srvrname;
my $pidfile;
my $logfile;
my $flags = "";
my $exe = "$perl $srcdir/httpserver.pl";
my $verbose_flag = "--verbose ";
if($alt eq "ipv6") {
# if IPv6, use a different setup
$ipvnum = 6;
$ip = $HOST6IP;
}
elsif($alt eq "proxy") {
# basically the same, but another ID
$idnum = 2;
}
elsif($alt eq "unix") {
# IP (protocol) is mutually exclusive with Unix sockets
$ipvnum = "unix";
}
$server = servername_id($proto, $ipvnum, $idnum);
$pidfile = $serverpidfile{$server};
my $portfile = $serverportfile{$server};
# don't retry if the server doesn't work
if ($doesntrun{$pidfile}) {
return (0, 0, 0);
}
my $pid = processexists($pidfile);
if($pid > 0) {
stopserver($server, "$pid");
}
unlink($pidfile) if(-f $pidfile);
$srvrname = servername_str($proto, $ipvnum, $idnum);
$logfile = server_logfilename($LOGDIR, $proto, $ipvnum, $idnum);
$flags .= "--gopher " if($proto eq "gopher");
$flags .= "--connect $HOSTIP " if($alt eq "proxy");
$flags .= $verbose_flag if($debugprotocol);
$flags .= "--pidfile \"$pidfile\" --logfile \"$logfile\" ";
$flags .= "--portfile $portfile ";
$flags .= "--id $idnum " if($idnum > 1);
if($ipvnum eq "unix") {
$flags .= "--unix-socket '$port_or_path' ";
} else {
$flags .= "--ipv$ipvnum --port 0 ";
}
$flags .= "--srcdir \"$TESTDIR/..\"";
my $cmd = "$exe $flags";
my ($httppid, $pid2) = startnew($cmd, $pidfile, 15, 0);
if($httppid <= 0 || !pidexists($httppid)) {
# it is NOT alive
logmsg "RUN: failed to start the $srvrname server\n";
stopserver($server, "$pid2");
displaylogs($testnumcheck);
$doesntrun{$pidfile} = 1;
return (0, 0, 0);
}
# where is it?
my $port;
if(!$port_or_path) {
$port = $port_or_path = pidfromfile($portfile);
}
# Server is up. Verify that we can speak to it.
my $pid3 = verifyserver($proto, $ipvnum, $idnum, $ip, $port_or_path);
if(!$pid3) {
logmsg "RUN: $srvrname server failed verification\n";
# failed to talk to it properly. Kill the server and return failure
stopserver($server, "$httppid $pid2");
displaylogs($testnumcheck);
$doesntrun{$pidfile} = 1;
return (0, 0, 0);
}
$pid2 = $pid3;
if($verbose) {
logmsg "RUN: $srvrname server is on PID $httppid port $port\n";
}
return ($httppid, $pid2, $port);
}
#######################################################################
# start the https stunnel based server
#
sub runhttpsserver {
my ($verbose, $proto, $proxy, $certfile) = @_;
my $ip = $HOSTIP;
my $ipvnum = 4;
my $idnum = 1;
my $server;
my $srvrname;
my $pidfile;
my $logfile;
my $flags = "";
if($proxy eq "proxy") {
# the https-proxy runs as https2
$idnum = 2;
}
if(!$stunnel) {
return (0, 0, 0);
}
$server = servername_id($proto, $ipvnum, $idnum);
$pidfile = $serverpidfile{$server};
# don't retry if the server doesn't work
if ($doesntrun{$pidfile}) {
return (0, 0, 0);
}
my $pid = processexists($pidfile);
if($pid > 0) {
stopserver($server, "$pid");
}
unlink($pidfile) if(-f $pidfile);
$srvrname = servername_str($proto, $ipvnum, $idnum);
$certfile = 'stunnel.pem' unless($certfile);
$logfile = server_logfilename($LOGDIR, $proto, $ipvnum, $idnum);
$flags .= "--verbose " if($debugprotocol);
$flags .= "--pidfile \"$pidfile\" --logfile \"$logfile\" ";
$flags .= "--id $idnum " if($idnum > 1);
$flags .= "--ipv$ipvnum --proto $proto ";
$flags .= "--certfile \"$certfile\" " if($certfile ne 'stunnel.pem');
$flags .= "--stunnel \"$stunnel\" --srcdir \"$srcdir\" ";
if($proto eq "gophers") {
$flags .= "--connect $GOPHERPORT";
}
elsif(!$proxy) {
$flags .= "--connect $HTTPPORT";
}
else {
# for HTTPS-proxy we connect to the HTTP proxy
$flags .= "--connect $HTTPPROXYPORT";
}
my $pid2;
my $httpspid;
my $port = 24512; # start attempt
for (1 .. 10) {
$port += int(rand(600));
my $options = "$flags --accept $port";
my $cmd = "$perl $srcdir/secureserver.pl $options";
($httpspid, $pid2) = startnew($cmd, $pidfile, 15, 0);
if($httpspid <= 0 || !pidexists($httpspid)) {
# it is NOT alive
stopserver($server, "$pid2");
displaylogs($testnumcheck);
$doesntrun{$pidfile} = 1;
$httpspid = $pid2 = 0;
next;
}
# we have a server!
if($verbose) {
logmsg "RUN: $srvrname server is PID $httpspid port $port\n";
}
last;
}
$runcert{$server} = $certfile;
logmsg "RUN: failed to start the $srvrname server\n" if(!$httpspid);
return ($httpspid, $pid2, $port);
}
#######################################################################
# start the non-stunnel HTTP TLS extensions capable server
#
sub runhttptlsserver {
my ($verbose, $ipv6) = @_;
my $proto = "httptls";
my $ip = ($ipv6 && ($ipv6 =~ /6$/)) ? "$HOST6IP" : "$HOSTIP";
my $ipvnum = ($ipv6 && ($ipv6 =~ /6$/)) ? 6 : 4;
my $idnum = 1;
my $server;
my $srvrname;
my $pidfile;
my $logfile;
my $flags = "";
if(!$httptlssrv) {
return (0,0);
}
$server = servername_id($proto, $ipvnum, $idnum);
$pidfile = $serverpidfile{$server};
# don't retry if the server doesn't work
if ($doesntrun{$pidfile}) {
return (0, 0, 0);
}
my $pid = processexists($pidfile);
if($pid > 0) {
stopserver($server, "$pid");
}
unlink($pidfile) if(-f $pidfile);
$srvrname = servername_str($proto, $ipvnum, $idnum);
$logfile = server_logfilename($LOGDIR, $proto, $ipvnum, $idnum);
$flags .= "--http ";
$flags .= "--debug 1 " if($debugprotocol);
$flags .= "--priority NORMAL:+SRP ";
$flags .= "--srppasswd $srcdir/certs/srp-verifier-db ";
$flags .= "--srppasswdconf $srcdir/certs/srp-verifier-conf";
my $port = 24367;
my ($httptlspid, $pid2);
for (1 .. 10) {
$port += int(rand(800));
my $allflags = "--port $port $flags";
my $cmd = "$httptlssrv $allflags > $logfile 2>&1";
($httptlspid, $pid2) = startnew($cmd, $pidfile, 10, 1);
if($httptlspid <= 0 || !pidexists($httptlspid)) {
# it is NOT alive
stopserver($server, "$pid2");
displaylogs($testnumcheck);
$doesntrun{$pidfile} = 1;
$httptlspid = $pid2 = 0;
next;
}
$doesntrun{$pidfile} = 0;
if($verbose) {
logmsg "RUN: $srvrname server PID $httptlspid port $port\n";
}
last;
}
logmsg "RUN: failed to start the $srvrname server\n" if(!$httptlspid);
return ($httptlspid, $pid2, $port);
}
#######################################################################
# start the pingpong server (FTP, POP3, IMAP, SMTP)
#
sub runpingpongserver {
my ($proto, $id, $verbose, $ipv6) = @_;
my $port;
my $ip = ($ipv6 && ($ipv6 =~ /6$/)) ? "$HOST6IP" : "$HOSTIP";
my $ipvnum = ($ipv6 && ($ipv6 =~ /6$/)) ? 6 : 4;
my $idnum = ($id && ($id =~ /^(\d+)$/) && ($id > 1)) ? $id : 1;
my $server;
my $srvrname;
my $pidfile;
my $logfile;
my $flags = "";
$server = servername_id($proto, $ipvnum, $idnum);
$pidfile = $serverpidfile{$server};
my $portfile = $serverportfile{$server};
# don't retry if the server doesn't work
if ($doesntrun{$pidfile}) {
return (0,0);
}
my $pid = processexists($pidfile);
if($pid > 0) {
stopserver($server, "$pid");
}
unlink($pidfile) if(-f $pidfile);
$srvrname = servername_str($proto, $ipvnum, $idnum);
$logfile = server_logfilename($LOGDIR, $proto, $ipvnum, $idnum);
$flags .= "--verbose " if($debugprotocol);
$flags .= "--pidfile \"$pidfile\" --logfile \"$logfile\" ";
$flags .= "--portfile \"$portfile\" ";
$flags .= "--srcdir \"$srcdir\" --proto $proto ";
$flags .= "--id $idnum " if($idnum > 1);
$flags .= "--ipv$ipvnum --port 0 --addr \"$ip\"";
my $cmd = "$perl $srcdir/ftpserver.pl $flags";
my ($ftppid, $pid2) = startnew($cmd, $pidfile, 15, 0);
if($ftppid <= 0 || !pidexists($ftppid)) {
# it is NOT alive
logmsg "RUN: failed to start the $srvrname server\n";
stopserver($server, "$pid2");
displaylogs($testnumcheck);
$doesntrun{$pidfile} = 1;
return (0,0);
}
# where is it?
$port = pidfromfile($portfile);
logmsg "PINGPONG runs on port $port ($portfile)\n" if($verbose);
# Server is up. Verify that we can speak to it.
my $pid3 = verifyserver($proto, $ipvnum, $idnum, $ip, $port);
if(!$pid3) {
logmsg "RUN: $srvrname server failed verification\n";
# failed to talk to it properly. Kill the server and return failure
stopserver($server, "$ftppid $pid2");
displaylogs($testnumcheck);
$doesntrun{$pidfile} = 1;
return (0,0);
}
$pid2 = $pid3;
logmsg "RUN: $srvrname server is PID $ftppid port $port\n" if($verbose);
# Assign the correct port variable!
if($proto eq "ftp") {
if($ipvnum == 6) {
# if IPv6, use a different setup
$FTP6PORT = $port;
}
else {
$FTPPORT = $port;
}
}
elsif($proto eq "pop3") {
if($ipvnum == 6) {
$POP36PORT = $port;
}
else {
$POP3PORT = $port;
}
}
elsif($proto eq "imap") {
if($ipvnum == 6) {
$IMAP6PORT = $port;
}
else {
$IMAPPORT = $port;
}
}
elsif($proto eq "smtp") {
if($ipvnum == 6) {
$SMTP6PORT = $port;
}
else {
$SMTPPORT = $port;
}
}
else {
print STDERR "Unsupported protocol $proto!!\n";
return (0,0);
}
return ($pid2, $ftppid);
}
#######################################################################
# start the ftps server (or rather, tunnel)
#
sub runftpsserver {
my ($verbose, $ipv6, $certfile) = @_;
my $proto = 'ftps';
my $ip = ($ipv6 && ($ipv6 =~ /6$/)) ? "$HOST6IP" : "$HOSTIP";
my $ipvnum = ($ipv6 && ($ipv6 =~ /6$/)) ? 6 : 4;
my $idnum = 1;
my $server;
my $srvrname;
my $pidfile;
my $logfile;
my $flags = "";
if(!$stunnel) {
return (0,0);
}
$server = servername_id($proto, $ipvnum, $idnum);
$pidfile = $serverpidfile{$server};
# don't retry if the server doesn't work
if ($doesntrun{$pidfile}) {
return (0, 0, 0);
}
my $pid = processexists($pidfile);
if($pid > 0) {
stopserver($server, "$pid");
}
unlink($pidfile) if(-f $pidfile);
$srvrname = servername_str($proto, $ipvnum, $idnum);
$certfile = 'stunnel.pem' unless($certfile);
$logfile = server_logfilename($LOGDIR, $proto, $ipvnum, $idnum);
$flags .= "--verbose " if($debugprotocol);
$flags .= "--pidfile \"$pidfile\" --logfile \"$logfile\" ";
$flags .= "--id $idnum " if($idnum > 1);
$flags .= "--ipv$ipvnum --proto $proto ";
$flags .= "--certfile \"$certfile\" " if($certfile ne 'stunnel.pem');
$flags .= "--stunnel \"$stunnel\" --srcdir \"$srcdir\" ";
$flags .= "--connect $FTPPORT";
my $ftpspid;
my $pid2;
my $port = 26713;
for (1 .. 10) {
$port += int(rand(700));
my $options = "$flags --accept $port";
my $cmd = "$perl $srcdir/secureserver.pl $options";
($ftpspid, $pid2) = startnew($cmd, $pidfile, 15, 0);
if($ftpspid <= 0 || !pidexists($ftpspid)) {
# it is NOT alive
stopserver($server, "$pid2");
displaylogs($testnumcheck);
$doesntrun{$pidfile} = 1;
$ftpspid = $pid2 = 0;
next;
}
$doesntrun{$pidfile} = 0;
$runcert{$server} = $certfile;
if($verbose) {
logmsg "RUN: $srvrname server is PID $ftpspid port $port\n";
}
last;
}
logmsg "RUN: failed to start the $srvrname server\n" if(!$ftpspid);
return ($ftpspid, $pid2, $port);
}
#######################################################################
# start the tftp server
#
sub runtftpserver {
my ($id, $verbose, $ipv6) = @_;
my $ip = $HOSTIP;
my $proto = 'tftp';
my $ipvnum = 4;
my $idnum = ($id && ($id =~ /^(\d+)$/) && ($id > 1)) ? $id : 1;
my $server;
my $srvrname;
my $pidfile;
my $logfile;
my $flags = "";
if($ipv6) {
# if IPv6, use a different setup
$ipvnum = 6;
$ip = $HOST6IP;
}
$server = servername_id($proto, $ipvnum, $idnum);
$pidfile = $serverpidfile{$server};
my $portfile = $serverportfile{$server};
# don't retry if the server doesn't work
if ($doesntrun{$pidfile}) {
return (0, 0, 0);
}
my $pid = processexists($pidfile);
if($pid > 0) {
stopserver($server, "$pid");
}
unlink($pidfile) if(-f $pidfile);
$srvrname = servername_str($proto, $ipvnum, $idnum);
$logfile = server_logfilename($LOGDIR, $proto, $ipvnum, $idnum);
$flags .= "--verbose " if($debugprotocol);
$flags .= "--pidfile \"$pidfile\" ".
"--portfile \"$portfile\" ".
"--logfile \"$logfile\" ";
$flags .= "--id $idnum " if($idnum > 1);
$flags .= "--ipv$ipvnum --port 0 --srcdir \"$srcdir\"";
my $cmd = "$perl $srcdir/tftpserver.pl $flags";
my ($tftppid, $pid2) = startnew($cmd, $pidfile, 15, 0);
if($tftppid <= 0 || !pidexists($tftppid)) {
# it is NOT alive
logmsg "RUN: failed to start the $srvrname server\n";
stopserver($server, "$pid2");
displaylogs($testnumcheck);
$doesntrun{$pidfile} = 1;
return (0, 0, 0);
}
my $port = pidfromfile($portfile);
# Server is up. Verify that we can speak to it.
my $pid3 = verifyserver($proto, $ipvnum, $idnum, $ip, $port);
if(!$pid3) {
logmsg "RUN: $srvrname server failed verification\n";
# failed to talk to it properly. Kill the server and return failure
stopserver($server, "$tftppid $pid2");
displaylogs($testnumcheck);
$doesntrun{$pidfile} = 1;
return (0, 0, 0);
}
$pid2 = $pid3;
if($verbose) {
logmsg "RUN: $srvrname server on PID $tftppid port $port\n";
}
return ($pid2, $tftppid, $port);
}
#######################################################################
# start the rtsp server
#
sub runrtspserver {
my ($verbose, $ipv6) = @_;
my $ip = $HOSTIP;
my $proto = 'rtsp';
my $ipvnum = 4;
my $idnum = 1;
my $server;
my $srvrname;
my $pidfile;
my $logfile;
my $flags = "";
if($ipv6) {
# if IPv6, use a different setup
$ipvnum = 6;
$ip = $HOST6IP;
}
$server = servername_id($proto, $ipvnum, $idnum);
$pidfile = $serverpidfile{$server};
my $portfile = $serverportfile{$server};
# don't retry if the server doesn't work
if ($doesntrun{$pidfile}) {
return (0, 0, 0);
}
my $pid = processexists($pidfile);
if($pid > 0) {
stopserver($server, "$pid");
}
unlink($pidfile) if(-f $pidfile);
$srvrname = servername_str($proto, $ipvnum, $idnum);
$logfile = server_logfilename($LOGDIR, $proto, $ipvnum, $idnum);
$flags .= "--verbose " if($debugprotocol);
$flags .= "--pidfile \"$pidfile\" ".
"--portfile \"$portfile\" ".
"--logfile \"$logfile\" ";
$flags .= "--id $idnum " if($idnum > 1);
$flags .= "--ipv$ipvnum --port 0 --srcdir \"$srcdir\"";
my $cmd = "$perl $srcdir/rtspserver.pl $flags";
my ($rtsppid, $pid2) = startnew($cmd, $pidfile, 15, 0);
if($rtsppid <= 0 || !pidexists($rtsppid)) {
# it is NOT alive
logmsg "RUN: failed to start the $srvrname server\n";
stopserver($server, "$pid2");
displaylogs($testnumcheck);
$doesntrun{$pidfile} = 1;
return (0, 0, 0);
}
my $port = pidfromfile($portfile);
# Server is up. Verify that we can speak to it.
my $pid3 = verifyserver($proto, $ipvnum, $idnum, $ip, $port);
if(!$pid3) {
logmsg "RUN: $srvrname server failed verification\n";
# failed to talk to it properly. Kill the server and return failure
stopserver($server, "$rtsppid $pid2");
displaylogs($testnumcheck);
$doesntrun{$pidfile} = 1;
return (0, 0, 0);
}
$pid2 = $pid3;
if($verbose) {
logmsg "RUN: $srvrname server PID $rtsppid port $port\n";
}
return ($rtsppid, $pid2, $port);
}
#######################################################################
# Start the ssh (scp/sftp) server
#
sub runsshserver {
my ($id, $verbose, $ipv6) = @_;
my $ip=$HOSTIP;
my $proto = 'ssh';
my $ipvnum = 4;
my $idnum = ($id && ($id =~ /^(\d+)$/) && ($id > 1)) ? $id : 1;
my $server;
my $srvrname;
my $pidfile;
my $logfile;
my $port = 20000; # no lower port
$server = servername_id($proto, $ipvnum, $idnum);
$pidfile = $serverpidfile{$server};
# don't retry if the server doesn't work
if ($doesntrun{$pidfile}) {
return (0, 0, 0);
}
my $sshd = find_sshd();
if($sshd) {
($sshdid,$sshdvernum,$sshdverstr,$sshderror) = sshversioninfo($sshd);
}
my $pid = processexists($pidfile);
if($pid > 0) {
stopserver($server, "$pid");
}
unlink($pidfile) if(-f $pidfile);
$srvrname = servername_str($proto, $ipvnum, $idnum);
$logfile = server_logfilename($LOGDIR, $proto, $ipvnum, $idnum);
my $flags = "";
$flags .= "--verbose " if($verbose);
$flags .= "--debugprotocol " if($debugprotocol);
$flags .= "--pidfile \"$pidfile\" ";
$flags .= "--id $idnum " if($idnum > 1);
$flags .= "--ipv$ipvnum --addr \"$ip\" ";
$flags .= "--user \"$USER\"";
my $sshpid;
my $pid2;
my $wport = 0,
my @tports;
for(1 .. 10) {
# sshd doesn't have a way to pick an unused random port number, so
# instead we iterate over possible port numbers to use until we find
# one that works
$port += int(rand(500));
push @tports, $port;
my $options = "$flags --sshport $port";
my $cmd = "$perl $srcdir/sshserver.pl $options";
($sshpid, $pid2) = startnew($cmd, $pidfile, 60, 0);
# on loaded systems sshserver start up can take longer than the
# timeout passed to startnew, when this happens startnew completes
# without being able to read the pidfile and consequently returns a
# zero pid2 above.
if($sshpid <= 0 || !pidexists($sshpid)) {
# it is NOT alive
stopserver($server, "$pid2");
$doesntrun{$pidfile} = 1;
$sshpid = $pid2 = 0;
next;
}
# once it is known that the ssh server is alive, sftp server
# verification is performed actually connecting to it, authenticating
# and performing a very simple remote command. This verification is
# tried only one time.
$sshdlog = server_logfilename($LOGDIR, 'ssh', $ipvnum, $idnum);
$sftplog = server_logfilename($LOGDIR, 'sftp', $ipvnum, $idnum);
if(verifysftp('sftp', $ipvnum, $idnum, $ip, $port) < 1) {
logmsg "RUN: SFTP server failed verification\n";
# failed to talk to it properly. Kill the server and return failure
display_sftplog();
display_sftpconfig();
display_sshdlog();
display_sshdconfig();
stopserver($server, "$sshpid $pid2");
$doesntrun{$pidfile} = 1;
$sshpid = $pid2 = 0;
next;
}
# we're happy, no need to loop anymore!
$doesntrun{$pidfile} = 0;
$wport = $port;
last;
}
logmsg "RUN: failed to start the $srvrname server on $port\n" if(!$sshpid);
if(!$wport) {
logmsg "RUN: couldn't start $srvrname. Tried these ports:";
logmsg "RUN: ".join(", ", @tports);
return (0,0,0);
}
my $hstpubmd5f = "curl_host_rsa_key.pub_md5";
if(!open(PUBMD5FILE, "<", $hstpubmd5f) ||
(read(PUBMD5FILE, $SSHSRVMD5, 32) != 32) ||
!close(PUBMD5FILE) ||
($SSHSRVMD5 !~ /^[a-f0-9]{32}$/i))
{
my $msg = "Fatal: $srvrname pubkey md5 missing : \"$hstpubmd5f\" : $!";
logmsg "$msg\n";
stopservers($verbose);
die $msg;
}
my $hstpubsha256f = "curl_host_rsa_key.pub_sha256";
if(!open(PUBSHA256FILE, "<", $hstpubsha256f) ||
(read(PUBSHA256FILE, $SSHSRVSHA256, 48) == 0) ||
!close(PUBSHA256FILE))
{
my $msg = "Fatal: $srvrname pubkey sha256 missing : \"$hstpubsha256f\" : $!";
logmsg "$msg\n";
stopservers($verbose);
die $msg;
}
logmsg "RUN: $srvrname on PID $pid2 port $wport\n" if($verbose);
return ($pid2, $sshpid, $wport);
}
#######################################################################
# Start the MQTT server
#
sub runmqttserver {
my ($id, $verbose, $ipv6) = @_;
my $ip=$HOSTIP;
my $port = $MQTTPORT;
my $proto = 'mqtt';
my $ipvnum = 4;
my $idnum = ($id && ($id =~ /^(\d+)$/) && ($id > 1)) ? $id : 1;
my $server;
my $srvrname;
my $pidfile;
my $portfile;
my $logfile;
my $flags = "";
$server = servername_id($proto, $ipvnum, $idnum);
$pidfile = $serverpidfile{$server};
$portfile = $serverportfile{$server};
# don't retry if the server doesn't work
if ($doesntrun{$pidfile}) {
return (0,0);
}
my $pid = processexists($pidfile);
if($pid > 0) {
stopserver($server, "$pid");
}
unlink($pidfile) if(-f $pidfile);
$srvrname = servername_str($proto, $ipvnum, $idnum);
$logfile = server_logfilename($LOGDIR, $proto, $ipvnum, $idnum);
# start our MQTT server - on a random port!
my $cmd="server/mqttd".exe_ext('SRV').
" --port 0 ".
" --pidfile $pidfile".
" --portfile $portfile".
" --config $FTPDCMD";
my ($sockspid, $pid2) = startnew($cmd, $pidfile, 30, 0);
if($sockspid <= 0 || !pidexists($sockspid)) {
# it is NOT alive
logmsg "RUN: failed to start the $srvrname server\n";
stopserver($server, "$pid2");
$doesntrun{$pidfile} = 1;
return (0,0);
}
$MQTTPORT = pidfromfile($portfile);
if($verbose) {
logmsg "RUN: $srvrname server is now running PID $pid2 on PORT $MQTTPORT\n";
}
return ($pid2, $sockspid);
}
#######################################################################
# Start the socks server
#
sub runsocksserver {
my ($id, $verbose, $ipv6) = @_;
my $ip=$HOSTIP;
my $proto = 'socks';
my $ipvnum = 4;
my $idnum = ($id && ($id =~ /^(\d+)$/) && ($id > 1)) ? $id : 1;
my $server;
my $srvrname;
my $pidfile;
my $logfile;
my $flags = "";
$server = servername_id($proto, $ipvnum, $idnum);
$pidfile = $serverpidfile{$server};
my $portfile = $serverportfile{$server};
# don't retry if the server doesn't work
if ($doesntrun{$pidfile}) {
return (0, 0, 0);
}
my $pid = processexists($pidfile);
if($pid > 0) {
stopserver($server, "$pid");
}
unlink($pidfile) if(-f $pidfile);
$srvrname = servername_str($proto, $ipvnum, $idnum);
$logfile = server_logfilename($LOGDIR, $proto, $ipvnum, $idnum);
# start our socks server, get commands from the FTP cmd file
my $cmd="server/socksd".exe_ext('SRV').
" --port 0 ".
" --pidfile $pidfile".
" --portfile $portfile".
" --backend $HOSTIP".
" --config $FTPDCMD";
my ($sockspid, $pid2) = startnew($cmd, $pidfile, 30, 0);
if($sockspid <= 0 || !pidexists($sockspid)) {
# it is NOT alive
logmsg "RUN: failed to start the $srvrname server\n";
stopserver($server, "$pid2");
$doesntrun{$pidfile} = 1;
return (0, 0, 0);
}
my $port = pidfromfile($portfile);
if($verbose) {
logmsg "RUN: $srvrname server is now running PID $pid2\n";
}
return ($pid2, $sockspid, $port);
}
#######################################################################
# start the dict server
#
sub rundictserver {
my ($verbose, $alt) = @_;
my $proto = "dict";
my $ip = $HOSTIP;
my $ipvnum = 4;
my $idnum = 1;
my $server;
my $srvrname;
my $pidfile;
my $logfile;
my $flags = "";
if($alt eq "ipv6") {
# No IPv6
}
$server = servername_id($proto, $ipvnum, $idnum);
$pidfile = $serverpidfile{$server};
# don't retry if the server doesn't work
if ($doesntrun{$pidfile}) {
return (0, 0, 0);
}
my $pid = processexists($pidfile);
if($pid > 0) {
stopserver($server, "$pid");
}
unlink($pidfile) if(-f $pidfile);
$srvrname = servername_str($proto, $ipvnum, $idnum);
$logfile = server_logfilename($LOGDIR, $proto, $ipvnum, $idnum);
$flags .= "--verbose 1 " if($debugprotocol);
$flags .= "--pidfile \"$pidfile\" --logfile \"$logfile\" ";
$flags .= "--id $idnum " if($idnum > 1);
$flags .= "--srcdir \"$srcdir\" ";
$flags .= "--host $HOSTIP";
my $port = 29000;
my ($dictpid, $pid2);
for(1 .. 10) {
$port += int(rand(900));
my $aflags = "--port $port $flags";
my $cmd = "$srcdir/dictserver.py $aflags";
($dictpid, $pid2) = startnew($cmd, $pidfile, 15, 0);
if($dictpid <= 0 || !pidexists($dictpid)) {
# it is NOT alive
stopserver($server, "$pid2");
displaylogs($testnumcheck);
$doesntrun{$pidfile} = 1;
$dictpid = $pid2 = 0;
next;
}
$doesntrun{$pidfile} = 0;
if($verbose) {
logmsg "RUN: $srvrname server PID $dictpid port $port\n";
}
last;
}
logmsg "RUN: failed to start the $srvrname server\n" if(!$dictpid);
return ($dictpid, $pid2, $port);
}
#######################################################################
# start the SMB server
#
sub runsmbserver {
my ($verbose, $alt) = @_;
my $proto = "smb";
my $ip = $HOSTIP;
my $ipvnum = 4;
my $idnum = 1;
my $server;
my $srvrname;
my $pidfile;
my $logfile;
my $flags = "";
if($alt eq "ipv6") {
# No IPv6
}
$server = servername_id($proto, $ipvnum, $idnum);
$pidfile = $serverpidfile{$server};
# don't retry if the server doesn't work
if ($doesntrun{$pidfile}) {
return (0, 0, 0);
}
my $pid = processexists($pidfile);
if($pid > 0) {
stopserver($server, "$pid");
}
unlink($pidfile) if(-f $pidfile);
$srvrname = servername_str($proto, $ipvnum, $idnum);
$logfile = server_logfilename($LOGDIR, $proto, $ipvnum, $idnum);
$flags .= "--verbose 1 " if($debugprotocol);
$flags .= "--pidfile \"$pidfile\" --logfile \"$logfile\" ";
$flags .= "--id $idnum " if($idnum > 1);
$flags .= "--srcdir \"$srcdir\" ";
$flags .= "--host $HOSTIP";
my ($smbpid, $pid2);
my $port = 31923;
for(1 .. 10) {
$port += int(rand(760));
my $aflags = "--port $port $flags";
my $cmd = "$srcdir/smbserver.py $aflags";
($smbpid, $pid2) = startnew($cmd, $pidfile, 15, 0);
if($smbpid <= 0 || !pidexists($smbpid)) {
# it is NOT alive
stopserver($server, "$pid2");
displaylogs($testnumcheck);
$doesntrun{$pidfile} = 1;
$smbpid = $pid2 = 0;
next;
}
$doesntrun{$pidfile} = 0;
if($verbose) {
logmsg "RUN: $srvrname server PID $smbpid port $port\n";
}
last;
}
logmsg "RUN: failed to start the $srvrname server\n" if(!$smbpid);
return ($smbpid, $pid2, $port);
}
#######################################################################
# start the telnet server
#
sub runnegtelnetserver {
my ($verbose, $alt) = @_;
my $proto = "telnet";
my $ip = $HOSTIP;
my $ipvnum = 4;
my $idnum = 1;
my $server;
my $srvrname;
my $pidfile;
my $logfile;
my $flags = "";
if($alt eq "ipv6") {
# No IPv6
}
$server = servername_id($proto, $ipvnum, $idnum);
$pidfile = $serverpidfile{$server};
# don't retry if the server doesn't work
if ($doesntrun{$pidfile}) {
return (0, 0, 0);
}
my $pid = processexists($pidfile);
if($pid > 0) {
stopserver($server, "$pid");
}
unlink($pidfile) if(-f $pidfile);
$srvrname = servername_str($proto, $ipvnum, $idnum);
$logfile = server_logfilename($LOGDIR, $proto, $ipvnum, $idnum);
$flags .= "--verbose 1 " if($debugprotocol);
$flags .= "--pidfile \"$pidfile\" --logfile \"$logfile\" ";
$flags .= "--id $idnum " if($idnum > 1);
$flags .= "--srcdir \"$srcdir\"";
my ($ntelpid, $pid2);
my $port = 32000;
for(1 .. 10) {
$port += int(rand(800));
my $aflags = "--port $port $flags";
my $cmd = "$srcdir/negtelnetserver.py $aflags";
($ntelpid, $pid2) = startnew($cmd, $pidfile, 15, 0);
if($ntelpid <= 0 || !pidexists($ntelpid)) {
# it is NOT alive
stopserver($server, "$pid2");
displaylogs($testnumcheck);
$doesntrun{$pidfile} = 1;
$ntelpid = $pid2 = 0;
next;
}
$doesntrun{$pidfile} = 0;
if($verbose) {
logmsg "RUN: $srvrname server PID $ntelpid port $port\n";
}
last;
}
logmsg "RUN: failed to start the $srvrname server\n" if(!$ntelpid);
return ($ntelpid, $pid2, $port);
}
#######################################################################
# Single shot http and gopher server responsiveness test. This should only
# be used to verify that a server present in %run hash is still functional
#
sub responsive_http_server {
my ($proto, $verbose, $alt, $port_or_path) = @_;
my $ip = $HOSTIP;
my $ipvnum = 4;
my $idnum = 1;
if($alt eq "ipv6") {
# if IPv6, use a different setup
$ipvnum = 6;
$ip = $HOST6IP;
}
elsif($alt eq "proxy") {
$idnum = 2;
}
elsif($alt eq "unix") {
# IP (protocol) is mutually exclusive with Unix sockets
$ipvnum = "unix";
}
return &responsiveserver($proto, $ipvnum, $idnum, $ip, $port_or_path);
}
#######################################################################
# Single shot pingpong server responsiveness test. This should only be
# used to verify that a server present in %run hash is still functional
#
sub responsive_pingpong_server {
my ($proto, $id, $verbose, $ipv6) = @_;
my $port;
my $ip = ($ipv6 && ($ipv6 =~ /6$/)) ? "$HOST6IP" : "$HOSTIP";
my $ipvnum = ($ipv6 && ($ipv6 =~ /6$/)) ? 6 : 4;
my $idnum = ($id && ($id =~ /^(\d+)$/) && ($id > 1)) ? $id : 1;
if($proto eq "ftp") {
$port = $FTPPORT;
if($ipvnum==6) {
# if IPv6, use a different setup
$port = $FTP6PORT;
}
}
elsif($proto eq "pop3") {
$port = ($ipvnum==6) ? $POP36PORT : $POP3PORT;
}
elsif($proto eq "imap") {
$port = ($ipvnum==6) ? $IMAP6PORT : $IMAPPORT;
}
elsif($proto eq "smtp") {
$port = ($ipvnum==6) ? $SMTP6PORT : $SMTPPORT;
}
else {
print STDERR "Unsupported protocol $proto!!\n";
return 0;
}
return &responsiveserver($proto, $ipvnum, $idnum, $ip, $port);
}
#######################################################################
# Single shot rtsp server responsiveness test. This should only be
# used to verify that a server present in %run hash is still functional
#
sub responsive_rtsp_server {
my ($verbose, $ipv6) = @_;
my $port = $RTSPPORT;
my $ip = $HOSTIP;
my $proto = 'rtsp';
my $ipvnum = 4;
my $idnum = 1;
if($ipv6) {
# if IPv6, use a different setup
$ipvnum = 6;
$port = $RTSP6PORT;
$ip = $HOST6IP;
}
return &responsiveserver($proto, $ipvnum, $idnum, $ip, $port);
}
#######################################################################
# Single shot tftp server responsiveness test. This should only be
# used to verify that a server present in %run hash is still functional
#
sub responsive_tftp_server {
my ($id, $verbose, $ipv6) = @_;
my $port = $TFTPPORT;
my $ip = $HOSTIP;
my $proto = 'tftp';
my $ipvnum = 4;
my $idnum = ($id && ($id =~ /^(\d+)$/) && ($id > 1)) ? $id : 1;
if($ipv6) {
# if IPv6, use a different setup
$ipvnum = 6;
$port = $TFTP6PORT;
$ip = $HOST6IP;
}
return &responsiveserver($proto, $ipvnum, $idnum, $ip, $port);
}
#######################################################################
# Single shot non-stunnel HTTP TLS extensions capable server
# responsiveness test. This should only be used to verify that a
# server present in %run hash is still functional
#
sub responsive_httptls_server {
my ($verbose, $ipv6) = @_;
my $proto = "httptls";
my $port = ($ipv6 && ($ipv6 =~ /6$/)) ? $HTTPTLS6PORT : $HTTPTLSPORT;
my $ip = ($ipv6 && ($ipv6 =~ /6$/)) ? "$HOST6IP" : "$HOSTIP";
my $ipvnum = ($ipv6 && ($ipv6 =~ /6$/)) ? 6 : 4;
my $idnum = 1;
return &responsiveserver($proto, $ipvnum, $idnum, $ip, $port);
}
#######################################################################
# Kill the processes that still lock files in a directory
#
sub clearlocks {
my $dir = $_[0];
my $done = 0;
if(pathhelp::os_is_win()) {
$dir = pathhelp::sys_native_abs_path($dir);
$dir =~ s/\//\\\\/g;
my $handle = "handle.exe";
if($ENV{"PROCESSOR_ARCHITECTURE"} =~ /64$/) {
$handle = "handle64.exe";
}
my @handles = `$handle $dir -accepteula -nobanner`;
for $handle (@handles) {
if($handle =~ /^(\S+)\s+pid:\s+(\d+)\s+type:\s+(\w+)\s+([0-9A-F]+):\s+(.+)\r\r/) {
logmsg "Found $3 lock of '$5' ($4) by $1 ($2)\n";
# Ignore stunnel since we cannot do anything about its locks
if("$3" eq "File" && "$1" ne "tstunnel.exe") {
logmsg "Killing IMAGENAME eq $1 and PID eq $2\n";
system("taskkill.exe -f -fi \"IMAGENAME eq $1\" -fi \"PID eq $2\" >nul 2>&1");
$done = 1;
}
}
}
}
return $done;
}
#######################################################################
# Remove all files in the specified directory
#
sub cleardir {
my $dir = $_[0];
my $done = 1;
my $file;
# Get all files
opendir(my $dh, $dir) ||
return 0; # can't open dir
while($file = readdir($dh)) {
if(($file !~ /^(\.|\.\.)\z/)) {
if(-d "$dir/$file") {
if(!cleardir("$dir/$file")) {
$done = 0;
}
if(!rmdir("$dir/$file")) {
$done = 0;
}
}
else {
# Ignore stunnel since we cannot do anything about its locks
if(!unlink("$dir/$file") && "$file" !~ /_stunnel\.log$/) {
$done = 0;
}
}
}
}
closedir $dh;
return $done;
}
#######################################################################
# compare test results with the expected output, we might filter off
# some pattern that is allowed to differ, output test results
#
sub compare {
my ($testnum, $testname, $subject, $firstref, $secondref)=@_;
my $result = compareparts($firstref, $secondref);
if($result) {
# timestamp test result verification end
$timevrfyend{$testnum} = Time::HiRes::time();
if(!$short) {
logmsg "\n $testnum: $subject FAILED:\n";
logmsg showdiff($LOGDIR, $firstref, $secondref);
}
elsif(!$automakestyle) {
logmsg "FAILED\n";
}
else {
# automakestyle
logmsg "FAIL: $testnum - $testname - $subject\n";
}
}
return $result;
}
sub setupfeatures {
$feature{"hyper"} = $has_hyper;
$feature{"c-ares"} = $has_cares;
$feature{"alt-svc"} = $has_altsvc;
$feature{"HSTS"} = $has_hsts;
$feature{"brotli"} = $has_brotli;
$feature{"crypto"} = $has_crypto;
$feature{"debug"} = $debug_build;
$feature{"getrlimit"} = $has_getrlimit;
$feature{"GnuTLS"} = $has_gnutls;
$feature{"GSS-API"} = $has_gssapi;
$feature{"http/2"} = $has_http2;
$feature{"https-proxy"} = $has_httpsproxy;
$feature{"idn"} = $has_idn;
$feature{"ipv6"} = $has_ipv6;
$feature{"Kerberos"} = $has_kerberos;
$feature{"large_file"} = $has_largefile;
$feature{"ld_preload"} = ($has_ldpreload && !$debug_build);
$feature{"libz"} = $has_libz;
$feature{"manual"} = $has_manual;
$feature{"MinGW"} = $has_mingw;
$feature{"MultiSSL"} = $has_multissl;
$feature{"NSS"} = $has_nss;
$feature{"NTLM"} = $has_ntlm;
$feature{"NTLM_WB"} = $has_ntlm_wb;
$feature{"OpenSSL"} = $has_openssl || $has_libressl || $has_boringssl;
$feature{"PSL"} = $has_psl;
$feature{"Schannel"} = $has_schannel;
$feature{"sectransp"} = $has_sectransp;
$feature{"SPNEGO"} = $has_spnego;
$feature{"SSL"} = $has_ssl;
$feature{"SSLpinning"} = $has_sslpinning;
$feature{"SSPI"} = $has_sspi;
$feature{"threaded-resolver"} = $has_threadedres;
$feature{"TLS-SRP"} = $has_tls_srp;
$feature{"TrackMemory"} = $has_memory_tracking;
$feature{"Unicode"} = $has_unicode;
$feature{"unittest"} = $debug_build;
$feature{"unix-sockets"} = $has_unix;
$feature{"win32"} = $has_win32;
$feature{"zstd"} = $has_zstd;
# make each protocol an enabled "feature"
for my $p (@protocols) {
$feature{$p} = 1;
}
# 'socks' was once here but is now removed
#
# strings that must match the names used in server/disabled.c
#
$feature{"cookies"} = 1;
$feature{"DoH"} = 1;
$feature{"HTTP-auth"} = 1;
$feature{"Mime"} = 1;
$feature{"netrc"} = 1;
$feature{"parsedate"} = 1;
$feature{"proxy"} = 1;
$feature{"shuffle-dns"} = 1;
$feature{"typecheck"} = 1;
$feature{"verbose-strings"} = 1;
$feature{"wakeup"} = 1;
}
#######################################################################
# display information about curl and the host the test suite runs on
#
sub checksystem {
unlink($memdump); # remove this if there was one left
my $feat;
my $curl;
my $libcurl;
my $versretval;
my $versnoexec;
my @version=();
my @disabled;
my $dis = "";
my $curlverout="$LOGDIR/curlverout.log";
my $curlvererr="$LOGDIR/curlvererr.log";
my $versioncmd="$CURL --version 1>$curlverout 2>$curlvererr";
unlink($curlverout);
unlink($curlvererr);
$versretval = runclient($versioncmd);
$versnoexec = $!;
open(VERSOUT, "<$curlverout");
@version = <VERSOUT>;
close(VERSOUT);
open(DISABLED, "server/disabled".exe_ext('TOOL')."|");
@disabled = <DISABLED>;
close(DISABLED);
if($disabled[0]) {
map s/[\r\n]//g, @disabled;
$dis = join(", ", @disabled);
}
$resolver="stock";
for(@version) {
chomp;
if($_ =~ /^curl ([^ ]*)/) {
$curl = $_;
$VERSION = $1;
$curl =~ s/^(.*)(libcurl.*)/$1/g;
$libcurl = $2;
if($curl =~ /linux|bsd|solaris/) {
$has_ldpreload = 1;
}
if($curl =~ /win32|Windows|mingw(32|64)/) {
# This is a Windows MinGW build or native build, we need to use
# Win32-style path.
$pwd = pathhelp::sys_native_current_path();
$has_textaware = 1;
$has_win32 = 1;
$has_mingw = 1 if ($curl =~ /-pc-mingw32/);
}
if ($libcurl =~ /(winssl|schannel)/i) {
$has_schannel=1;
$has_sslpinning=1;
}
elsif ($libcurl =~ /openssl/i) {
$has_openssl=1;
$has_sslpinning=1;
}
elsif ($libcurl =~ /gnutls/i) {
$has_gnutls=1;
$has_sslpinning=1;
}
elsif ($libcurl =~ /nss/i) {
$has_nss=1;
$has_sslpinning=1;
}
elsif ($libcurl =~ /wolfssl/i) {
$has_wolfssl=1;
$has_sslpinning=1;
}
elsif ($libcurl =~ /securetransport/i) {
$has_sectransp=1;
$has_sslpinning=1;
}
elsif ($libcurl =~ /BoringSSL/i) {
$has_boringssl=1;
$has_sslpinning=1;
}
elsif ($libcurl =~ /libressl/i) {
$has_libressl=1;
$has_sslpinning=1;
}
elsif ($libcurl =~ /mbedTLS/i) {
$has_mbedtls=1;
$has_sslpinning=1;
}
if ($libcurl =~ /ares/i) {
$has_cares=1;
$resolver="c-ares";
}
if ($libcurl =~ /mesalink/i) {
$has_mesalink=1;
}
if ($libcurl =~ /Hyper/i) {
$has_hyper=1;
}
}
elsif($_ =~ /^Protocols: (.*)/i) {
# these are the protocols compiled in to this libcurl
@protocols = split(' ', lc($1));
# Generate a "proto-ipv6" version of each protocol to match the
# IPv6 <server> name and a "proto-unix" to match the variant which
# uses Unix domain sockets. This works even if support isn't
# compiled in because the <features> test will fail.
push @protocols, map(("$_-ipv6", "$_-unix"), @protocols);
# 'http-proxy' is used in test cases to do CONNECT through
push @protocols, 'http-proxy';
# 'none' is used in test cases to mean no server
push @protocols, 'none';
}
elsif($_ =~ /^Features: (.*)/i) {
$feat = $1;
if($feat =~ /TrackMemory/i) {
# built with memory tracking support (--enable-curldebug)
$has_memory_tracking = 1;
}
if($feat =~ /debug/i) {
# curl was built with --enable-debug
$debug_build = 1;
}
if($feat =~ /SSL/i) {
# ssl enabled
$has_ssl=1;
}
if($feat =~ /MultiSSL/i) {
# multiple ssl backends available.
$has_multissl=1;
}
if($feat =~ /Largefile/i) {
# large file support
$has_largefile=1;
}
if($feat =~ /IDN/i) {
# IDN support
$has_idn=1;
}
if($feat =~ /IPv6/i) {
$has_ipv6 = 1;
}
if($feat =~ /UnixSockets/i) {
$has_unix = 1;
}
if($feat =~ /libz/i) {
$has_libz = 1;
}
if($feat =~ /brotli/i) {
$has_brotli = 1;
}
if($feat =~ /zstd/i) {
$has_zstd = 1;
}
if($feat =~ /NTLM/i) {
# NTLM enabled
$has_ntlm=1;
# Use this as a proxy for any cryptographic authentication
$has_crypto=1;
}
if($feat =~ /NTLM_WB/i) {
# NTLM delegation to winbind daemon ntlm_auth helper enabled
$has_ntlm_wb=1;
}
if($feat =~ /SSPI/i) {
# SSPI enabled
$has_sspi=1;
}
if($feat =~ /GSS-API/i) {
# GSS-API enabled
$has_gssapi=1;
}
if($feat =~ /Kerberos/i) {
# Kerberos enabled
$has_kerberos=1;
# Use this as a proxy for any cryptographic authentication
$has_crypto=1;
}
if($feat =~ /SPNEGO/i) {
# SPNEGO enabled
$has_spnego=1;
# Use this as a proxy for any cryptographic authentication
$has_crypto=1;
}
if($feat =~ /CharConv/i) {
# CharConv enabled
$has_charconv=1;
}
if($feat =~ /TLS-SRP/i) {
# TLS-SRP enabled
$has_tls_srp=1;
}
if($feat =~ /PSL/i) {
# PSL enabled
$has_psl=1;
}
if($feat =~ /alt-svc/i) {
# alt-svc enabled
$has_altsvc=1;
}
if($feat =~ /HSTS/i) {
$has_hsts=1;
}
if($feat =~ /AsynchDNS/i) {
if(!$has_cares) {
# this means threaded resolver
$has_threadedres=1;
$resolver="threaded";
}
}
if($feat =~ /HTTP2/) {
# http2 enabled
$has_http2=1;
push @protocols, 'http/2';
}
if($feat =~ /HTTPS-proxy/) {
$has_httpsproxy=1;
# 'https-proxy' is used as "server" so consider it a protocol
push @protocols, 'https-proxy';
}
if($feat =~ /Unicode/i) {
$has_unicode = 1;
}
}
#
# Test harness currently uses a non-stunnel server in order to
# run HTTP TLS-SRP tests required when curl is built with https
# protocol support and TLS-SRP feature enabled. For convenience
# 'httptls' may be included in the test harness protocols array
# to differentiate this from classic stunnel based 'https' test
# harness server.
#
if($has_tls_srp) {
my $add_httptls;
for(@protocols) {
if($_ =~ /^https(-ipv6|)$/) {
$add_httptls=1;
last;
}
}
if($add_httptls && (! grep /^httptls$/, @protocols)) {
push @protocols, 'httptls';
push @protocols, 'httptls-ipv6';
}
}
}
if(!$curl) {
logmsg "unable to get curl's version, further details are:\n";
logmsg "issued command: \n";
logmsg "$versioncmd \n";
if ($versretval == -1) {
logmsg "command failed with: \n";
logmsg "$versnoexec \n";
}
elsif ($versretval & 127) {
logmsg sprintf("command died with signal %d, and %s coredump.\n",
($versretval & 127), ($versretval & 128)?"a":"no");
}
else {
logmsg sprintf("command exited with value %d \n", $versretval >> 8);
}
logmsg "contents of $curlverout: \n";
displaylogcontent("$curlverout");
logmsg "contents of $curlvererr: \n";
displaylogcontent("$curlvererr");
die "couldn't get curl's version";
}
if(-r "../lib/curl_config.h") {
open(CONF, "<../lib/curl_config.h");
while(<CONF>) {
if($_ =~ /^\#define HAVE_GETRLIMIT/) {
$has_getrlimit = 1;
}
}
close(CONF);
}
if($has_ipv6) {
# client has IPv6 support
# check if the HTTP server has it!
my $cmd = "server/sws".exe_ext('SRV')." --version";
my @sws = `$cmd`;
if($sws[0] =~ /IPv6/) {
# HTTP server has IPv6 support!
$http_ipv6 = 1;
$gopher_ipv6 = 1;
}
# check if the FTP server has it!
$cmd = "server/sockfilt".exe_ext('SRV')." --version";
@sws = `$cmd`;
if($sws[0] =~ /IPv6/) {
# FTP server has IPv6 support!
$ftp_ipv6 = 1;
}
}
if($has_unix) {
# client has Unix sockets support, check whether the HTTP server has it
my $cmd = "server/sws".exe_ext('SRV')." --version";
my @sws = `$cmd`;
$http_unix = 1 if($sws[0] =~ /unix/);
}
if(!$has_memory_tracking && $torture) {
die "can't run torture tests since curl was built without ".
"TrackMemory feature (--enable-curldebug)";
}
open(M, "$CURL -M 2>&1|");
while(my $s = <M>) {
if($s =~ /built-in manual was disabled at build-time/) {
$has_manual = 0;
last;
}
$has_manual = 1;
last;
}
close(M);
$has_shared = `sh $CURLCONFIG --built-shared`;
chomp $has_shared;
my $hostname=join(' ', runclientoutput("hostname"));
my $hosttype=join(' ', runclientoutput("uname -a"));
my $hostos=$^O;
logmsg ("********* System characteristics ******** \n",
"* $curl\n",
"* $libcurl\n",
"* Features: $feat\n",
"* Disabled: $dis\n",
"* Host: $hostname",
"* System: $hosttype",
"* OS: $hostos\n");
if($has_memory_tracking && $has_threadedres) {
$has_memory_tracking = 0;
logmsg("*\n",
"*** DISABLES memory tracking when using threaded resolver\n",
"*\n");
}
logmsg sprintf("* Servers: %s", $stunnel?"SSL ":"");
logmsg sprintf("%s", $http_ipv6?"HTTP-IPv6 ":"");
logmsg sprintf("%s", $http_unix?"HTTP-unix ":"");
logmsg sprintf("%s\n", $ftp_ipv6?"FTP-IPv6 ":"");
logmsg sprintf("* Env: %s%s", $valgrind?"Valgrind ":"",
$run_event_based?"event-based ":"");
logmsg sprintf("%s\n", $libtool?"Libtool ":"");
logmsg ("* Seed: $randseed\n");
if($verbose) {
if($has_unix) {
logmsg "* Unix socket paths:\n";
if($http_unix) {
logmsg sprintf("* HTTP-Unix:%s\n", $HTTPUNIXPATH);
}
}
}
logmsg "***************************************** \n";
setupfeatures();
# toggle off the features that were disabled in the build
for my $d(@disabled) {
$feature{$d} = 0;
}
}
#######################################################################
# substitute the variable stuff into either a joined up file or
# a command, in either case passed by reference
#
sub subVariables {
my ($thing, $testnum, $prefix) = @_;
if(!$prefix) {
$prefix = "%";
}
# test server ports
$$thing =~ s/${prefix}FTP6PORT/$FTP6PORT/g;
$$thing =~ s/${prefix}FTPSPORT/$FTPSPORT/g;
$$thing =~ s/${prefix}FTPPORT/$FTPPORT/g;
$$thing =~ s/${prefix}GOPHER6PORT/$GOPHER6PORT/g;
$$thing =~ s/${prefix}GOPHERPORT/$GOPHERPORT/g;
$$thing =~ s/${prefix}GOPHERSPORT/$GOPHERSPORT/g;
$$thing =~ s/${prefix}HTTPTLS6PORT/$HTTPTLS6PORT/g;
$$thing =~ s/${prefix}HTTPTLSPORT/$HTTPTLSPORT/g;
$$thing =~ s/${prefix}HTTP6PORT/$HTTP6PORT/g;
$$thing =~ s/${prefix}HTTPSPORT/$HTTPSPORT/g;
$$thing =~ s/${prefix}HTTPSPROXYPORT/$HTTPSPROXYPORT/g;
$$thing =~ s/${prefix}HTTP2PORT/$HTTP2PORT/g;
$$thing =~ s/${prefix}HTTPPORT/$HTTPPORT/g;
$$thing =~ s/${prefix}PROXYPORT/$HTTPPROXYPORT/g;
$$thing =~ s/${prefix}MQTTPORT/$MQTTPORT/g;
$$thing =~ s/${prefix}IMAP6PORT/$IMAP6PORT/g;
$$thing =~ s/${prefix}IMAPPORT/$IMAPPORT/g;
$$thing =~ s/${prefix}POP36PORT/$POP36PORT/g;
$$thing =~ s/${prefix}POP3PORT/$POP3PORT/g;
$$thing =~ s/${prefix}RTSP6PORT/$RTSP6PORT/g;
$$thing =~ s/${prefix}RTSPPORT/$RTSPPORT/g;
$$thing =~ s/${prefix}SMTP6PORT/$SMTP6PORT/g;
$$thing =~ s/${prefix}SMTPPORT/$SMTPPORT/g;
$$thing =~ s/${prefix}SOCKSPORT/$SOCKSPORT/g;
$$thing =~ s/${prefix}SSHPORT/$SSHPORT/g;
$$thing =~ s/${prefix}TFTP6PORT/$TFTP6PORT/g;
$$thing =~ s/${prefix}TFTPPORT/$TFTPPORT/g;
$$thing =~ s/${prefix}DICTPORT/$DICTPORT/g;
$$thing =~ s/${prefix}SMBPORT/$SMBPORT/g;
$$thing =~ s/${prefix}SMBSPORT/$SMBSPORT/g;
$$thing =~ s/${prefix}TELNETPORT/$TELNETPORT/g;
$$thing =~ s/${prefix}NOLISTENPORT/$NOLISTENPORT/g;
# server Unix domain socket paths
$$thing =~ s/${prefix}HTTPUNIXPATH/$HTTPUNIXPATH/g;
# client IP addresses
$$thing =~ s/${prefix}CLIENT6IP/$CLIENT6IP/g;
$$thing =~ s/${prefix}CLIENTIP/$CLIENTIP/g;
# server IP addresses
$$thing =~ s/${prefix}HOST6IP/$HOST6IP/g;
$$thing =~ s/${prefix}HOSTIP/$HOSTIP/g;
# misc
$$thing =~ s/${prefix}CURL/$CURL/g;
$$thing =~ s/${prefix}PWD/$pwd/g;
$$thing =~ s/${prefix}POSIX_PWD/$posix_pwd/g;
$$thing =~ s/${prefix}VERSION/$VERSION/g;
$$thing =~ s/${prefix}TESTNUMBER/$testnum/g;
my $file_pwd = $pwd;
if($file_pwd !~ /^\//) {
$file_pwd = "/$file_pwd";
}
my $ssh_pwd = $posix_pwd;
if ($sshdid && $sshdid =~ /OpenSSH-Windows/) {
$ssh_pwd = $file_pwd;
}
$$thing =~ s/${prefix}FILE_PWD/$file_pwd/g;
$$thing =~ s/${prefix}SSH_PWD/$ssh_pwd/g;
$$thing =~ s/${prefix}SRCDIR/$srcdir/g;
$$thing =~ s/${prefix}USER/$USER/g;
$$thing =~ s/${prefix}SSHSRVMD5/$SSHSRVMD5/g;
$$thing =~ s/${prefix}SSHSRVSHA256/$SSHSRVSHA256/g;
# The purpose of FTPTIME2 and FTPTIME3 is to provide times that can be
# used for time-out tests and that would work on most hosts as these
# adjust for the startup/check time for this particular host. We needed to
# do this to make the test suite run better on very slow hosts.
my $ftp2 = $ftpchecktime * 2;
my $ftp3 = $ftpchecktime * 3;
$$thing =~ s/${prefix}FTPTIME2/$ftp2/g;
$$thing =~ s/${prefix}FTPTIME3/$ftp3/g;
# HTTP2
$$thing =~ s/${prefix}H2CVER/$h2cver/g;
}
sub subBase64 {
my ($thing) = @_;
# cut out the base64 piece
if($$thing =~ s/%b64\[(.*)\]b64%/%%B64%%/i) {
my $d = $1;
# encode %NN characters
$d =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
my $enc = encode_base64($d, "");
# put the result into there
$$thing =~ s/%%B64%%/$enc/;
}
# hex decode
if($$thing =~ s/%hex\[(.*)\]hex%/%%HEX%%/i) {
# decode %NN characters
my $d = $1;
$d =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
$$thing =~ s/%%HEX%%/$d/;
}
if($$thing =~ s/%repeat\[(\d+) x (.*)\]%/%%REPEAT%%/i) {
# decode %NN characters
my ($d, $n) = ($2, $1);
$d =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
my $all = $d x $n;
$$thing =~ s/%%REPEAT%%/$all/;
}
}
my $prevupdate;
sub subNewlines {
my ($thing) = @_;
# When curl is built with Hyper, it gets all response headers delivered as
# name/value pairs and curl "invents" the newlines when it saves the
# headers. Therefore, curl will always save headers with CRLF newlines
# when built to use Hyper. By making sure we deliver all tests using CRLF
# as well, all test comparisons will survive without knowing about this
# little quirk.
if(($$thing =~ /^HTTP\/(1.1|1.0|2) [1-5][^\x0d]*\z/) ||
(($$thing =~ /^[a-z0-9_-]+: [^\x0d]*\z/i) &&
# skip curl error messages
($$thing !~ /^curl: \(\d+\) /))) {
# enforce CRLF newline
$$thing =~ s/\x0a/\x0d\x0a/;
$prevupdate = 1;
}
else {
if(($$thing =~ /^\n\z/) && $prevupdate) {
# if there's a blank link after a line we update, we hope it is
# the empty line following headers
$$thing =~ s/\x0a/\x0d\x0a/;
}
$prevupdate = 0;
}
}
#######################################################################
# Provide time stamps for single test skipped events
#
sub timestampskippedevents {
my $testnum = $_[0];
return if((not defined($testnum)) || ($testnum < 1));
if($timestats) {
if($timevrfyend{$testnum}) {
return;
}
elsif($timesrvrlog{$testnum}) {
$timevrfyend{$testnum} = $timesrvrlog{$testnum};
return;
}
elsif($timetoolend{$testnum}) {
$timevrfyend{$testnum} = $timetoolend{$testnum};
$timesrvrlog{$testnum} = $timetoolend{$testnum};
}
elsif($timetoolini{$testnum}) {
$timevrfyend{$testnum} = $timetoolini{$testnum};
$timesrvrlog{$testnum} = $timetoolini{$testnum};
$timetoolend{$testnum} = $timetoolini{$testnum};
}
elsif($timesrvrend{$testnum}) {
$timevrfyend{$testnum} = $timesrvrend{$testnum};
$timesrvrlog{$testnum} = $timesrvrend{$testnum};
$timetoolend{$testnum} = $timesrvrend{$testnum};
$timetoolini{$testnum} = $timesrvrend{$testnum};
}
elsif($timesrvrini{$testnum}) {
$timevrfyend{$testnum} = $timesrvrini{$testnum};
$timesrvrlog{$testnum} = $timesrvrini{$testnum};
$timetoolend{$testnum} = $timesrvrini{$testnum};
$timetoolini{$testnum} = $timesrvrini{$testnum};
$timesrvrend{$testnum} = $timesrvrini{$testnum};
}
elsif($timeprepini{$testnum}) {
$timevrfyend{$testnum} = $timeprepini{$testnum};
$timesrvrlog{$testnum} = $timeprepini{$testnum};
$timetoolend{$testnum} = $timeprepini{$testnum};
$timetoolini{$testnum} = $timeprepini{$testnum};
$timesrvrend{$testnum} = $timeprepini{$testnum};
$timesrvrini{$testnum} = $timeprepini{$testnum};
}
}
}
#
# 'prepro' processes the input array and replaces %-variables in the array
# etc. Returns the processed version of the array
sub prepro {
my $testnum = shift;
my (@entiretest) = @_;
my $show = 1;
my @out;
for my $s (@entiretest) {
my $f = $s;
if($s =~ /^ *%if (.*)/) {
my $cond = $1;
my $rev = 0;
if($cond =~ /^!(.*)/) {
$cond = $1;
$rev = 1;
}
$rev ^= $feature{$cond} ? 1 : 0;
$show = $rev;
next;
}
elsif($s =~ /^ *%else/) {
$show ^= 1;
next;
}
elsif($s =~ /^ *%endif/) {
$show = 1;
next;
}
if($show) {
subVariables(\$s, $testnum, "%");
subBase64(\$s);
subNewlines(\$s) if($has_hyper && ($keywords{"HTTP"} ||
$keywords{"HTTPS"}));
push @out, $s;
}
}
return @out;
}
#######################################################################
# Run a single specified test case
#
sub singletest {
my ($evbased, # 1 means switch on if possible (and "curl" is tested)
# returns "not a test" if it can't be used for this test
$testnum,
$count,
$total)=@_;
my @what;
my $why;
my $cmd;
my $disablevalgrind;
my $errorreturncode = 1; # 1 means normal error, 2 means ignored error
# fist, remove all lingering log files
if(!cleardir($LOGDIR) && $clearlocks) {
clearlocks($LOGDIR);
cleardir($LOGDIR);
}
# copy test number to a global scope var, this allows
# testnum checking when starting test harness servers.
$testnumcheck = $testnum;
# timestamp test preparation start
$timeprepini{$testnum} = Time::HiRes::time();
if($disttests !~ /test$testnum(\W|\z)/ ) {
logmsg "Warning: test$testnum not present in tests/data/Makefile.inc\n";
}
if($disabled{$testnum}) {
if(!$run_disabeled) {
$why = "listed in DISABLED";
}
else {
logmsg "Warning: test$testnum is explicitly disabled\n";
}
}
if($ignored{$testnum}) {
logmsg "Warning: test$testnum result is ignored\n";
$errorreturncode = 2;
}
# load the test case file definition
if(loadtest("${TESTDIR}/test${testnum}")) {
if($verbose) {
# this is not a test
logmsg "RUN: $testnum doesn't look like a test case\n";
}
$why = "no test";
}
else {
@what = getpart("client", "features");
}
# We require a feature to be present
for(@what) {
my $f = $_;
$f =~ s/\s//g;
if($f =~ /^([^!].*)$/) {
if($feature{$1}) {
next;
}
$why = "curl lacks $1 support";
last;
}
}
# We require a feature to not be present
if(!$why) {
for(@what) {
my $f = $_;
$f =~ s/\s//g;
if($f =~ /^!(.*)$/) {
if(!$feature{$1}) {
next;
}
}
else {
next;
}
$why = "curl has $1 support";
last;
}
}
if(!$why) {
my @info_keywords = getpart("info", "keywords");
my $match;
my $k;
# Clear the list of keywords from the last test
%keywords = ();
if(!$info_keywords[0]) {
$why = "missing the <keywords> section!";
}
for $k (@info_keywords) {
chomp $k;
if ($disabled_keywords{lc($k)}) {
$why = "disabled by keyword";
} elsif ($enabled_keywords{lc($k)}) {
$match = 1;
}
if ($ignored_keywords{lc($k)}) {
logmsg "Warning: test$testnum result is ignored due to $k\n";
$errorreturncode = 2;
}
$keywords{$k} = 1;
}
if(!$why && !$match && %enabled_keywords) {
$why = "disabled by missing keyword";
}
}
if (!$why && defined $custom_skip_reasons{test}{$testnum}) {
$why = $custom_skip_reasons{test}{$testnum};
}
if (!$why && defined $custom_skip_reasons{tool}) {
foreach my $tool (getpart("client", "tool")) {
foreach my $tool_skip_pattern (keys %{$custom_skip_reasons{tool}}) {
if ($tool =~ /$tool_skip_pattern/i) {
$why = $custom_skip_reasons{tool}{$tool_skip_pattern};
}
}
}
}
if (!$why && defined $custom_skip_reasons{keyword}) {
foreach my $keyword (getpart("info", "keywords")) {
foreach my $keyword_skip_pattern (keys %{$custom_skip_reasons{keyword}}) {
if ($keyword =~ /$keyword_skip_pattern/i) {
$why = $custom_skip_reasons{keyword}{$keyword_skip_pattern};
}
}
}
}
# test definition may instruct to (un)set environment vars
# this is done this early, so that the precheck can use environment
# variables and still bail out fine on errors
# restore environment variables that were modified in a previous run
foreach my $var (keys %oldenv) {
if($oldenv{$var} eq 'notset') {
delete $ENV{$var} if($ENV{$var});
}
else {
$ENV{$var} = $oldenv{$var};
}
delete $oldenv{$var};
}
# get the name of the test early
my @testname= getpart("client", "name");
my $testname = $testname[0];
$testname =~ s/\n//g;
# create test result in CI services
if(azure_check_environment() && $AZURE_RUN_ID) {
$AZURE_RESULT_ID = azure_create_test_result($VCURL, $AZURE_RUN_ID, $testnum, $testname);
}
elsif(appveyor_check_environment()) {
appveyor_create_test_result($VCURL, $testnum, $testname);
}
# remove test server commands file before servers are started/verified
unlink($FTPDCMD) if(-f $FTPDCMD);
# timestamp required servers verification start
$timesrvrini{$testnum} = Time::HiRes::time();
if(!$why) {
$why = serverfortest($testnum);
}
# Save a preprocessed version of the entire test file. This allows more
# "basic" test case readers to enjoy variable replacements.
my @entiretest = fulltest();
my $otest = "log/test$testnum";
@entiretest = prepro($testnum, @entiretest);
# save the new version
open(D, ">$otest");
print D @entiretest;
close(D);
# in case the process changed the file, reload it
loadtest("log/test${testnum}");
# timestamp required servers verification end
$timesrvrend{$testnum} = Time::HiRes::time();
my @setenv = getpart("client", "setenv");
if(@setenv) {
foreach my $s (@setenv) {
chomp $s;
if($s =~ /([^=]*)=(.*)/) {
my ($var, $content) = ($1, $2);
# remember current setting, to restore it once test runs
$oldenv{$var} = ($ENV{$var})?"$ENV{$var}":'notset';
# set new value
if(!$content) {
delete $ENV{$var} if($ENV{$var});
}
else {
if($var =~ /^LD_PRELOAD/) {
if(exe_ext('TOOL') && (exe_ext('TOOL') eq '.exe')) {
# print "Skipping LD_PRELOAD due to lack of OS support\n";
next;
}
if($debug_build || ($has_shared ne "yes")) {
# print "Skipping LD_PRELOAD due to no release shared build\n";
next;
}
}
$ENV{$var} = "$content";
print "setenv $var = $content\n" if($verbose);
}
}
}
}
if($use_external_proxy) {
$ENV{http_proxy} = $proxy_address;
$ENV{HTTPS_PROXY} = $proxy_address;
}
if(!$why) {
my @precheck = getpart("client", "precheck");
if(@precheck) {
$cmd = $precheck[0];
chomp $cmd;
if($cmd) {
my @p = split(/ /, $cmd);
if($p[0] !~ /\//) {
# the first word, the command, does not contain a slash so
# we will scan the "improved" PATH to find the command to
# be able to run it
my $fullp = checktestcmd($p[0]);
if($fullp) {
$p[0] = $fullp;
}
$cmd = join(" ", @p);
}
my @o = `$cmd 2>log/precheck-$testnum`;
if($o[0]) {
$why = $o[0];
chomp $why;
} elsif($?) {
$why = "precheck command error";
}
logmsg "prechecked $cmd\n" if($verbose);
}
}
}
if($why && !$listonly) {
# there's a problem, count it as "skipped"
$skipped++;
$skipped{$why}++;
$teststat[$testnum]=$why; # store reason for this test case
if(!$short) {
if($skipped{$why} <= 3) {
# show only the first three skips for each reason
logmsg sprintf("test %04d SKIPPED: $why\n", $testnum);
}
}
timestampskippedevents($testnum);
return -1;
}
logmsg sprintf("test %04d...", $testnum) if(!$automakestyle);
my %replyattr = getpartattr("reply", "data");
my @reply;
if (partexists("reply", "datacheck")) {
for my $partsuffix (('', '1', '2', '3', '4')) {
my @replycheckpart = getpart("reply", "datacheck".$partsuffix);
if(@replycheckpart) {
my %replycheckpartattr = getpartattr("reply", "datacheck".$partsuffix);
# get the mode attribute
my $filemode=$replycheckpartattr{'mode'};
if($filemode && ($filemode eq "text") && $has_textaware) {
# text mode when running on windows: fix line endings
map s/\r\n/\n/g, @replycheckpart;
map s/\n/\r\n/g, @replycheckpart;
}
if($replycheckpartattr{'nonewline'}) {
# Yes, we must cut off the final newline from the final line
# of the datacheck
chomp($replycheckpart[$#replycheckpart]);
}
push(@reply, @replycheckpart);
}
}
}
else {
# check against the data section
@reply = getpart("reply", "data");
# get the mode attribute
my $filemode=$replyattr{'mode'};
if($filemode && ($filemode eq "text") && $has_textaware) {
# text mode when running on windows: fix line endings
map s/\r\n/\n/g, @reply;
map s/\n/\r\n/g, @reply;
}
}
# this is the valid protocol blurb curl should generate
my @protocol= getpart("verify", "protocol");
# this is the valid protocol blurb curl should generate to a proxy
my @proxyprot = getpart("verify", "proxy");
# redirected stdout/stderr to these files
$STDOUT="$LOGDIR/stdout$testnum";
$STDERR="$LOGDIR/stderr$testnum";
# if this section exists, we verify that the stdout contained this:
my @validstdout = getpart("verify", "stdout");
my @validstderr = getpart("verify", "stderr");
# if this section exists, we verify upload
my @upload = getpart("verify", "upload");
if(@upload) {
my %hash = getpartattr("verify", "upload");
if($hash{'nonewline'}) {
# cut off the final newline from the final line of the upload data
chomp($upload[$#upload]);
}
}
# if this section exists, it might be FTP server instructions:
my @ftpservercmd = getpart("reply", "servercmd");
my $CURLOUT="$LOGDIR/curl$testnum.out"; # curl output if not stdout
# name of the test
logmsg "[$testname]\n" if(!$short);
if($listonly) {
timestampskippedevents($testnum);
return 0; # look successful
}
my @codepieces = getpart("client", "tool");
my $tool="";
if(@codepieces) {
$tool = $codepieces[0];
chomp $tool;
$tool .= exe_ext('TOOL');
}
# remove server output logfile
unlink($SERVERIN);
unlink($SERVER2IN);
unlink($PROXYIN);
push @ftpservercmd, "Testnum $testnum\n";
# write the instructions to file
writearray($FTPDCMD, \@ftpservercmd);
# get the command line options to use
my @blaha;
($cmd, @blaha)= getpart("client", "command");
if($cmd) {
# make some nice replace operations
$cmd =~ s/\n//g; # no newlines please
# substitute variables in the command line
}
else {
# there was no command given, use something silly
$cmd="-";
}
if($has_memory_tracking) {
unlink($memdump);
}
# create (possibly-empty) files before starting the test
for my $partsuffix (('', '1', '2', '3', '4')) {
my @inputfile=getpart("client", "file".$partsuffix);
my %fileattr = getpartattr("client", "file".$partsuffix);
my $filename=$fileattr{'name'};
if(@inputfile || $filename) {
if(!$filename) {
logmsg "ERROR: section client=>file has no name attribute\n";
timestampskippedevents($testnum);
return -1;
}
my $fileContent = join('', @inputfile);
open(OUTFILE, ">$filename");
binmode OUTFILE; # for crapage systems, use binary
if($fileattr{'nonewline'}) {
# cut off the final newline
chomp($fileContent);
}
print OUTFILE $fileContent;
close(OUTFILE);
}
}
my %cmdhash = getpartattr("client", "command");
my $out="";
if((!$cmdhash{'option'}) || ($cmdhash{'option'} !~ /no-output/)) {
#We may slap on --output!
if (!@validstdout ||
($cmdhash{'option'} && $cmdhash{'option'} =~ /force-output/)) {
$out=" --output $CURLOUT ";
}
}
my $serverlogslocktimeout = $defserverlogslocktimeout;
if($cmdhash{'timeout'}) {
# test is allowed to override default server logs lock timeout
if($cmdhash{'timeout'} =~ /(\d+)/) {
$serverlogslocktimeout = $1 if($1 >= 0);
}
}
my $postcommanddelay = $defpostcommanddelay;
if($cmdhash{'delay'}) {
# test is allowed to specify a delay after command is executed
if($cmdhash{'delay'} =~ /(\d+)/) {
$postcommanddelay = $1 if($1 > 0);
}
}
my $CMDLINE;
my $cmdargs;
my $cmdtype = $cmdhash{'type'} || "default";
my $fail_due_event_based = $evbased;
if($cmdtype eq "perl") {
# run the command line prepended with "perl"
$cmdargs ="$cmd";
$CMDLINE = "$perl ";
$tool=$CMDLINE;
$disablevalgrind=1;
}
elsif($cmdtype eq "shell") {
# run the command line prepended with "/bin/sh"
$cmdargs ="$cmd";
$CMDLINE = "/bin/sh ";
$tool=$CMDLINE;
$disablevalgrind=1;
}
elsif(!$tool && !$keywords{"unittest"}) {
# run curl, add suitable command line options
my $inc="";
if((!$cmdhash{'option'}) || ($cmdhash{'option'} !~ /no-include/)) {
$inc = " --include";
}
$cmdargs = "$out$inc ";
if($cmdhash{'option'} && ($cmdhash{'option'} =~ /binary-trace/)) {
$cmdargs .= "--trace log/trace$testnum ";
}
else {
$cmdargs .= "--trace-ascii log/trace$testnum ";
}
$cmdargs .= "--trace-time ";
if($evbased) {
$cmdargs .= "--test-event ";
$fail_due_event_based--;
}
$cmdargs .= $cmd;
if ($use_external_proxy) {
$cmdargs .= " --proxy $proxy_address ";
}
}
else {
$cmdargs = " $cmd"; # $cmd is the command line for the test file
$CURLOUT = $STDOUT; # sends received data to stdout
# Default the tool to a unit test with the same name as the test spec
if($keywords{"unittest"} && !$tool) {
$tool="unit$testnum";
}
if($tool =~ /^lib/) {
$CMDLINE="$LIBDIR/$tool";
}
elsif($tool =~ /^unit/) {
$CMDLINE="$UNITDIR/$tool";
}
if(! -f $CMDLINE) {
logmsg "The tool set in the test case for this: '$tool' does not exist\n";
timestampskippedevents($testnum);
return -1;
}
$DBGCURL=$CMDLINE;
}
if($gdbthis) {
# gdb is incompatible with valgrind, so disable it when debugging
# Perhaps a better approach would be to run it under valgrind anyway
# with --db-attach=yes or --vgdb=yes.
$disablevalgrind=1;
}
if($fail_due_event_based) {
logmsg "This test cannot run event based\n";
return -1;
}
my @stdintest = getpart("client", "stdin");
if(@stdintest) {
my $stdinfile="$LOGDIR/stdin-for-$testnum";
my %hash = getpartattr("client", "stdin");
if($hash{'nonewline'}) {
# cut off the final newline from the final line of the stdin data
chomp($stdintest[$#stdintest]);
}
writearray($stdinfile, \@stdintest);
$cmdargs .= " <$stdinfile";
}
if(!$tool) {
$CMDLINE="$CURL";
}
my $usevalgrind;
if($valgrind && !$disablevalgrind) {
my @valgrindoption = getpart("verify", "valgrind");
if((!@valgrindoption) || ($valgrindoption[0] !~ /disable/)) {
$usevalgrind = 1;
my $valgrindcmd = "$valgrind ";
$valgrindcmd .= "$valgrind_tool " if($valgrind_tool);
$valgrindcmd .= "--quiet --leak-check=yes ";
$valgrindcmd .= "--suppressions=$srcdir/valgrind.supp ";
# $valgrindcmd .= "--gen-suppressions=all ";
$valgrindcmd .= "--num-callers=16 ";
$valgrindcmd .= "${valgrind_logfile}=$LOGDIR/valgrind$testnum";
$CMDLINE = "$valgrindcmd $CMDLINE";
}
}
$CMDLINE .= "$cmdargs >$STDOUT 2>$STDERR";
if($verbose) {
logmsg "$CMDLINE\n";
}
open(CMDLOG, ">", "$LOGDIR/$CURLLOG");
print CMDLOG "$CMDLINE\n";
close(CMDLOG);
unlink("core");
my $dumped_core;
my $cmdres;
if($gdbthis) {
my $gdbinit = "$TESTDIR/gdbinit$testnum";
open(GDBCMD, ">$LOGDIR/gdbcmd");
print GDBCMD "set args $cmdargs\n";
print GDBCMD "show args\n";
print GDBCMD "source $gdbinit\n" if -e $gdbinit;
close(GDBCMD);
}
# Flush output.
$| = 1;
# timestamp starting of test command
$timetoolini{$testnum} = Time::HiRes::time();
# run the command line we built
if ($torture) {
$cmdres = torture($CMDLINE,
$testnum,
"$gdb --directory $LIBDIR $DBGCURL -x $LOGDIR/gdbcmd");
}
elsif($gdbthis) {
my $GDBW = ($gdbxwin) ? "-w" : "";
runclient("$gdb --directory $LIBDIR $DBGCURL $GDBW -x $LOGDIR/gdbcmd");
$cmdres=0; # makes it always continue after a debugged run
}
else {
$cmdres = runclient("$CMDLINE");
my $signal_num = $cmdres & 127;
$dumped_core = $cmdres & 128;
if(!$anyway && ($signal_num || $dumped_core)) {
$cmdres = 1000;
}
else {
$cmdres >>= 8;
$cmdres = (2000 + $signal_num) if($signal_num && !$cmdres);
}
}
# timestamp finishing of test command
$timetoolend{$testnum} = Time::HiRes::time();
if(!$dumped_core) {
if(-r "core") {
# there's core file present now!
$dumped_core = 1;
}
}
if($dumped_core) {
logmsg "core dumped\n";
if(0 && $gdb) {
logmsg "running gdb for post-mortem analysis:\n";
open(GDBCMD, ">$LOGDIR/gdbcmd2");
print GDBCMD "bt\n";
close(GDBCMD);
runclient("$gdb --directory libtest -x $LOGDIR/gdbcmd2 -batch $DBGCURL core ");
# unlink("$LOGDIR/gdbcmd2");
}
}
# If a server logs advisor read lock file exists, it is an indication
# that the server has not yet finished writing out all its log files,
# including server request log files used for protocol verification.
# So, if the lock file exists the script waits here a certain amount
# of time until the server removes it, or the given time expires.
if($serverlogslocktimeout) {
my $lockretry = $serverlogslocktimeout * 20;
while((-f $SERVERLOGS_LOCK) && $lockretry--) {
portable_sleep(0.05);
}
if(($lockretry < 0) &&
($serverlogslocktimeout >= $defserverlogslocktimeout)) {
logmsg "Warning: server logs lock timeout ",
"($serverlogslocktimeout seconds) expired\n";
}
}
# Test harness ssh server does not have this synchronization mechanism,
# this implies that some ssh server based tests might need a small delay
# once that the client command has run to avoid false test failures.
#
# gnutls-serv also lacks this synchronization mechanism, so gnutls-serv
# based tests might need a small delay once that the client command has
# run to avoid false test failures.
portable_sleep($postcommanddelay) if($postcommanddelay);
# timestamp removal of server logs advisor read lock
$timesrvrlog{$testnum} = Time::HiRes::time();
# test definition might instruct to stop some servers
# stop also all servers relative to the given one
my @killtestservers = getpart("client", "killserver");
if(@killtestservers) {
foreach my $server (@killtestservers) {
chomp $server;
if(stopserver($server)) {
return 1; # normal error if asked to fail on unexpected alive
}
}
}
# run the postcheck command
my @postcheck= getpart("client", "postcheck");
if(@postcheck) {
$cmd = join("", @postcheck);
chomp $cmd;
if($cmd) {
logmsg "postcheck $cmd\n" if($verbose);
my $rc = runclient("$cmd");
# Must run the postcheck command in torture mode in order
# to clean up, but the result can't be relied upon.
if($rc != 0 && !$torture) {
logmsg " postcheck FAILED\n";
# timestamp test result verification end
$timevrfyend{$testnum} = Time::HiRes::time();
return $errorreturncode;
}
}
}
# restore environment variables that were modified
if(%oldenv) {
foreach my $var (keys %oldenv) {
if($oldenv{$var} eq 'notset') {
delete $ENV{$var} if($ENV{$var});
}
else {
$ENV{$var} = "$oldenv{$var}";
}
}
}
# Skip all the verification on torture tests
if ($torture) {
# timestamp test result verification end
$timevrfyend{$testnum} = Time::HiRes::time();
return $cmdres;
}
my @err = getpart("verify", "errorcode");
my $errorcode = $err[0] || "0";
my $ok="";
my $res;
chomp $errorcode;
if (@validstdout) {
# verify redirected stdout
my @actual = loadarray($STDOUT);
# what parts to cut off from stdout
my @stripfile = getpart("verify", "stripfile");
foreach my $strip (@stripfile) {
chomp $strip;
my @newgen;
for(@actual) {
eval $strip;
if($_) {
push @newgen, $_;
}
}
# this is to get rid of array entries that vanished (zero
# length) because of replacements
@actual = @newgen;
}
# get all attributes
my %hash = getpartattr("verify", "stdout");
# get the mode attribute
my $filemode=$hash{'mode'};
if($filemode && ($filemode eq "text") && $has_textaware) {
# text mode when running on windows: fix line endings
map s/\r\n/\n/g, @validstdout;
map s/\n/\r\n/g, @validstdout;
}
if($hash{'nonewline'}) {
# Yes, we must cut off the final newline from the final line
# of the protocol data
chomp($validstdout[$#validstdout]);
}
$res = compare($testnum, $testname, "stdout", \@actual, \@validstdout);
if($res) {
return $errorreturncode;
}
$ok .= "s";
}
else {
$ok .= "-"; # stdout not checked
}
if (@validstderr) {
# verify redirected stderr
my @actual = loadarray($STDERR);
# what parts to cut off from stderr
my @stripfile = getpart("verify", "stripfile");
foreach my $strip (@stripfile) {
chomp $strip;
my @newgen;
for(@actual) {
eval $strip;
if($_) {
push @newgen, $_;
}
}
# this is to get rid of array entries that vanished (zero
# length) because of replacements
@actual = @newgen;
}
# get all attributes
my %hash = getpartattr("verify", "stderr");
# get the mode attribute
my $filemode=$hash{'mode'};
if($filemode && ($filemode eq "text") && $has_textaware) {
# text mode when running on windows: fix line endings
map s/\r\n/\n/g, @validstderr;
map s/\n/\r\n/g, @validstderr;
}
if($hash{'nonewline'}) {
# Yes, we must cut off the final newline from the final line
# of the protocol data
chomp($validstderr[$#validstderr]);
}
$res = compare($testnum, $testname, "stderr", \@actual, \@validstderr);
if($res) {
return $errorreturncode;
}
$ok .= "r";
}
else {
$ok .= "-"; # stderr not checked
}
if(@protocol) {
# Verify the sent request
my @out = loadarray($SERVERIN);
# what to cut off from the live protocol sent by curl
my @strip = getpart("verify", "strip");
my @protstrip=@protocol;
# check if there's any attributes on the verify/protocol section
my %hash = getpartattr("verify", "protocol");
if($hash{'nonewline'}) {
# Yes, we must cut off the final newline from the final line
# of the protocol data
chomp($protstrip[$#protstrip]);
}
for(@strip) {
# strip off all lines that match the patterns from both arrays
chomp $_;
@out = striparray( $_, \@out);
@protstrip= striparray( $_, \@protstrip);
}
# what parts to cut off from the protocol
my @strippart = getpart("verify", "strippart");
my $strip;
for $strip (@strippart) {
chomp $strip;
for(@out) {
eval $strip;
}
}
if((!$out[0] || ($out[0] eq "")) && $protstrip[0]) {
logmsg "\n $testnum: protocol FAILED!\n".
" There was no content at all in the file $SERVERIN.\n".
" Server glitch? Total curl failure? Returned: $cmdres\n";
return $errorreturncode;
}
$res = compare($testnum, $testname, "protocol", \@out, \@protstrip);
if($res) {
return $errorreturncode;
}
$ok .= "p";
}
else {
$ok .= "-"; # protocol not checked
}
if(!$replyattr{'nocheck'} && (@reply || $replyattr{'sendzero'})) {
# verify the received data
my @out = loadarray($CURLOUT);
$res = compare($testnum, $testname, "data", \@out, \@reply);
if ($res) {
return $errorreturncode;
}
$ok .= "d";
}
else {
$ok .= "-"; # data not checked
}
if(@upload) {
# verify uploaded data
my @out = loadarray("$LOGDIR/upload.$testnum");
# what parts to cut off from the upload
my @strippart = getpart("verify", "strippart");
my $strip;
for $strip (@strippart) {
chomp $strip;
for(@out) {
eval $strip;
}
}
$res = compare($testnum, $testname, "upload", \@out, \@upload);
if ($res) {
return $errorreturncode;
}
$ok .= "u";
}
else {
$ok .= "-"; # upload not checked
}
if(@proxyprot) {
# Verify the sent proxy request
my @out = loadarray($PROXYIN);
# what to cut off from the live protocol sent by curl, we use the
# same rules as for <protocol>
my @strip = getpart("verify", "strip");
my @protstrip=@proxyprot;
# check if there's any attributes on the verify/protocol section
my %hash = getpartattr("verify", "proxy");
if($hash{'nonewline'}) {
# Yes, we must cut off the final newline from the final line
# of the protocol data
chomp($protstrip[$#protstrip]);
}
for(@strip) {
# strip off all lines that match the patterns from both arrays
chomp $_;
@out = striparray( $_, \@out);
@protstrip= striparray( $_, \@protstrip);
}
# what parts to cut off from the protocol
my @strippart = getpart("verify", "strippart");
my $strip;
for $strip (@strippart) {
chomp $strip;
for(@out) {
eval $strip;
}
}
$res = compare($testnum, $testname, "proxy", \@out, \@protstrip);
if($res) {
return $errorreturncode;
}
$ok .= "P";
}
else {
$ok .= "-"; # protocol not checked
}
my $outputok;
for my $partsuffix (('', '1', '2', '3', '4')) {
my @outfile=getpart("verify", "file".$partsuffix);
if(@outfile || partexists("verify", "file".$partsuffix) ) {
# we're supposed to verify a dynamically generated file!
my %hash = getpartattr("verify", "file".$partsuffix);
my $filename=$hash{'name'};
if(!$filename) {
logmsg "ERROR: section verify=>file$partsuffix ".
"has no name attribute\n";
stopservers($verbose);
# timestamp test result verification end
$timevrfyend{$testnum} = Time::HiRes::time();
return -1;
}
my @generated=loadarray($filename);
# what parts to cut off from the file
my @stripfile = getpart("verify", "stripfile".$partsuffix);
my $filemode=$hash{'mode'};
if($filemode && ($filemode eq "text") && $has_textaware) {
# text mode when running on windows: fix line endings
map s/\r\n/\n/g, @outfile;
map s/\n/\r\n/g, @outfile;
}
my $strip;
for $strip (@stripfile) {
chomp $strip;
my @newgen;
for(@generated) {
eval $strip;
if($_) {
push @newgen, $_;
}
}
# this is to get rid of array entries that vanished (zero
# length) because of replacements
@generated = @newgen;
}
$res = compare($testnum, $testname, "output ($filename)",
\@generated, \@outfile);
if($res) {
return $errorreturncode;
}
$outputok = 1; # output checked
}
}
$ok .= ($outputok) ? "o" : "-"; # output checked or not
# accept multiple comma-separated error codes
my @splerr = split(/ *, */, $errorcode);
my $errok;
foreach my $e (@splerr) {
if($e == $cmdres) {
# a fine error code
$errok = 1;
last;
}
}
if($errok) {
$ok .= "e";
}
else {
if(!$short) {
logmsg sprintf("\n%s returned $cmdres, when expecting %s\n",
(!$tool)?"curl":$tool, $errorcode);
}
logmsg " exit FAILED\n";
# timestamp test result verification end
$timevrfyend{$testnum} = Time::HiRes::time();
return $errorreturncode;
}
if($has_memory_tracking) {
if(! -f $memdump) {
logmsg "\n** ALERT! memory tracking with no output file?\n"
if(!$cmdtype eq "perl");
}
else {
my @memdata=`$memanalyze $memdump`;
my $leak=0;
for(@memdata) {
if($_ ne "") {
# well it could be other memory problems as well, but
# we call it leak for short here
$leak=1;
}
}
if($leak) {
logmsg "\n** MEMORY FAILURE\n";
logmsg @memdata;
# timestamp test result verification end
$timevrfyend{$testnum} = Time::HiRes::time();
return $errorreturncode;
}
else {
$ok .= "m";
}
}
}
else {
$ok .= "-"; # memory not checked
}
if($valgrind) {
if($usevalgrind) {
unless(opendir(DIR, "$LOGDIR")) {
logmsg "ERROR: unable to read $LOGDIR\n";
# timestamp test result verification end
$timevrfyend{$testnum} = Time::HiRes::time();
return $errorreturncode;
}
my @files = readdir(DIR);
closedir(DIR);
my $vgfile;
foreach my $file (@files) {
if($file =~ /^valgrind$testnum(\..*|)$/) {
$vgfile = $file;
last;
}
}
if(!$vgfile) {
logmsg "ERROR: valgrind log file missing for test $testnum\n";
# timestamp test result verification end
$timevrfyend{$testnum} = Time::HiRes::time();
return $errorreturncode;
}
my @e = valgrindparse("$LOGDIR/$vgfile");
if(@e && $e[0]) {
if($automakestyle) {
logmsg "FAIL: $testnum - $testname - valgrind\n";
}
else {
logmsg " valgrind ERROR ";
logmsg @e;
}
# timestamp test result verification end
$timevrfyend{$testnum} = Time::HiRes::time();
return $errorreturncode;
}
$ok .= "v";
}
else {
if($verbose && !$disablevalgrind) {
logmsg " valgrind SKIPPED\n";
}
$ok .= "-"; # skipped
}
}
else {
$ok .= "-"; # valgrind not checked
}
# add 'E' for event-based
$ok .= $evbased ? "E" : "-";
logmsg "$ok " if(!$short);
# timestamp test result verification end
$timevrfyend{$testnum} = Time::HiRes::time();
my $sofar= time()-$start;
my $esttotal = $sofar/$count * $total;
my $estleft = $esttotal - $sofar;
my $left=sprintf("remaining: %02d:%02d",
$estleft/60,
$estleft%60);
my $took = $timevrfyend{$testnum} - $timeprepini{$testnum};
my $duration = sprintf("duration: %02d:%02d",
$sofar/60, $sofar%60);
if(!$automakestyle) {
logmsg sprintf("OK (%-3d out of %-3d, %s, took %.3fs, %s)\n",
$count, $total, $left, $took, $duration);
}
else {
logmsg "PASS: $testnum - $testname\n";
}
if($errorreturncode==2) {
logmsg "Warning: test$testnum result is ignored, but passed!\n";
}
return 0;
}
#######################################################################
# Stop all running test servers
#
sub stopservers {
my $verbose = $_[0];
#
# kill sockfilter processes for all pingpong servers
#
killallsockfilters($verbose);
#
# kill all server pids from %run hash clearing them
#
my $pidlist;
foreach my $server (keys %run) {
if($run{$server}) {
if($verbose) {
my $prev = 0;
my $pids = $run{$server};
foreach my $pid (split(' ', $pids)) {
if($pid != $prev) {
logmsg sprintf("* kill pid for %s => %d\n",
$server, $pid);
$prev = $pid;
}
}
}
$pidlist .= "$run{$server} ";
$run{$server} = 0;
}
$runcert{$server} = 0 if($runcert{$server});
}
killpid($verbose, $pidlist);
#
# cleanup all server pid files
#
my $result = 0;
foreach my $server (keys %serverpidfile) {
my $pidfile = $serverpidfile{$server};
my $pid = processexists($pidfile);
if($pid > 0) {
if($err_unexpected) {
logmsg "ERROR: ";
$result = -1;
}
else {
logmsg "Warning: ";
}
logmsg "$server server unexpectedly alive\n";
killpid($verbose, $pid);
}
unlink($pidfile) if(-f $pidfile);
}
return $result;
}
#######################################################################
# startservers() starts all the named servers
#
# Returns: string with error reason or blank for success
#
sub startservers {
my @what = @_;
my ($pid, $pid2);
for(@what) {
my (@whatlist) = split(/\s+/,$_);
my $what = lc($whatlist[0]);
$what =~ s/[^a-z0-9\/-]//g;
my $certfile;
if($what =~ /^(ftp|gopher|http|imap|pop3|smtp)s((\d*)(-ipv6|-unix|))$/) {
$certfile = ($whatlist[1]) ? $whatlist[1] : 'stunnel.pem';
}
if(($what eq "pop3") ||
($what eq "ftp") ||
($what eq "imap") ||
($what eq "smtp")) {
if($torture && $run{$what} &&
!responsive_pingpong_server($what, "", $verbose)) {
if(stopserver($what)) {
return "failed stopping unresponsive ".uc($what)." server";
}
}
if(!$run{$what}) {
($pid, $pid2) = runpingpongserver($what, "", $verbose);
if($pid <= 0) {
return "failed starting ". uc($what) ." server";
}
printf ("* pid $what => %d %d\n", $pid, $pid2) if($verbose);
$run{$what}="$pid $pid2";
}
}
elsif($what eq "ftp-ipv6") {
if($torture && $run{'ftp-ipv6'} &&
!responsive_pingpong_server("ftp", "", $verbose, "ipv6")) {
if(stopserver('ftp-ipv6')) {
return "failed stopping unresponsive FTP-IPv6 server";
}
}
if(!$run{'ftp-ipv6'}) {
($pid, $pid2) = runpingpongserver("ftp", "", $verbose, "ipv6");
if($pid <= 0) {
return "failed starting FTP-IPv6 server";
}
logmsg sprintf("* pid ftp-ipv6 => %d %d\n", $pid,
$pid2) if($verbose);
$run{'ftp-ipv6'}="$pid $pid2";
}
}
elsif($what eq "gopher") {
if($torture && $run{'gopher'} &&
!responsive_http_server("gopher", $verbose, 0, $GOPHERPORT)) {
if(stopserver('gopher')) {
return "failed stopping unresponsive GOPHER server";
}
}
if(!$run{'gopher'}) {
($pid, $pid2, $GOPHERPORT) =
runhttpserver("gopher", $verbose, 0);
if($pid <= 0) {
return "failed starting GOPHER server";
}
logmsg sprintf ("* pid gopher => %d %d\n", $pid, $pid2)
if($verbose);
$run{'gopher'}="$pid $pid2";
}
}
elsif($what eq "gopher-ipv6") {
if($torture && $run{'gopher-ipv6'} &&
!responsive_http_server("gopher", $verbose, "ipv6",
$GOPHER6PORT)) {
if(stopserver('gopher-ipv6')) {
return "failed stopping unresponsive GOPHER-IPv6 server";
}
}
if(!$run{'gopher-ipv6'}) {
($pid, $pid2, $GOPHER6PORT) =
runhttpserver("gopher", $verbose, "ipv6");
if($pid <= 0) {
return "failed starting GOPHER-IPv6 server";
}
logmsg sprintf("* pid gopher-ipv6 => %d %d\n", $pid,
$pid2) if($verbose);
$run{'gopher-ipv6'}="$pid $pid2";
}
}
elsif($what eq "http/2") {
if(!$run{'http/2'}) {
($pid, $pid2, $HTTP2PORT) = runhttp2server($verbose);
if($pid <= 0) {
return "failed starting HTTP/2 server";
}
logmsg sprintf ("* pid http/2 => %d %d\n", $pid, $pid2)
if($verbose);
$run{'http/2'}="$pid $pid2";
}
}
elsif($what eq "http") {
if($torture && $run{'http'} &&
!responsive_http_server("http", $verbose, 0, $HTTPPORT)) {
if(stopserver('http')) {
return "failed stopping unresponsive HTTP server";
}
}
if(!$run{'http'}) {
($pid, $pid2, $HTTPPORT) =
runhttpserver("http", $verbose, 0);
if($pid <= 0) {
return "failed starting HTTP server";
}
logmsg sprintf ("* pid http => %d %d\n", $pid, $pid2)
if($verbose);
$run{'http'}="$pid $pid2";
}
}
elsif($what eq "http-proxy") {
if($torture && $run{'http-proxy'} &&
!responsive_http_server("http", $verbose, "proxy",
$HTTPPROXYPORT)) {
if(stopserver('http-proxy')) {
return "failed stopping unresponsive HTTP-proxy server";
}
}
if(!$run{'http-proxy'}) {
($pid, $pid2, $HTTPPROXYPORT) =
runhttpserver("http", $verbose, "proxy");
if($pid <= 0) {
return "failed starting HTTP-proxy server";
}
logmsg sprintf ("* pid http-proxy => %d %d\n", $pid, $pid2)
if($verbose);
$run{'http-proxy'}="$pid $pid2";
}
}
elsif($what eq "http-ipv6") {
if($torture && $run{'http-ipv6'} &&
!responsive_http_server("http", $verbose, "ipv6", $HTTP6PORT)) {
if(stopserver('http-ipv6')) {
return "failed stopping unresponsive HTTP-IPv6 server";
}
}
if(!$run{'http-ipv6'}) {
($pid, $pid2, $HTTP6PORT) =
runhttpserver("http", $verbose, "ipv6");
if($pid <= 0) {
return "failed starting HTTP-IPv6 server";
}
logmsg sprintf("* pid http-ipv6 => %d %d\n", $pid, $pid2)
if($verbose);
$run{'http-ipv6'}="$pid $pid2";
}
}
elsif($what eq "rtsp") {
if($torture && $run{'rtsp'} &&
!responsive_rtsp_server($verbose)) {
if(stopserver('rtsp')) {
return "failed stopping unresponsive RTSP server";
}
}
if(!$run{'rtsp'}) {
($pid, $pid2, $RTSPPORT) = runrtspserver($verbose);
if($pid <= 0) {
return "failed starting RTSP server";
}
printf ("* pid rtsp => %d %d\n", $pid, $pid2) if($verbose);
$run{'rtsp'}="$pid $pid2";
}
}
elsif($what eq "rtsp-ipv6") {
if($torture && $run{'rtsp-ipv6'} &&
!responsive_rtsp_server($verbose, "ipv6")) {
if(stopserver('rtsp-ipv6')) {
return "failed stopping unresponsive RTSP-IPv6 server";
}
}
if(!$run{'rtsp-ipv6'}) {
($pid, $pid2, $RTSP6PORT) = runrtspserver($verbose, "ipv6");
if($pid <= 0) {
return "failed starting RTSP-IPv6 server";
}
logmsg sprintf("* pid rtsp-ipv6 => %d %d\n", $pid, $pid2)
if($verbose);
$run{'rtsp-ipv6'}="$pid $pid2";
}
}
elsif($what eq "ftps") {
if(!$stunnel) {
# we can't run ftps tests without stunnel
return "no stunnel";
}
if($runcert{'ftps'} && ($runcert{'ftps'} ne $certfile)) {
# stop server when running and using a different cert
if(stopserver('ftps')) {
return "failed stopping FTPS server with different cert";
}
}
if($torture && $run{'ftp'} &&
!responsive_pingpong_server("ftp", "", $verbose)) {
if(stopserver('ftp')) {
return "failed stopping unresponsive FTP server";
}
}
if(!$run{'ftp'}) {
($pid, $pid2) = runpingpongserver("ftp", "", $verbose);
if($pid <= 0) {
return "failed starting FTP server";
}
printf ("* pid ftp => %d %d\n", $pid, $pid2) if($verbose);
$run{'ftp'}="$pid $pid2";
}
if(!$run{'ftps'}) {
($pid, $pid2, $FTPSPORT) =
runftpsserver($verbose, "", $certfile);
if($pid <= 0) {
return "failed starting FTPS server (stunnel)";
}
logmsg sprintf("* pid ftps => %d %d\n", $pid, $pid2)
if($verbose);
$run{'ftps'}="$pid $pid2";
}
}
elsif($what eq "file") {
# we support it but have no server!
}
elsif($what eq "https") {
if(!$stunnel) {
# we can't run https tests without stunnel
return "no stunnel";
}
if($runcert{'https'} && ($runcert{'https'} ne $certfile)) {
# stop server when running and using a different cert
if(stopserver('https')) {
return "failed stopping HTTPS server with different cert";
}
}
if($torture && $run{'http'} &&
!responsive_http_server("http", $verbose, 0, $HTTPPORT)) {
if(stopserver('http')) {
return "failed stopping unresponsive HTTP server";
}
}
if(!$run{'http'}) {
($pid, $pid2, $HTTPPORT) =
runhttpserver("http", $verbose, 0);
if($pid <= 0) {
return "failed starting HTTP server";
}
printf ("* pid http => %d %d\n", $pid, $pid2) if($verbose);
$run{'http'}="$pid $pid2";
}
if(!$run{'https'}) {
($pid, $pid2, $HTTPSPORT) =
runhttpsserver($verbose, "https", "", $certfile);
if($pid <= 0) {
return "failed starting HTTPS server (stunnel)";
}
logmsg sprintf("* pid https => %d %d\n", $pid, $pid2)
if($verbose);
$run{'https'}="$pid $pid2";
}
}
elsif($what eq "gophers") {
if(!$stunnel) {
# we can't run TLS tests without stunnel
return "no stunnel";
}
if($runcert{'gophers'} && ($runcert{'gophers'} ne $certfile)) {
# stop server when running and using a different cert
if(stopserver('gophers')) {
return "failed stopping GOPHERS server with different crt";
}
}
if($torture && $run{'gopher'} &&
!responsive_http_server("gopher", $verbose, 0, $GOPHERPORT)) {
if(stopserver('gopher')) {
return "failed stopping unresponsive GOPHER server";
}
}
if(!$run{'gopher'}) {
($pid, $pid2, $GOPHERPORT) =
runhttpserver("gopher", $verbose, 0);
if($pid <= 0) {
return "failed starting GOPHER server";
}
printf ("* pid gopher => %d %d\n", $pid, $pid2) if($verbose);
print "GOPHERPORT => $GOPHERPORT\n" if($verbose);
$run{'gopher'}="$pid $pid2";
}
if(!$run{'gophers'}) {
($pid, $pid2, $GOPHERSPORT) =
runhttpsserver($verbose, "gophers", "", $certfile);
if($pid <= 0) {
return "failed starting GOPHERS server (stunnel)";
}
logmsg sprintf("* pid gophers => %d %d\n", $pid, $pid2)
if($verbose);
print "GOPHERSPORT => $GOPHERSPORT\n" if($verbose);
$run{'gophers'}="$pid $pid2";
}
}
elsif($what eq "https-proxy") {
if(!$stunnel) {
# we can't run https-proxy tests without stunnel
return "no stunnel";
}
if($runcert{'https-proxy'} &&
($runcert{'https-proxy'} ne $certfile)) {
# stop server when running and using a different cert
if(stopserver('https-proxy')) {
return "failed stopping HTTPS-proxy with different cert";
}
}
# we front the http-proxy with stunnel so we need to make sure the
# proxy runs as well
my $f = startservers("http-proxy");
if($f) {
return $f;1
}
if(!$run{'https-proxy'}) {
($pid, $pid2, $HTTPSPROXYPORT) =
runhttpsserver($verbose, "https", "proxy", $certfile);
if($pid <= 0) {
return "failed starting HTTPS-proxy (stunnel)";
}
logmsg sprintf("* pid https-proxy => %d %d\n", $pid, $pid2)
if($verbose);
$run{'https-proxy'}="$pid $pid2";
}
}
elsif($what eq "httptls") {
if(!$httptlssrv) {
# for now, we can't run http TLS-EXT tests without gnutls-serv
return "no gnutls-serv";
}
if($torture && $run{'httptls'} &&
!responsive_httptls_server($verbose, "IPv4")) {
if(stopserver('httptls')) {
return "failed stopping unresponsive HTTPTLS server";
}
}
if(!$run{'httptls'}) {
($pid, $pid2, $HTTPTLSPORT) =
runhttptlsserver($verbose, "IPv4");
if($pid <= 0) {
return "failed starting HTTPTLS server (gnutls-serv)";
}
logmsg sprintf("* pid httptls => %d %d\n", $pid, $pid2)
if($verbose);
$run{'httptls'}="$pid $pid2";
}
}
elsif($what eq "httptls-ipv6") {
if(!$httptlssrv) {
# for now, we can't run http TLS-EXT tests without gnutls-serv
return "no gnutls-serv";
}
if($torture && $run{'httptls-ipv6'} &&
!responsive_httptls_server($verbose, "ipv6")) {
if(stopserver('httptls-ipv6')) {
return "failed stopping unresponsive HTTPTLS-IPv6 server";
}
}
if(!$run{'httptls-ipv6'}) {
($pid, $pid2, $HTTPTLS6PORT) =
runhttptlsserver($verbose, "ipv6");
if($pid <= 0) {
return "failed starting HTTPTLS-IPv6 server (gnutls-serv)";
}
logmsg sprintf("* pid httptls-ipv6 => %d %d\n", $pid, $pid2)
if($verbose);
$run{'httptls-ipv6'}="$pid $pid2";
}
}
elsif($what eq "tftp") {
if($torture && $run{'tftp'} &&
!responsive_tftp_server("", $verbose)) {
if(stopserver('tftp')) {
return "failed stopping unresponsive TFTP server";
}
}
if(!$run{'tftp'}) {
($pid, $pid2, $TFTPPORT) =
runtftpserver("", $verbose);
if($pid <= 0) {
return "failed starting TFTP server";
}
printf ("* pid tftp => %d %d\n", $pid, $pid2) if($verbose);
$run{'tftp'}="$pid $pid2";
}
}
elsif($what eq "tftp-ipv6") {
if($torture && $run{'tftp-ipv6'} &&
!responsive_tftp_server("", $verbose, "ipv6")) {
if(stopserver('tftp-ipv6')) {
return "failed stopping unresponsive TFTP-IPv6 server";
}
}
if(!$run{'tftp-ipv6'}) {
($pid, $pid2, $TFTP6PORT) =
runtftpserver("", $verbose, "ipv6");
if($pid <= 0) {
return "failed starting TFTP-IPv6 server";
}
printf("* pid tftp-ipv6 => %d %d\n", $pid, $pid2) if($verbose);
$run{'tftp-ipv6'}="$pid $pid2";
}
}
elsif($what eq "sftp" || $what eq "scp") {
if(!$run{'ssh'}) {
($pid, $pid2, $SSHPORT) = runsshserver("", $verbose);
if($pid <= 0) {
return "failed starting SSH server";
}
printf ("* pid ssh => %d %d\n", $pid, $pid2) if($verbose);
$run{'ssh'}="$pid $pid2";
}
}
elsif($what eq "socks4" || $what eq "socks5" ) {
if(!$run{'socks'}) {
($pid, $pid2, $SOCKSPORT) = runsocksserver("", $verbose);
if($pid <= 0) {
return "failed starting socks server";
}
printf ("* pid socks => %d %d\n", $pid, $pid2) if($verbose);
$run{'socks'}="$pid $pid2";
}
}
elsif($what eq "mqtt" ) {
if(!$run{'mqtt'}) {
($pid, $pid2) = runmqttserver("", $verbose);
if($pid <= 0) {
return "failed starting mqtt server";
}
printf ("* pid mqtt => %d %d\n", $pid, $pid2) if($verbose);
$run{'mqtt'}="$pid $pid2";
}
}
elsif($what eq "http-unix") {
if($torture && $run{'http-unix'} &&
!responsive_http_server("http", $verbose, "unix", $HTTPUNIXPATH)) {
if(stopserver('http-unix')) {
return "failed stopping unresponsive HTTP-unix server";
}
}
if(!$run{'http-unix'}) {
my $unused;
($pid, $pid2, $unused) =
runhttpserver("http", $verbose, "unix", $HTTPUNIXPATH);
if($pid <= 0) {
return "failed starting HTTP-unix server";
}
logmsg sprintf("* pid http-unix => %d %d\n", $pid, $pid2)
if($verbose);
$run{'http-unix'}="$pid $pid2";
}
}
elsif($what eq "dict") {
if(!$run{'dict'}) {
($pid, $pid2, $DICTPORT) = rundictserver($verbose, "");
if($pid <= 0) {
return "failed starting DICT server";
}
logmsg sprintf ("* pid DICT => %d %d\n", $pid, $pid2)
if($verbose);
$run{'dict'}="$pid $pid2";
}
}
elsif($what eq "smb") {
if(!$run{'smb'}) {
($pid, $pid2, $SMBPORT) = runsmbserver($verbose, "");
if($pid <= 0) {
return "failed starting SMB server";
}
logmsg sprintf ("* pid SMB => %d %d\n", $pid, $pid2)
if($verbose);
$run{'smb'}="$pid $pid2";
}
}
elsif($what eq "telnet") {
if(!$run{'telnet'}) {
($pid, $pid2, $TELNETPORT) =
runnegtelnetserver($verbose, "");
if($pid <= 0) {
return "failed starting neg TELNET server";
}
logmsg sprintf ("* pid neg TELNET => %d %d\n", $pid, $pid2)
if($verbose);
$run{'telnet'}="$pid $pid2";
}
}
elsif($what eq "none") {
logmsg "* starts no server\n" if ($verbose);
}
else {
warn "we don't support a server for $what";
return "no server for $what";
}
}
return 0;
}
##############################################################################
# This function makes sure the right set of server is running for the
# specified test case. This is a useful design when we run single tests as not
# all servers need to run then!
#
# Returns: a string, blank if everything is fine or a reason why it failed
#
sub serverfortest {
my ($testnum)=@_;
my @what = getpart("client", "server");
if(!$what[0]) {
warn "Test case $testnum has no server(s) specified";
return "no server specified";
}
for(my $i = scalar(@what) - 1; $i >= 0; $i--) {
my $srvrline = $what[$i];
chomp $srvrline if($srvrline);
if($srvrline =~ /^(\S+)((\s*)(.*))/) {
my $server = "${1}";
my $lnrest = "${2}";
my $tlsext;
if($server =~ /^(httptls)(\+)(ext|srp)(\d*)(-ipv6|)$/) {
$server = "${1}${4}${5}";
$tlsext = uc("TLS-${3}");
}
if(! grep /^\Q$server\E$/, @protocols) {
if(substr($server,0,5) ne "socks") {
if($tlsext) {
return "curl lacks $tlsext support";
}
else {
return "curl lacks $server server support";
}
}
}
$what[$i] = "$server$lnrest" if($tlsext);
}
}
return &startservers(@what);
}
#######################################################################
# runtimestats displays test-suite run time statistics
#
sub runtimestats {
my $lasttest = $_[0];
return if(not $timestats);
logmsg "\nTest suite total running time breakdown per task...\n\n";
my @timesrvr;
my @timeprep;
my @timetool;
my @timelock;
my @timevrfy;
my @timetest;
my $timesrvrtot = 0.0;
my $timepreptot = 0.0;
my $timetooltot = 0.0;
my $timelocktot = 0.0;
my $timevrfytot = 0.0;
my $timetesttot = 0.0;
my $counter;
for my $testnum (1 .. $lasttest) {
if($timesrvrini{$testnum}) {
$timesrvrtot += $timesrvrend{$testnum} - $timesrvrini{$testnum};
$timepreptot +=
(($timetoolini{$testnum} - $timeprepini{$testnum}) -
($timesrvrend{$testnum} - $timesrvrini{$testnum}));
$timetooltot += $timetoolend{$testnum} - $timetoolini{$testnum};
$timelocktot += $timesrvrlog{$testnum} - $timetoolend{$testnum};
$timevrfytot += $timevrfyend{$testnum} - $timesrvrlog{$testnum};
$timetesttot += $timevrfyend{$testnum} - $timeprepini{$testnum};
push @timesrvr, sprintf("%06.3f %04d",
$timesrvrend{$testnum} - $timesrvrini{$testnum}, $testnum);
push @timeprep, sprintf("%06.3f %04d",
($timetoolini{$testnum} - $timeprepini{$testnum}) -
($timesrvrend{$testnum} - $timesrvrini{$testnum}), $testnum);
push @timetool, sprintf("%06.3f %04d",
$timetoolend{$testnum} - $timetoolini{$testnum}, $testnum);
push @timelock, sprintf("%06.3f %04d",
$timesrvrlog{$testnum} - $timetoolend{$testnum}, $testnum);
push @timevrfy, sprintf("%06.3f %04d",
$timevrfyend{$testnum} - $timesrvrlog{$testnum}, $testnum);
push @timetest, sprintf("%06.3f %04d",
$timevrfyend{$testnum} - $timeprepini{$testnum}, $testnum);
}
}
{
no warnings 'numeric';
@timesrvr = sort { $b <=> $a } @timesrvr;
@timeprep = sort { $b <=> $a } @timeprep;
@timetool = sort { $b <=> $a } @timetool;
@timelock = sort { $b <=> $a } @timelock;
@timevrfy = sort { $b <=> $a } @timevrfy;
@timetest = sort { $b <=> $a } @timetest;
}
logmsg "Spent ". sprintf("%08.3f ", $timesrvrtot) .
"seconds starting and verifying test harness servers.\n";
logmsg "Spent ". sprintf("%08.3f ", $timepreptot) .
"seconds reading definitions and doing test preparations.\n";
logmsg "Spent ". sprintf("%08.3f ", $timetooltot) .
"seconds actually running test tools.\n";
logmsg "Spent ". sprintf("%08.3f ", $timelocktot) .
"seconds awaiting server logs lock removal.\n";
logmsg "Spent ". sprintf("%08.3f ", $timevrfytot) .
"seconds verifying test results.\n";
logmsg "Spent ". sprintf("%08.3f ", $timetesttot) .
"seconds doing all of the above.\n";
$counter = 25;
logmsg "\nTest server starting and verification time per test ".
sprintf("(%s)...\n\n", (not $fullstats)?"top $counter":"full");
logmsg "-time- test\n";
logmsg "------ ----\n";
foreach my $txt (@timesrvr) {
last if((not $fullstats) && (not $counter--));
logmsg "$txt\n";
}
$counter = 10;
logmsg "\nTest definition reading and preparation time per test ".
sprintf("(%s)...\n\n", (not $fullstats)?"top $counter":"full");
logmsg "-time- test\n";
logmsg "------ ----\n";
foreach my $txt (@timeprep) {
last if((not $fullstats) && (not $counter--));
logmsg "$txt\n";
}
$counter = 25;
logmsg "\nTest tool execution time per test ".
sprintf("(%s)...\n\n", (not $fullstats)?"top $counter":"full");
logmsg "-time- test\n";
logmsg "------ ----\n";
foreach my $txt (@timetool) {
last if((not $fullstats) && (not $counter--));
logmsg "$txt\n";
}
$counter = 15;
logmsg "\nTest server logs lock removal time per test ".
sprintf("(%s)...\n\n", (not $fullstats)?"top $counter":"full");
logmsg "-time- test\n";
logmsg "------ ----\n";
foreach my $txt (@timelock) {
last if((not $fullstats) && (not $counter--));
logmsg "$txt\n";
}
$counter = 10;
logmsg "\nTest results verification time per test ".
sprintf("(%s)...\n\n", (not $fullstats)?"top $counter":"full");
logmsg "-time- test\n";
logmsg "------ ----\n";
foreach my $txt (@timevrfy) {
last if((not $fullstats) && (not $counter--));
logmsg "$txt\n";
}
$counter = 50;
logmsg "\nTotal time per test ".
sprintf("(%s)...\n\n", (not $fullstats)?"top $counter":"full");
logmsg "-time- test\n";
logmsg "------ ----\n";
foreach my $txt (@timetest) {
last if((not $fullstats) && (not $counter--));
logmsg "$txt\n";
}
logmsg "\n";
}
#######################################################################
# Check options to this test program
#
# Special case for CMake: replace '$TFLAGS' by the contents of the
# environment variable (if any).
if(@ARGV && $ARGV[-1] eq '$TFLAGS') {
pop @ARGV;
push(@ARGV, split(' ', $ENV{'TFLAGS'})) if defined($ENV{'TFLAGS'});
}
my $number=0;
my $fromnum=-1;
my @testthis;
while(@ARGV) {
if ($ARGV[0] eq "-v") {
# verbose output
$verbose=1;
}
elsif ($ARGV[0] eq "-c") {
# use this path to curl instead of default
$DBGCURL=$CURL="\"$ARGV[1]\"";
shift @ARGV;
}
elsif ($ARGV[0] eq "-vc") {
# use this path to a curl used to verify servers
# Particularly useful when you introduce a crashing bug somewhere in
# the development version as then it won't be able to run any tests
# since it can't verify the servers!
$VCURL="\"$ARGV[1]\"";
shift @ARGV;
}
elsif ($ARGV[0] eq "-d") {
# have the servers display protocol output
$debugprotocol=1;
}
elsif($ARGV[0] eq "-e") {
# run the tests cases event based if possible
$run_event_based=1;
}
elsif($ARGV[0] eq "-f") {
# force - run the test case even if listed in DISABLED
$run_disabeled=1;
}
elsif($ARGV[0] eq "-E") {
# load additional reasons to skip tests
shift @ARGV;
my $exclude_file = $ARGV[0];
open(my $fd, "<", $exclude_file) or die "Couldn't open '$exclude_file': $!";
while(my $line = <$fd>) {
next if ($line =~ /^#/);
chomp $line;
my ($type, $patterns, $skip_reason) = split(/\s*:\s*/, $line, 3);
die "Unsupported type: $type\n" if($type !~ /^keyword|test|tool$/);
foreach my $pattern (split(/,/, $patterns)) {
if($type =~ /^test$/) {
# Strip leading zeros in the test number
$pattern = int($pattern);
}
$custom_skip_reasons{$type}{$pattern} = $skip_reason;
}
}
close($fd);
}
elsif ($ARGV[0] eq "-g") {
# run this test with gdb
$gdbthis=1;
}
elsif ($ARGV[0] eq "-gw") {
# run this test with windowed gdb
$gdbthis=1;
$gdbxwin=1;
}
elsif($ARGV[0] eq "-s") {
# short output
$short=1;
}
elsif($ARGV[0] eq "-am") {
# automake-style output
$short=1;
$automakestyle=1;
}
elsif($ARGV[0] eq "-n") {
# no valgrind
undef $valgrind;
}
elsif ($ARGV[0] eq "-R") {
# execute in scrambled order
$scrambleorder=1;
}
elsif($ARGV[0] =~ /^-t(.*)/) {
# torture
$torture=1;
my $xtra = $1;
if($xtra =~ s/(\d+)$//) {
$tortalloc = $1;
}
}
elsif($ARGV[0] =~ /--shallow=(\d+)/) {
# Fail no more than this amount per tests when running
# torture.
my ($num)=($1);
$shallow=$num;
}
elsif($ARGV[0] =~ /--repeat=(\d+)/) {
# Repeat-run the given tests this many times
$repeat = $1;
}
elsif($ARGV[0] =~ /--seed=(\d+)/) {
# Set a fixed random seed (used for -R and --shallow)
$randseed = $1;
}
elsif($ARGV[0] eq "-a") {
# continue anyway, even if a test fail
$anyway=1;
}
elsif($ARGV[0] eq "-o") {
shift @ARGV;
if ($ARGV[0] =~ /^(\w+)=([\w.:\/\[\]-]+)$/) {
my ($variable, $value) = ($1, $2);
eval "\$$variable='$value'" or die "Failed to set \$$variable to $value: $@";
} else {
die "Failed to parse '-o $ARGV[0]'. May contain unexpected characters.\n";
}
}
elsif($ARGV[0] eq "-p") {
$postmortem=1;
}
elsif($ARGV[0] eq "-P") {
shift @ARGV;
$use_external_proxy=1;
$proxy_address=$ARGV[0];
}
elsif($ARGV[0] eq "-L") {
# require additional library file
shift @ARGV;
require $ARGV[0];
}
elsif($ARGV[0] eq "-l") {
# lists the test case names only
$listonly=1;
}
elsif($ARGV[0] eq "-k") {
# keep stdout and stderr files after tests
$keepoutfiles=1;
}
elsif($ARGV[0] eq "-r") {
# run time statistics needs Time::HiRes
if($Time::HiRes::VERSION) {
keys(%timeprepini) = 1000;
keys(%timesrvrini) = 1000;
keys(%timesrvrend) = 1000;
keys(%timetoolini) = 1000;
keys(%timetoolend) = 1000;
keys(%timesrvrlog) = 1000;
keys(%timevrfyend) = 1000;
$timestats=1;
$fullstats=0;
}
}
elsif($ARGV[0] eq "-rf") {
# run time statistics needs Time::HiRes
if($Time::HiRes::VERSION) {
keys(%timeprepini) = 1000;
keys(%timesrvrini) = 1000;
keys(%timesrvrend) = 1000;
keys(%timetoolini) = 1000;
keys(%timetoolend) = 1000;
keys(%timesrvrlog) = 1000;
keys(%timevrfyend) = 1000;
$timestats=1;
$fullstats=1;
}
}
elsif($ARGV[0] eq "-rm") {
# force removal of files by killing locking processes
$clearlocks=1;
}
elsif($ARGV[0] eq "-u") {
# error instead of warning on server unexpectedly alive
$err_unexpected=1;
}
elsif(($ARGV[0] eq "-h") || ($ARGV[0] eq "--help")) {
# show help text
print <<EOHELP
Usage: runtests.pl [options] [test selection(s)]
-a continue even if a test fails
-am automake style output PASS/FAIL: [number] [name]
-c path use this curl executable
-d display server debug info
-e event-based execution
-E file load the specified file to exclude certain tests
-f forcibly run even if disabled
-g run the test case with gdb
-gw run the test case with gdb as a windowed application
-h this help text
-k keep stdout and stderr files present after tests
-L path require an additional perl library file to replace certain functions
-l list all test case names/descriptions
-n no valgrind
-o variable=value set internal variable to the specified value
-P proxy use the specified proxy
-p print log file contents when a test fails
-R scrambled order (uses the random seed, see --seed)
-r run time statistics
-rf full run time statistics
-rm force removal of files by killing locking processes (Windows only)
-s short output
--seed=[num] set the random seed to a fixed number
--shallow=[num] randomly makes the torture tests "thinner"
-t[N] torture (simulate function failures); N means fail Nth function
-u error instead of warning on server unexpectedly alive
-v verbose output
-vc path use this curl only to verify the existing servers
[num] like "5 6 9" or " 5 to 22 " to run those tests only
[!num] like "!5 !6 !9" to disable those tests
[~num] like "~5 ~6 ~9" to ignore the result of those tests
[keyword] like "IPv6" to select only tests containing the key word
[!keyword] like "!cookies" to disable any tests containing the key word
[~keyword] like "~cookies" to ignore results of tests containing key word
EOHELP
;
exit;
}
elsif($ARGV[0] =~ /^(\d+)/) {
$number = $1;
if($fromnum >= 0) {
for my $n ($fromnum .. $number) {
push @testthis, $n;
}
$fromnum = -1;
}
else {
push @testthis, $1;
}
}
elsif($ARGV[0] =~ /^to$/i) {
$fromnum = $number+1;
}
elsif($ARGV[0] =~ /^!(\d+)/) {
$fromnum = -1;
$disabled{$1}=$1;
}
elsif($ARGV[0] =~ /^~(\d+)/) {
$fromnum = -1;
$ignored{$1}=$1;
}
elsif($ARGV[0] =~ /^!(.+)/) {
$disabled_keywords{lc($1)}=$1;
}
elsif($ARGV[0] =~ /^~(.+)/) {
$ignored_keywords{lc($1)}=$1;
}
elsif($ARGV[0] =~ /^([-[{a-zA-Z].*)/) {
$enabled_keywords{lc($1)}=$1;
}
else {
print "Unknown option: $ARGV[0]\n";
exit;
}
shift @ARGV;
}
if(!$randseed) {
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
localtime(time);
# seed of the month. December 2019 becomes 201912
$randseed = ($year+1900)*100 + $mon+1;
open(C, "$CURL --version 2>/dev/null|");
my @c = <C>;
close(C);
# use the first line of output and get the md5 out of it
my $str = md5($c[0]);
$randseed += unpack('S', $str); # unsigned 16 bit value
}
srand $randseed;
if(@testthis && ($testthis[0] ne "")) {
$TESTCASES=join(" ", @testthis);
}
if($valgrind) {
# we have found valgrind on the host, use it
# verify that we can invoke it fine
my $code = runclient("valgrind >/dev/null 2>&1");
if(($code>>8) != 1) {
#logmsg "Valgrind failure, disable it\n";
undef $valgrind;
} else {
# since valgrind 2.1.x, '--tool' option is mandatory
# use it, if it is supported by the version installed on the system
runclient("valgrind --help 2>&1 | grep -- --tool > /dev/null 2>&1");
if (($? >> 8)==0) {
$valgrind_tool="--tool=memcheck";
}
open(C, "<$CURL");
my $l = <C>;
if($l =~ /^\#\!/) {
# A shell script. This is typically when built with libtool,
$valgrind="../libtool --mode=execute $valgrind";
}
close(C);
# valgrind 3 renamed the --logfile option to --log-file!!!
my $ver=join(' ', runclientoutput("valgrind --version"));
# cut off all but digits and dots
$ver =~ s/[^0-9.]//g;
if($ver =~ /^(\d+)/) {
$ver = $1;
if($ver >= 3) {
$valgrind_logfile="--log-file";
}
}
}
}
if ($gdbthis) {
# open the executable curl and read the first 4 bytes of it
open(CHECK, "<$CURL");
my $c;
sysread CHECK, $c, 4;
close(CHECK);
if($c eq "#! /") {
# A shell script. This is typically when built with libtool,
$libtool = 1;
$gdb = "../libtool --mode=execute gdb";
}
}
$HTTPUNIXPATH = "http$$.sock"; # HTTP server Unix domain socket path
#######################################################################
# clear and create logging directory:
#
cleardir($LOGDIR);
mkdir($LOGDIR, 0777);
#######################################################################
# initialize some variables
#
get_disttests();
init_serverpidfile_hash();
#######################################################################
# Output curl version and host info being tested
#
if(!$listonly) {
checksystem();
}
# globally disabled tests
disabledtests("$TESTDIR/DISABLED");
#######################################################################
# Fetch all disabled tests, if there are any
#
sub disabledtests {
my ($file) = @_;
my @input;
if(open(D, "<$file")) {
while(<D>) {
if(/^ *\#/) {
# allow comments
next;
}
push @input, $_;
}
close(D);
# preprocess the input to make conditionally disabled tests depending
# on variables
my @pp = prepro(0, @input);
for my $t (@pp) {
if($t =~ /(\d+)/) {
my ($n) = $1;
$disabled{$n}=$n; # disable this test number
if(! -f "$srcdir/data/test$n") {
print STDERR "WARNING! Non-existing test $n in $file!\n";
# fail hard to make user notice
exit 1;
}
logmsg "DISABLED: test $n\n" if ($verbose);
}
else {
print STDERR "$file: rubbish content: $t\n";
exit 2;
}
}
}
}
#######################################################################
# If 'all' tests are requested, find out all test numbers
#
if ( $TESTCASES eq "all") {
# Get all commands and find out their test numbers
opendir(DIR, $TESTDIR) || die "can't opendir $TESTDIR: $!";
my @cmds = grep { /^test([0-9]+)$/ && -f "$TESTDIR/$_" } readdir(DIR);
closedir(DIR);
$TESTCASES=""; # start with no test cases
# cut off everything but the digits
for(@cmds) {
$_ =~ s/[a-z\/\.]*//g;
}
# sort the numbers from low to high
foreach my $n (sort { $a <=> $b } @cmds) {
if($disabled{$n}) {
# skip disabled test cases
my $why = "configured as DISABLED";
$skipped++;
$skipped{$why}++;
$teststat[$n]=$why; # store reason for this test case
next;
}
$TESTCASES .= " $n";
}
}
else {
my $verified="";
map {
if (-e "$TESTDIR/test$_") {
$verified.="$_ ";
}
} split(" ", $TESTCASES);
if($verified eq "") {
print "No existing test cases were specified\n";
exit;
}
$TESTCASES = $verified;
}
if($repeat) {
my $s;
for(1 .. $repeat) {
$s .= $TESTCASES;
}
$TESTCASES = $s;
}
if($scrambleorder) {
# scramble the order of the test cases
my @rand;
while($TESTCASES) {
my @all = split(/ +/, $TESTCASES);
if(!$all[0]) {
# if the first is blank, shift away it
shift @all;
}
my $r = rand @all;
push @rand, $all[$r];
$all[$r]="";
$TESTCASES = join(" ", @all);
}
$TESTCASES = join(" ", @rand);
}
# Display the contents of the given file. Line endings are canonicalized
# and excessively long files are elided
sub displaylogcontent {
my ($file)=@_;
if(open(SINGLE, "<$file")) {
my $linecount = 0;
my $truncate;
my @tail;
while(my $string = <SINGLE>) {
$string =~ s/\r\n/\n/g;
$string =~ s/[\r\f\032]/\n/g;
$string .= "\n" unless ($string =~ /\n$/);
$string =~ tr/\n//;
for my $line (split("\n", $string)) {
$line =~ s/\s*\!$//;
if ($truncate) {
push @tail, " $line\n";
} else {
logmsg " $line\n";
}
$linecount++;
$truncate = $linecount > 1000;
}
}
if(@tail) {
my $tailshow = 200;
my $tailskip = 0;
my $tailtotal = scalar @tail;
if($tailtotal > $tailshow) {
$tailskip = $tailtotal - $tailshow;
logmsg "=== File too long: $tailskip lines omitted here\n";
}
for($tailskip .. $tailtotal-1) {
logmsg "$tail[$_]";
}
}
close(SINGLE);
}
}
sub displaylogs {
my ($testnum)=@_;
opendir(DIR, "$LOGDIR") ||
die "can't open dir: $!";
my @logs = readdir(DIR);
closedir(DIR);
logmsg "== Contents of files in the $LOGDIR/ dir after test $testnum\n";
foreach my $log (sort @logs) {
if($log =~ /\.(\.|)$/) {
next; # skip "." and ".."
}
if($log =~ /^\.nfs/) {
next; # skip ".nfs"
}
if(($log eq "memdump") || ($log eq "core")) {
next; # skip "memdump" and "core"
}
if((-d "$LOGDIR/$log") || (! -s "$LOGDIR/$log")) {
next; # skip directory and empty files
}
if(($log =~ /^stdout\d+/) && ($log !~ /^stdout$testnum/)) {
next; # skip stdoutNnn of other tests
}
if(($log =~ /^stderr\d+/) && ($log !~ /^stderr$testnum/)) {
next; # skip stderrNnn of other tests
}
if(($log =~ /^upload\d+/) && ($log !~ /^upload$testnum/)) {
next; # skip uploadNnn of other tests
}
if(($log =~ /^curl\d+\.out/) && ($log !~ /^curl$testnum\.out/)) {
next; # skip curlNnn.out of other tests
}
if(($log =~ /^test\d+\.txt/) && ($log !~ /^test$testnum\.txt/)) {
next; # skip testNnn.txt of other tests
}
if(($log =~ /^file\d+\.txt/) && ($log !~ /^file$testnum\.txt/)) {
next; # skip fileNnn.txt of other tests
}
if(($log =~ /^netrc\d+/) && ($log !~ /^netrc$testnum/)) {
next; # skip netrcNnn of other tests
}
if(($log =~ /^trace\d+/) && ($log !~ /^trace$testnum/)) {
next; # skip traceNnn of other tests
}
if(($log =~ /^valgrind\d+/) && ($log !~ /^valgrind$testnum(\..*|)$/)) {
next; # skip valgrindNnn of other tests
}
if(($log =~ /^test$testnum$/)) {
next; # skip test$testnum since it can be very big
}
logmsg "=== Start of file $log\n";
displaylogcontent("$LOGDIR/$log");
logmsg "=== End of file $log\n";
}
}
#######################################################################
# Setup Azure Pipelines Test Run (if running in Azure DevOps)
#
if(azure_check_environment()) {
$AZURE_RUN_ID = azure_create_test_run($VCURL);
logmsg "Azure Run ID: $AZURE_RUN_ID\n" if ($verbose);
}
#######################################################################
# The main test-loop
#
my $failed;
my $failedign;
my $testnum;
my $ok=0;
my $ign=0;
my $total=0;
my $lasttest=0;
my @at = split(" ", $TESTCASES);
my $count=0;
$start = time();
foreach $testnum (@at) {
$lasttest = $testnum if($testnum > $lasttest);
$count++;
my $error = singletest($run_event_based, $testnum, $count, scalar(@at));
# update test result in CI services
if(azure_check_environment() && $AZURE_RUN_ID && $AZURE_RESULT_ID) {
$AZURE_RESULT_ID = azure_update_test_result($VCURL, $AZURE_RUN_ID, $AZURE_RESULT_ID, $testnum, $error,
$timeprepini{$testnum}, $timevrfyend{$testnum});
}
elsif(appveyor_check_environment()) {
appveyor_update_test_result($VCURL, $testnum, $error, $timeprepini{$testnum}, $timevrfyend{$testnum});
}
if($error < 0) {
# not a test we can run
next;
}
$total++; # number of tests we've run
if($error>0) {
if($error==2) {
# ignored test failures
$failedign .= "$testnum ";
}
else {
$failed.= "$testnum ";
}
if($postmortem) {
# display all files in log/ in a nice way
displaylogs($testnum);
}
if($error==2) {
$ign++; # ignored test result counter
}
elsif(!$anyway) {
# a test failed, abort
logmsg "\n - abort tests\n";
last;
}
}
elsif(!$error) {
$ok++; # successful test counter
}
# loop for next test
}
my $sofar = time() - $start;
#######################################################################
# Finish Azure Pipelines Test Run (if running in Azure DevOps)
#
if(azure_check_environment() && $AZURE_RUN_ID) {
$AZURE_RUN_ID = azure_update_test_run($VCURL, $AZURE_RUN_ID);
}
# Tests done, stop the servers
my $unexpected = stopservers($verbose);
my $all = $total + $skipped;
runtimestats($lasttest);
if($all) {
logmsg "TESTDONE: $all tests were considered during ".
sprintf("%.0f", $sofar) ." seconds.\n";
}
if($skipped && !$short) {
my $s=0;
# Temporary hash to print the restraints sorted by the number
# of their occurences
my %restraints;
logmsg "TESTINFO: $skipped tests were skipped due to these restraints:\n";
for(keys %skipped) {
my $r = $_;
my $skip_count = $skipped{$r};
my $log_line = sprintf("TESTINFO: \"%s\" %d time%s (", $r, $skip_count,
($skip_count == 1) ? "" : "s");
# now gather all test case numbers that had this reason for being
# skipped
my $c=0;
my $max = 9;
for(0 .. scalar @teststat) {
my $t = $_;
if($teststat[$t] && ($teststat[$t] eq $r)) {
if($c < $max) {
$log_line .= ", " if($c);
$log_line .= $t;
}
$c++;
}
}
if($c > $max) {
$log_line .= " and ".($c-$max)." more";
}
$log_line .= ")\n";
$restraints{$log_line} = $skip_count;
}
foreach my $log_line (sort {$restraints{$b} <=> $restraints{$a}} keys %restraints) {
logmsg $log_line;
}
}
if($total) {
if($failedign) {
logmsg "IGNORED: failed tests: $failedign\n";
}
logmsg sprintf("TESTDONE: $ok tests out of $total reported OK: %d%%\n",
$ok/$total*100);
if($ok != $total) {
logmsg "\nTESTFAIL: These test cases failed: $failed\n\n";
}
}
else {
logmsg "\nTESTFAIL: No tests were performed\n\n";
if(scalar(keys %enabled_keywords)) {
logmsg "TESTFAIL: Nothing matched these keywords: ";
for(keys %enabled_keywords) {
logmsg "$_ ";
}
logmsg "\n";
}
}
if(($total && (($ok+$ign) != $total)) || !$total || $unexpected) {
exit 1;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/version-scan.pl | #!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 2010 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
#
# Verify that curl_version_info.3 documents all the CURL_VERSION_ bits
# from the header.
#
use strict;
use warnings;
my $manpage=$ARGV[0];
my $header=$ARGV[1];
my %manversion;
my %headerversion;
my $error;
open(M, "<$manpage");
while(<M>) {
if($_ =~ /^.ip (CURL_VERSION_[A-Z0-9_]+)/i) {
$manversion{$1}++;
}
}
close(M);
open(H, "<$header");
while(<H>) {
if($_ =~ /^\#define (CURL_VERSION_[A-Z0-9_]+)/i) {
$headerversion{$1}++;
}
}
close(H);
for my $h (keys %headerversion) {
if(!$manversion{$h}) {
print STDERR "$manpage: missing $h\n";
$error++;
}
}
for my $h (keys %manversion) {
if(!$headerversion{$h}) {
print STDERR "$manpage: $h is not in the header!\n";
$error++;
}
}
exit $error;
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/smbserver.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 2017 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
"""Server for testing SMB"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import argparse
import logging
import os
import sys
import tempfile
# Import our curl test data helper
from util import ClosingFileHandler, TestData
if sys.version_info.major >= 3:
import configparser
else:
import ConfigParser as configparser
# impacket needs to be installed in the Python environment
try:
import impacket
except ImportError:
sys.stderr.write('Python package impacket needs to be installed!\n')
sys.stderr.write('Use pip or your package manager to install it.\n')
sys.exit(1)
from impacket import smb as imp_smb
from impacket import smbserver as imp_smbserver
from impacket.nt_errors import (STATUS_ACCESS_DENIED, STATUS_NO_SUCH_FILE,
STATUS_SUCCESS)
log = logging.getLogger(__name__)
SERVER_MAGIC = "SERVER_MAGIC"
TESTS_MAGIC = "TESTS_MAGIC"
VERIFIED_REQ = "verifiedserver"
VERIFIED_RSP = "WE ROOLZ: {pid}\n"
def smbserver(options):
"""Start up a TCP SMB server that serves forever
"""
if options.pidfile:
pid = os.getpid()
# see tests/server/util.c function write_pidfile
if os.name == "nt":
pid += 65536
with open(options.pidfile, "w") as f:
f.write(str(pid))
# Here we write a mini config for the server
smb_config = configparser.ConfigParser()
smb_config.add_section("global")
smb_config.set("global", "server_name", "SERVICE")
smb_config.set("global", "server_os", "UNIX")
smb_config.set("global", "server_domain", "WORKGROUP")
smb_config.set("global", "log_file", "")
smb_config.set("global", "credentials_file", "")
# We need a share which allows us to test that the server is running
smb_config.add_section("SERVER")
smb_config.set("SERVER", "comment", "server function")
smb_config.set("SERVER", "read only", "yes")
smb_config.set("SERVER", "share type", "0")
smb_config.set("SERVER", "path", SERVER_MAGIC)
# Have a share for tests. These files will be autogenerated from the
# test input.
smb_config.add_section("TESTS")
smb_config.set("TESTS", "comment", "tests")
smb_config.set("TESTS", "read only", "yes")
smb_config.set("TESTS", "share type", "0")
smb_config.set("TESTS", "path", TESTS_MAGIC)
if not options.srcdir or not os.path.isdir(options.srcdir):
raise ScriptException("--srcdir is mandatory")
test_data_dir = os.path.join(options.srcdir, "data")
smb_server = TestSmbServer((options.host, options.port),
config_parser=smb_config,
test_data_directory=test_data_dir)
log.info("[SMB] setting up SMB server on port %s", options.port)
smb_server.processConfigFile()
smb_server.serve_forever()
return 0
class TestSmbServer(imp_smbserver.SMBSERVER):
"""
Test server for SMB which subclasses the impacket SMBSERVER and provides
test functionality.
"""
def __init__(self,
address,
config_parser=None,
test_data_directory=None):
imp_smbserver.SMBSERVER.__init__(self,
address,
config_parser=config_parser)
# Set up a test data object so we can get test data later.
self.ctd = TestData(test_data_directory)
# Override smbComNtCreateAndX so we can pretend to have files which
# don't exist.
self.hookSmbCommand(imp_smb.SMB.SMB_COM_NT_CREATE_ANDX,
self.create_and_x)
def create_and_x(self, conn_id, smb_server, smb_command, recv_packet):
"""
Our version of smbComNtCreateAndX looks for special test files and
fools the rest of the framework into opening them as if they were
normal files.
"""
conn_data = smb_server.getConnectionData(conn_id)
# Wrap processing in a try block which allows us to throw SmbException
# to control the flow.
try:
ncax_parms = imp_smb.SMBNtCreateAndX_Parameters(
smb_command["Parameters"])
path = self.get_share_path(conn_data,
ncax_parms["RootFid"],
recv_packet["Tid"])
log.info("[SMB] Requested share path: %s", path)
disposition = ncax_parms["Disposition"]
log.debug("[SMB] Requested disposition: %s", disposition)
# Currently we only support reading files.
if disposition != imp_smb.FILE_OPEN:
raise SmbException(STATUS_ACCESS_DENIED,
"Only support reading files")
# Check to see if the path we were given is actually a
# magic path which needs generating on the fly.
if path not in [SERVER_MAGIC, TESTS_MAGIC]:
# Pass the command onto the original handler.
return imp_smbserver.SMBCommands.smbComNtCreateAndX(conn_id,
smb_server,
smb_command,
recv_packet)
flags2 = recv_packet["Flags2"]
ncax_data = imp_smb.SMBNtCreateAndX_Data(flags=flags2,
data=smb_command[
"Data"])
requested_file = imp_smbserver.decodeSMBString(
flags2,
ncax_data["FileName"])
log.debug("[SMB] User requested file '%s'", requested_file)
if path == SERVER_MAGIC:
fid, full_path = self.get_server_path(requested_file)
else:
assert (path == TESTS_MAGIC)
fid, full_path = self.get_test_path(requested_file)
resp_parms = imp_smb.SMBNtCreateAndXResponse_Parameters()
resp_data = ""
# Simple way to generate a fid
if len(conn_data["OpenedFiles"]) == 0:
fakefid = 1
else:
fakefid = conn_data["OpenedFiles"].keys()[-1] + 1
resp_parms["Fid"] = fakefid
resp_parms["CreateAction"] = disposition
if os.path.isdir(path):
resp_parms[
"FileAttributes"] = imp_smb.SMB_FILE_ATTRIBUTE_DIRECTORY
resp_parms["IsDirectory"] = 1
else:
resp_parms["IsDirectory"] = 0
resp_parms["FileAttributes"] = ncax_parms["FileAttributes"]
# Get this file's information
resp_info, error_code = imp_smbserver.queryPathInformation(
os.path.dirname(full_path), os.path.basename(full_path),
level=imp_smb.SMB_QUERY_FILE_ALL_INFO)
if error_code != STATUS_SUCCESS:
raise SmbException(error_code, "Failed to query path info")
resp_parms["CreateTime"] = resp_info["CreationTime"]
resp_parms["LastAccessTime"] = resp_info[
"LastAccessTime"]
resp_parms["LastWriteTime"] = resp_info["LastWriteTime"]
resp_parms["LastChangeTime"] = resp_info[
"LastChangeTime"]
resp_parms["FileAttributes"] = resp_info[
"ExtFileAttributes"]
resp_parms["AllocationSize"] = resp_info[
"AllocationSize"]
resp_parms["EndOfFile"] = resp_info["EndOfFile"]
# Let's store the fid for the connection
# smbServer.log("Create file %s, mode:0x%x" % (pathName, mode))
conn_data["OpenedFiles"][fakefid] = {}
conn_data["OpenedFiles"][fakefid]["FileHandle"] = fid
conn_data["OpenedFiles"][fakefid]["FileName"] = path
conn_data["OpenedFiles"][fakefid]["DeleteOnClose"] = False
except SmbException as s:
log.debug("[SMB] SmbException hit: %s", s)
error_code = s.error_code
resp_parms = ""
resp_data = ""
resp_cmd = imp_smb.SMBCommand(imp_smb.SMB.SMB_COM_NT_CREATE_ANDX)
resp_cmd["Parameters"] = resp_parms
resp_cmd["Data"] = resp_data
smb_server.setConnectionData(conn_id, conn_data)
return [resp_cmd], None, error_code
def get_share_path(self, conn_data, root_fid, tid):
conn_shares = conn_data["ConnectedShares"]
if tid in conn_shares:
if root_fid > 0:
# If we have a rootFid, the path is relative to that fid
path = conn_data["OpenedFiles"][root_fid]["FileName"]
log.debug("RootFid present %s!" % path)
else:
if "path" in conn_shares[tid]:
path = conn_shares[tid]["path"]
else:
raise SmbException(STATUS_ACCESS_DENIED,
"Connection share had no path")
else:
raise SmbException(imp_smbserver.STATUS_SMB_BAD_TID,
"TID was invalid")
return path
def get_server_path(self, requested_filename):
log.debug("[SMB] Get server path '%s'", requested_filename)
if requested_filename not in [VERIFIED_REQ]:
raise SmbException(STATUS_NO_SUCH_FILE, "Couldn't find the file")
fid, filename = tempfile.mkstemp()
log.debug("[SMB] Created %s (%d) for storing '%s'",
filename, fid, requested_filename)
contents = ""
if requested_filename == VERIFIED_REQ:
log.debug("[SMB] Verifying server is alive")
pid = os.getpid()
# see tests/server/util.c function write_pidfile
if os.name == "nt":
pid += 65536
contents = VERIFIED_RSP.format(pid=pid).encode('utf-8')
self.write_to_fid(fid, contents)
return fid, filename
def write_to_fid(self, fid, contents):
# Write the contents to file descriptor
os.write(fid, contents)
os.fsync(fid)
# Rewind the file to the beginning so a read gets us the contents
os.lseek(fid, 0, os.SEEK_SET)
def get_test_path(self, requested_filename):
log.info("[SMB] Get reply data from 'test%s'", requested_filename)
fid, filename = tempfile.mkstemp()
log.debug("[SMB] Created %s (%d) for storing test '%s'",
filename, fid, requested_filename)
try:
contents = self.ctd.get_test_data(requested_filename).encode('utf-8')
self.write_to_fid(fid, contents)
return fid, filename
except Exception:
log.exception("Failed to make test file")
raise SmbException(STATUS_NO_SUCH_FILE, "Failed to make test file")
class SmbException(Exception):
def __init__(self, error_code, error_message):
super(SmbException, self).__init__(error_message)
self.error_code = error_code
class ScriptRC(object):
"""Enum for script return codes"""
SUCCESS = 0
FAILURE = 1
EXCEPTION = 2
class ScriptException(Exception):
pass
def get_options():
parser = argparse.ArgumentParser()
parser.add_argument("--port", action="store", default=9017,
type=int, help="port to listen on")
parser.add_argument("--host", action="store", default="127.0.0.1",
help="host to listen on")
parser.add_argument("--verbose", action="store", type=int, default=0,
help="verbose output")
parser.add_argument("--pidfile", action="store",
help="file name for the PID")
parser.add_argument("--logfile", action="store",
help="file name for the log")
parser.add_argument("--srcdir", action="store", help="test directory")
parser.add_argument("--id", action="store", help="server ID")
parser.add_argument("--ipv4", action="store_true", default=0,
help="IPv4 flag")
return parser.parse_args()
def setup_logging(options):
"""
Set up logging from the command line options
"""
root_logger = logging.getLogger()
add_stdout = False
formatter = logging.Formatter("%(asctime)s %(levelname)-5.5s %(message)s")
# Write out to a logfile
if options.logfile:
handler = ClosingFileHandler(options.logfile)
handler.setFormatter(formatter)
handler.setLevel(logging.DEBUG)
root_logger.addHandler(handler)
else:
# The logfile wasn't specified. Add a stdout logger.
add_stdout = True
if options.verbose:
# Add a stdout logger as well in verbose mode
root_logger.setLevel(logging.DEBUG)
add_stdout = True
else:
root_logger.setLevel(logging.INFO)
if add_stdout:
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setFormatter(formatter)
stdout_handler.setLevel(logging.DEBUG)
root_logger.addHandler(stdout_handler)
if __name__ == '__main__':
# Get the options from the user.
options = get_options()
# Setup logging using the user options
setup_logging(options)
# Run main script.
try:
rc = smbserver(options)
except Exception as e:
log.exception(e)
rc = ScriptRC.EXCEPTION
if options.pidfile and os.path.isfile(options.pidfile):
os.unlink(options.pidfile)
log.info("[SMB] Returning %d", rc)
sys.exit(rc)
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/badsymbols.pl | #!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 2010-2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
#
# This script grew out of help from Przemyslaw Iskra and Balint Szilakszi
# a late evening in the #curl IRC channel.
#
use strict;
use warnings;
use vars qw($Cpreprocessor);
#
# configurehelp perl module is generated by configure script
#
my $rc = eval {
require configurehelp;
configurehelp->import(qw(
$Cpreprocessor
));
1;
};
# Set default values if configure has not generated a configurehelp.pm file.
# This is the case with cmake.
if (!$rc) {
$Cpreprocessor = 'cpp';
}
my $verbose=0;
# verbose mode when -v is the first argument
if($ARGV[0] eq "-v") {
$verbose=1;
shift;
}
# we may get the dir root pointed out
my $root=$ARGV[0] || ".";
# need an include directory when building out-of-tree
my $i = ($ARGV[1]) ? "-I$ARGV[1] " : '';
my $incdir = "$root/include/curl";
my $summary=0;
my $misses=0;
my @syms;
my %doc;
my %rem;
sub scanenums {
my ($file)=@_;
my $skipit = 0;
open H_IN, "-|", "$Cpreprocessor $i$file" || die "Cannot preprocess $file";
while ( <H_IN> ) {
my ($line, $linenum) = ($_, $.);
if( /^#(line|) (\d+) \"(.*)\"/) {
# if the included file isn't in our incdir, then we skip this section
# until next #line
#
if($3 !~ /^$incdir/) {
$skipit = 1;
next;
}
# parse this!
$skipit = 0;
next;
}
if($skipit) {
next;
}
if (/^#/) {
next;
}
if ( /enum\s+(\S+\s+)?{/ .. /}/ ) {
s/^\s+//;
chomp;
s/[,\s].*//;
if(($_ !~ /\}(;|)/) &&
($_ ne "typedef") &&
($_ ne "enum") &&
($_ !~ /^[ \t]*$/)) {
if($verbose) {
print "Source: $Cpreprocessor $i$file\n";
print "Symbol: $_\n";
print "Line #$linenum: $line\n\n";
}
push @syms, $_;
}
}
}
close H_IN || die "Error preprocessing $file";
}
sub scanheader {
my ($f)=@_;
scanenums($f);
open H, "<$f";
while(<H>) {
my ($line, $linenum) = ($_, $.);
if (/^#define +([^ \n]*)/) {
if($verbose) {
print "Source: $f\n";
print "Symbol: $1\n";
print "Line #$linenum: $line\n\n";
}
push @syms, $1;
}
}
close H;
}
opendir(my $dh, $incdir) || die "Can't opendir $incdir: $!";
my @hfiles = grep { /\.h$/ } readdir($dh);
closedir $dh;
for(@hfiles) {
scanheader("$incdir/$_");
}
my $errors = 0;
for my $s (@syms) {
if($s !~ /^(lib|)curl/i) {
print "Bad symbols in public header files:\n" if(!$errors);
$errors++;
print " $s\n";
}
}
if($errors) {
exit 1;
}
printf "%d fine symbols found\n", scalar(@syms);
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/nroff-scan.pl | #!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 2016 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
#
# scan nroff pages to find basic syntactic problems such as unbalanced \f
# codes or references to non-existing curl man pages.
my $docsroot = $ARGV[0];
if(!$docsroot || ($docsroot eq "-g")) {
print "Usage: nroff-scan.pl <docs root dir> [nroff files]\n";
exit;
}
shift @ARGV;
my @f = @ARGV;
my %manp;
sub manpresent {
my ($man) = @_;
if($manp{$man}) {
return 1;
}
elsif(-r "$docsroot/$man" ||
-r "$docsroot/libcurl/$man" ||
-r "$docsroot/libcurl/opts/$man") {
$manp{$man}=1;
return 1;
}
return 0;
}
sub file {
my ($f) = @_;
open(F, "<$f") ||
die "no file";
my $line = 1;
while(<F>) {
chomp;
my $l = $_;
while($l =~ s/\\f(.)([^ ]*)\\f(.)//) {
my ($pre, $str, $post)=($1, $2, $3);
if($post ne "P") {
print "error: $f:$line: missing \\fP after $str\n";
$errors++;
}
if($str =~ /((libcurl|curl)([^ ]*))\(3\)/i) {
my $man = "$1.3";
if(!manpresent($man)) {
print "error: $f:$line: referring to non-existing man page $man\n";
$errors++;
}
if($pre ne "I") {
print "error: $f:$line: use \\fI before $str\n";
$errors++;
}
}
}
if($l =~ /(curl([^ ]*)\(3\))/i) {
print "error: $f:$line: non-referencing $1\n";
$errors++;
}
if($l =~ /^\.BR (.*)/) {
my $i= $1;
while($i =~ s/((lib|)curl([^ ]*)) *\"\(3\)(,|) *\" *//i ) {
my $man = "$1.3";
if(!manpresent($man)) {
print "error: $f:$line: referring to non-existing man page $man\n";
$errors++;
}
}
}
$line++;
}
close(F);
}
foreach my $f (@f) {
file($f);
}
print "OK\n" if(!$errors);
exit $errors?1:0;
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/disable-scan.pl | #!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 2010 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
#
use strict;
use warnings;
# the DISABLE options that can be set by configure
my %disable;
# the DISABLE options that are used in C files
my %file;
# the DISABLE options that are documented
my %docs;
# we may get the dir root pointed out
my $root=$ARGV[0] || ".";
my $DOCS="CURL-DISABLE.md";
sub scanconf {
my ($f)=@_;
open S, "<$f";
while(<S>) {
if(/(CURL_DISABLE_[A-Z_]+)/g) {
my ($sym)=($1);
$disable{$sym} = 1;
}
}
close S;
}
sub scan_configure {
opendir(my $m, "$root/m4") || die "Can't opendir $root/m4: $!";
my @m4 = grep { /\.m4$/ } readdir($m);
closedir $m;
scanconf("$root/configure.ac");
# scan all m4 files too
for my $e (@m4) {
scanconf("$root/m4/$e");
}
}
sub scan_file {
my ($source)=@_;
open F, "<$source";
while(<F>) {
if(/(CURL_DISABLE_[A-Z_]+)/g) {
my ($sym)=($1);
$file{$sym} = $source;
}
}
close F;
}
sub scan_dir {
my ($dir)=@_;
opendir(my $dh, $dir) || die "Can't opendir $dir: $!";
my @cfiles = grep { /\.[ch]\z/ && -f "$dir/$_" } readdir($dh);
closedir $dh;
for my $f (sort @cfiles) {
scan_file("$dir/$f");
}
}
sub scan_sources {
scan_dir("$root/src");
scan_dir("$root/lib");
scan_dir("$root/lib/vtls");
scan_dir("$root/lib/vauth");
}
sub scan_docs {
open F, "<$root/docs/$DOCS";
my $line = 0;
while(<F>) {
$line++;
if(/^## (CURL_DISABLE_[A-Z_]+)/g) {
my ($sym)=($1);
$docs{$sym} = $line;
}
}
close F;
}
scan_configure();
scan_sources();
scan_docs();
my $error = 0;
# Check the configure symbols for use in code
for my $s (sort keys %disable) {
if(!$file{$s}) {
printf "Present in configure.ac, not used by code: %s\n", $s;
$error++;
}
if(!$docs{$s}) {
printf "Present in configure.ac, not documented in $DOCS: %s\n", $s;
$error++;
}
}
# Check the code symbols for use in configure
for my $s (sort keys %file) {
if(!$disable{$s}) {
printf "Not set by configure: %s (%s)\n", $s, $file{$s};
$error++;
}
if(!$docs{$s}) {
printf "Used in code, not documented in $DOCS: %s\n", $s;
$error++;
}
}
# Check the documented symbols
for my $s (sort keys %docs) {
if(!$disable{$s}) {
printf "Documented but not in configure: %s\n", $s;
$error++;
}
if(!$file{$s}) {
printf "Documented, but not used by code: %s\n", $s;
$error++;
}
}
exit $error;
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/options-scan.pl | #!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 2010 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
#
#
# - Get all options mentioned in the $cmddir.
# - Make sure they're all mentioned in the $opts document
# - Make usre that the version in $opts matches the version in the file in
# $cmddir
#
my $opts = $ARGV[0];
my $cmddir = $ARGV[1];
sub cmdfiles {
my ($dir)=@_;
opendir(my $dh, $dir) || die "Can't opendir $dir: $!";
my @opts = grep { /\.d$/ && -f "$dir/$_" } readdir($dh);
closedir $dh;
for(@opts) {
$_ =~ s/\.d$//;
$file{$_}=1;
}
return @opts;
}
sub mentions {
my ($f) = @_;
my @options;
open(F, "<$f");
while(<F>) {
chomp;
if(/(.*) +([0-9.]+)/) {
my ($flag, $version)=($1, $2);
# store the name without the leading dashes
$flag =~ s/^--//;
# cut out short option (if present)
$flag =~ s/ \(-.\)//;
# store the name without trailing space
$flag =~ s/ +$//;
push @options, $flag;
# options-in-versions says...
$oiv{$flag} = $version;
}
}
return @options;
}
sub versioncheck {
my ($f, $v)=@_;
open(F, "<$cmddir/$f.d");
while(<F>) {
chomp;
if(/^Added: ([0-9.]+)/) {
if($1 ne $v) {
print STDERR "$f lists $v in doc but $1 in file\n";
$error++;
}
last;
}
}
close(F);
}
# get all the files
my @cmdopts = cmdfiles($cmddir);
# get all the options mentioned in $o
my @veropts = mentions($opts);
# check if all files are in the doc
for my $c (sort @cmdopts) {
if($oiv{$c}) {
# present, but at same version?
versioncheck($c, $oiv{$c});
}
else {
print STDERR "--$c is in the option directory but not in $opts!\n";
$error++;
}
}
# check if the all options in the doc have files
for my $v (sort @veropts) {
if($file{$v}) {
# present
}
else {
print STDERR "$v is in the doc but NOT as a file!\n";
$error++;
}
}
print STDERR "ok\n" if(!$error);
exit $error;
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/README.md | # The curl Test Suite
# Running
## Requires to run
- perl (and a unix-style shell)
- python (and a unix-style shell, for SMB and TELNET tests)
- python-impacket (for SMB tests)
- diff (when a test fails, a diff is shown)
- stunnel (for HTTPS and FTPS tests)
- OpenSSH or SunSSH (for SCP, SFTP and SOCKS4/5 tests)
- nghttpx (for HTTP/2 tests)
- nroff (for --manual tests)
- An available `en_US.UTF-8` locale
### Installation of python-impacket
The Python-based test servers support both recent Python 2 and 3.
You can figure out your default Python interpreter with python -V
Please install python-impacket in the correct Python environment.
You can use pip or your OS' package manager to install 'impacket'.
On Debian/Ubuntu the package names are:
- Python 2: 'python-impacket'
- Python 3: 'python3-impacket'
On FreeBSD the package names are:
- Python 2: 'py27-impacket'
- Python 3: 'py37-impacket'
On any system where pip is available:
- Python 2: 'pip2 install impacket'
- Python 3: 'pip3 install impacket'
You may also need to manually install the Python package 'six'
as that may be a missing requirement for impacket on Python 3.
### Port numbers used by test servers
All test servers run on "random" port numbers. All tests should be written
to use suitable variables instead of fixed port numbers so that test cases
continue to work independent on what port numbers the test servers actually
use.
See [FILEFORMAT](FILEFORMAT.md) for the port number variables.
### Test servers
The test suite runs stand-alone servers on random ports to which it makes
requests. For SSL tests, it runs stunnel to handle encryption to the regular
servers. For SSH, it runs a standard OpenSSH server. For SOCKS4/5 tests SSH
is used to perform the SOCKS functionality and requires a SSH client and
server.
The listen port numbers for the test servers are picked randomly to allow
users to run multiple test cases concurrently and to not collide with other
existing services that might listen to ports on the machine.
The HTTP server supports listening on a Unix domain socket, the default
location is 'http.sock'.
### Run
`./configure && make && make test`. This builds the test suite support code
and invokes the 'runtests.pl' perl script to run all the tests. Edit the top
variables of that script in case you have some specific needs, or run the
script manually (after the support code has been built).
The script breaks on the first test that doesn't do OK. Use `-a` to prevent
the script from aborting on the first error. Run the script with `-v` for
more verbose output. Use `-d` to run the test servers with debug output
enabled as well. Specifying `-k` keeps all the log files generated by the
test intact.
Use `-s` for shorter output, or pass test numbers to run specific tests only
(like `./runtests.pl 3 4` to test 3 and 4 only). It also supports test case
ranges with 'to', as in `./runtests.pl 3 to 9` which runs the seven tests
from 3 to 9. Any test numbers starting with ! are disabled, as are any test
numbers found in the files `data/DISABLED` or `data/DISABLED.local` (one per
line). The latter is meant for local temporary disables and will be ignored
by git.
Test cases mentioned in `DISABLED` can still be run if `-f` is provided.
When `-s` is not present, each successful test will display on one line the
test number and description and on the next line a set of flags, the test
result, current test sequence, total number of tests to be run and an
estimated amount of time to complete the test run. The flags consist of
these letters describing what is checked in this test:
s stdout
d data
u upload
p protocol
o output
e exit code
m memory
v valgrind
### Shell startup scripts
Tests which use the ssh test server, SCP/SFTP/SOCKS tests, might be badly
influenced by the output of system wide or user specific shell startup
scripts, .bashrc, .profile, /etc/csh.cshrc, .login, /etc/bashrc, etc. which
output text messages or escape sequences on user login. When these shell
startup messages or escape sequences are output they might corrupt the
expected stream of data which flows to the sftp-server or from the ssh
client which can result in bad test behavior or even prevent the test
server from running.
If the test suite ssh or sftp server fails to start up and logs the message
'Received message too long' then you are certainly suffering the unwanted
output of a shell startup script. Locate, cleanup or adjust the shell
script.
### Memory test
The test script will check that all allocated memory is freed properly IF
curl has been built with the `CURLDEBUG` define set. The script will
automatically detect if that is the case, and it will use the
'memanalyze.pl' script to analyze the memory debugging output.
Also, if you run tests on a machine where valgrind is found, the script will
use valgrind to run the test with (unless you use `-n`) to further verify
correctness.
runtests.pl's `-t` option will enable torture testing mode, which runs each
test many times and makes each different memory allocation fail on each
successive run. This tests the out of memory error handling code to ensure
that memory leaks do not occur even in those situations. It can help to
compile curl with `CPPFLAGS=-DMEMDEBUG_LOG_SYNC` when using this option, to
ensure that the memory log file is properly written even if curl crashes.
### Debug
If a test case fails, you can conveniently get the script to invoke the
debugger (gdb) for you with the server running and the exact same command
line parameters that failed. Just invoke `runtests.pl <test number> -g` and
then just type 'run' in the debugger to perform the command through the
debugger.
### Logs
All logs are generated in the log/ subdirectory (it is emptied first in the
runtests.pl script). They remain in there after a test run.
### Test input files
All test cases are put in the `data/` subdirectory. Each test is stored in
the file named according to the test number.
See [FILEFORMAT.md](FILEFORMAT.md) for a description of the test case file
format.
### Code coverage
gcc provides a tool that can determine the code coverage figures for the
test suite. To use it, configure curl with `CFLAGS='-fprofile-arcs
-ftest-coverage -g -O0'`. Make sure you run the normal and torture tests to
get more full coverage, i.e. do:
make test
make test-torture
The graphical tool ggcov can be used to browse the source and create
coverage reports on *NIX hosts:
ggcov -r lib src
The text mode tool gcov may also be used, but it doesn't handle object files
in more than one directory very well.
### Remote testing
The runtests.pl script provides some hooks to allow curl to be tested on a
machine where perl can not be run. The test framework in this case runs on
a workstation where perl is available, while curl itself is run on a remote
system using ssh or some other remote execution method. See the comments at
the beginning of runtests.pl for details.
## Test case numbering
Test cases used to be numbered by category ranges, but the ranges filled
up. Subsets of tests can now be selected by passing keywords to the
runtests.pl script via the make `TFLAGS` variable.
New tests are added by finding a free number in `tests/data/Makefile.inc`.
## Write tests
Here's a quick description on writing test cases. We basically have three
kinds of tests: the ones that test the curl tool, the ones that build small
applications and test libcurl directly and the unit tests that test
individual (possibly internal) functions.
### test data
Each test has a master file that controls all the test data. What to read,
what the protocol exchange should look like, what exit code to expect and
what command line arguments to use etc.
These files are `tests/data/test[num]` where `[num]` is just a unique
identifier described above, and the XML-like file format of them is
described in the separate [FILEFORMAT.md](FILEFORMAT.md) document.
### curl tests
A test case that runs the curl tool and verifies that it gets the correct
data, it sends the correct data, it uses the correct protocol primitives
etc.
### libcurl tests
The libcurl tests are identical to the curl ones, except that they use a
specific and dedicated custom-built program to run instead of "curl". This
tool is built from source code placed in `tests/libtest` and if you want to
make a new libcurl test that is where you add your code.
### unit tests
Unit tests are placed in `tests/unit`. There's a tests/unit/README
describing the specific set of checks and macros that may be used when
writing tests that verify behaviors of specific individual functions.
The unit tests depend on curl being built with debug enabled.
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/mem-include-scan.pl | #!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 2010 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
#
# This script scans C source files. If they seem to use memory functions,
# it also makes sure that it #includes the correct two header files!
#
# You can also mark a C source as fine by using 'mem-include-scan' anywhere in
# it.
#
use strict;
use warnings;
my $dir = $ARGV[0] || die "specify directory!";
sub scanfile {
my ($file) = @_;
my $memfunc;
my $memdebug;
my $curlmem;
print STDERR "checking $file...\n";
open(F, "<$file");
while(<F>) {
if($_ =~ /\W(free|alloc|strdup)\(/) {
$memfunc++;
}
elsif($_ =~ /^ *# *include \"memdebug.h\"/) {
$memdebug++;
}
elsif($_ =~ /^ *# *include \"curl_memory.h\"/) {
$curlmem++;
}
elsif($_ =~ /mem-include-scan/) {
# free pass
close(F);
return 0;
}
if($memfunc && $memdebug && $curlmem) {
last;
}
}
close(F);
if($memfunc) {
if($memdebug && $curlmem) {
return 0;
}
else {
if(!$memdebug) {
print STDERR "$file doesn't include \"memdebug.h\"!\n";
}
if(!$curlmem) {
print STDERR "$file doesn't include \"curl_memory.h\"!\n";
}
return 1;
}
}
return 0;
}
opendir(my $dh, $dir) || die "can't opendir $dir: $!";
my @cfiles = grep { /\.c\z/ && -f "$dir/$_" } readdir($dh);
closedir $dh;
my $errs;
for(@cfiles) {
$errs += scanfile("$dir/$_");
}
if($errs) {
print STDERR "----\n$errs errors detected!\n";
exit 2;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/tftpserver.pl | #!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
#***************************************************************************
BEGIN {
push(@INC, $ENV{'srcdir'}) if(defined $ENV{'srcdir'});
push(@INC, ".");
}
use strict;
use warnings;
use serverhelp qw(
server_pidfilename
server_logfilename
);
use sshhelp qw(
exe_ext
);
my $verbose = 0; # set to 1 for debugging
my $port = 8997; # just a default
my $ipvnum = 4; # default IP version of tftp server
my $idnum = 1; # default tftp server instance number
my $proto = 'tftp'; # protocol the tftp server speaks
my $pidfile;
my $portfile;
my $logfile;
my $srcdir;
my $fork;
my $flags = "";
my $path = '.';
my $logdir = $path .'/log';
while(@ARGV) {
if($ARGV[0] eq '--pidfile') {
if($ARGV[1]) {
$pidfile = $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--portfile') {
if($ARGV[1]) {
$portfile = $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--logfile') {
if($ARGV[1]) {
$logfile = $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--srcdir') {
if($ARGV[1]) {
$srcdir = $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--ipv4') {
$ipvnum = 4;
}
elsif($ARGV[0] eq '--ipv6') {
$ipvnum = 6;
}
elsif($ARGV[0] eq '--port') {
if($ARGV[1] =~ /^(\d+)$/) {
$port = $1;
shift @ARGV;
}
}
elsif($ARGV[0] eq '--id') {
if($ARGV[1] =~ /^(\d+)$/) {
$idnum = $1 if($1 > 0);
shift @ARGV;
}
}
elsif($ARGV[0] eq '--verbose') {
$verbose = 1;
}
else {
print STDERR "\nWarning: tftpserver.pl unknown parameter: $ARGV[0]\n";
}
shift @ARGV;
}
if(!$srcdir) {
$srcdir = $ENV{'srcdir'} || '.';
}
if(!$pidfile) {
$pidfile = "$path/". server_pidfilename($proto, $ipvnum, $idnum);
}
if(!$logfile) {
$logfile = server_logfilename($logdir, $proto, $ipvnum, $idnum);
}
$flags .= "--pidfile \"$pidfile\" ".
"--portfile \"$portfile\" ".
"--logfile \"$logfile\" ";
$flags .= "--ipv$ipvnum --port $port --srcdir \"$srcdir\"";
$| = 1;
exec("exec server/tftpd".exe_ext('SRV')." $flags");
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/testcurl.pl | #!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
###########################
# What is This Script?
###########################
# testcurl.pl is the master script to use for automatic testing of curl
# directly off its source repository.
# This is written for the purpose of being run from a crontab job or similar
# at a regular interval. The output is suitable to be mailed to
# [email protected] to be dealt with automatically (make sure the
# subject includes the word "autobuild" as the mail gets silently discarded
# otherwise). The most current build status (with a reasonable backlog) will
# be published on the curl site, at https://curl.se/auto/
# USAGE:
# testcurl.pl [options] [curl-daily-name] > output
# Options:
#
# --configure=[options] Configure options
# --crosscompile This is a crosscompile
# --desc=[desc] Description of your test system
# --email=[email] Set email address to report as
# --extvercmd=[command] Command to use for displaying version with cross compiles.
# --mktarball=[command] Command to run after completed test
# --name=[name] Set name to report as
# --notes=[notes] More human-readable information about this configuration
# --nocvsup Don't pull from git even though it is a git tree
# --nogitpull Don't pull from git even though it is a git tree
# --nobuildconf Don't run buildconf
# --noconfigure Don't run configure
# --runtestopts=[options] Options to pass to runtests.pl
# --setup=[file name] File name to read setup from (deprecated)
# --target=[your os] Specify your target environment.
#
# if [curl-daily-name] is omitted, a 'curl' git directory is assumed.
#
use strict;
use Cwd;
use File::Spec;
# Turn on warnings (equivalent to -w, which can't be used with /usr/bin/env)
#BEGIN { $^W = 1; }
use vars qw($version $fixed $infixed $CURLDIR $git $pwd $build $buildlog
$buildlogname $configurebuild $targetos $confheader $binext
$libext);
use vars qw($name $email $desc $confopts $runtestopts $setupfile $mktarball
$extvercmd $nogitpull $nobuildconf $crosscompile
$timestamp $notes);
# version of this script
$version='2014-11-25';
$fixed=0;
# Determine if we're running from git or a canned copy of curl,
# or if we got a specific target option or setup file option.
$CURLDIR="curl";
if (-f ".git/config") {
$CURLDIR = "./";
}
$git=1;
$setupfile = 'setup';
$configurebuild = 1;
while ($ARGV[0]) {
if ($ARGV[0] =~ /--target=/) {
$targetos = (split(/=/, shift @ARGV, 2))[1];
}
elsif ($ARGV[0] =~ /--setup=/) {
$setupfile = (split(/=/, shift @ARGV, 2))[1];
}
elsif ($ARGV[0] =~ /--extvercmd=/) {
$extvercmd = (split(/=/, shift @ARGV, 2))[1];
}
elsif ($ARGV[0] =~ /--mktarball=/) {
$mktarball = (split(/=/, shift @ARGV, 2))[1];
}
elsif ($ARGV[0] =~ /--name=/) {
$name = (split(/=/, shift @ARGV, 2))[1];
}
elsif ($ARGV[0] =~ /--email=/) {
$email = (split(/=/, shift @ARGV, 2))[1];
}
elsif ($ARGV[0] =~ /--desc=/) {
$desc = (split(/=/, shift @ARGV, 2))[1];
}
elsif ($ARGV[0] =~ /--notes=/) {
$notes = (split(/=/, shift @ARGV, 2))[1];
}
elsif ($ARGV[0] =~ /--configure=(.*)/) {
$confopts = $1;
shift @ARGV;
}
elsif (($ARGV[0] eq "--nocvsup") || ($ARGV[0] eq "--nogitpull")) {
$nogitpull=1;
shift @ARGV;
}
elsif ($ARGV[0] =~ /--nobuildconf/) {
$nobuildconf=1;
shift @ARGV;
}
elsif ($ARGV[0] =~ /--noconfigure/) {
$configurebuild=0;
shift @ARGV;
}
elsif ($ARGV[0] =~ /--crosscompile/) {
$crosscompile=1;
shift @ARGV;
}
elsif ($ARGV[0] =~ /--runtestopts=/) {
$runtestopts = (split(/=/, shift @ARGV, 2))[1];
}
else {
$CURLDIR=shift @ARGV;
$git=0; # a given dir, assume not using git
}
}
# Do the platform-specific stuff here
$confheader = 'curl_config.h';
$binext = '';
$libext = '.la'; # .la since both libcurl and libcares are made with libtool
if ($^O eq 'MSWin32' || $targetos) {
if (!$targetos) {
# If no target defined on Win32 lets assume vc
$targetos = 'vc';
}
if ($targetos =~ /vc/ || $targetos =~ /borland/ || $targetos =~ /watcom/) {
$binext = '.exe';
$libext = '.lib';
}
elsif ($targetos =~ /mingw/) {
$binext = '.exe';
if ($^O eq 'MSWin32') {
$libext = '.a';
}
}
elsif ($targetos =~ /netware/) {
$configurebuild = 0;
$binext = '.nlm';
if ($^O eq 'MSWin32') {
$libext = '.lib';
}
else {
$libext = '.a';
}
}
}
if (($^O eq 'MSWin32' || $^O eq 'cygwin' || $^O eq 'msys') &&
($targetos =~ /vc/ || $targetos =~ /mingw32/ ||
$targetos =~ /borland/ || $targetos =~ /watcom/)) {
# Set these things only when building ON Windows and for Win32 platform.
# FOR Windows since we might be cross-compiling on another system. Non-
# Windows builds still default to configure-style builds with curl_config.h.
$configurebuild = 0;
$confheader = 'config-win32.h';
}
$ENV{LC_ALL}="C" if (($ENV{LC_ALL}) && ($ENV{LC_ALL} !~ /^C$/));
$ENV{LC_CTYPE}="C" if (($ENV{LC_CTYPE}) && ($ENV{LC_CTYPE} !~ /^C$/));
$ENV{LANG}="C";
sub rmtree($) {
my $target = $_[0];
if ($^O eq 'MSWin32') {
foreach (glob($target)) {
s:/:\\:g;
system("rd /s /q $_");
}
} else {
system("rm -rf $target");
}
}
sub grepfile($$) {
my ($target, $fn) = @_;
open(F, $fn) or die;
while (<F>) {
if (/$target/) {
close(F);
return 1;
}
}
close(F);
return 0;
}
sub logit($) {
my $text=$_[0];
if ($text) {
print "testcurl: $text\n";
}
}
sub logit_spaced($) {
my $text=$_[0];
if ($text) {
print "\ntestcurl: $text\n\n";
}
}
sub mydie($){
my $text=$_[0];
logit "$text";
chdir $pwd; # cd back to the original root dir
if ($pwd && $build) {
# we have a build directory name, remove the dir
logit "removing the $build dir";
rmtree "$pwd/$build";
}
if (-r $buildlog) {
# we have a build log output file left, remove it
logit "removing the $buildlogname file";
unlink "$buildlog";
}
logit "ENDING HERE"; # last line logged!
exit 1;
}
sub get_host_triplet {
my $triplet;
my $configfile = "$pwd/$build/lib/curl_config.h";
if(-f $configfile && -s $configfile && open(LIBCONFIGH, "<$configfile")) {
while(<LIBCONFIGH>) {
if($_ =~ /^\#define\s+OS\s+"*([^"][^"]*)"*\s*/) {
$triplet = $1;
last;
}
}
close(LIBCONFIGH);
}
return $triplet;
}
if($name && $email && $desc) {
# having these fields set are enough to continue, skip reading the setup
# file
$infixed=4;
$fixed=4;
}
elsif (open(F, "$setupfile")) {
while (<F>) {
if (/(\w+)=(.*)/) {
eval "\$$1=$2;";
}
}
close(F);
$infixed=$fixed;
}
else {
$infixed=0; # so that "additional args to configure" works properly first time...
}
if (!$name) {
print "please enter your name\n";
$name = <>;
chomp $name;
$fixed=1;
}
if (!$email) {
print "please enter your contact email address\n";
$email = <>;
chomp $email;
$fixed=2;
}
if (!$desc) {
print "please enter a one line system description\n";
$desc = <>;
chomp $desc;
$fixed=3;
}
if (!$confopts) {
if ($infixed < 4) {
print "please enter your additional arguments to configure\n";
print "examples: --with-openssl --enable-debug --enable-ipv6\n";
$confopts = <>;
chomp $confopts;
}
}
if ($fixed < 4) {
$fixed=4;
open(F, ">$setupfile") or die;
print F "name='$name'\n";
print F "email='$email'\n";
print F "desc='$desc'\n";
print F "confopts='$confopts'\n";
print F "notes='$notes'\n";
print F "fixed='$fixed'\n";
close(F);
}
# Enable picky compiler warnings unless explicitly disabled
if (($confopts !~ /--enable-debug/) &&
($confopts !~ /--enable-warnings/) &&
($confopts !~ /--disable-warnings/)) {
$confopts .= " --enable-warnings";
}
my $str1066os = 'o' x 1066;
# Set timestamp to the UTC this script is running. Its value might
# be changed later in the script to the value present in curlver.h
$timestamp = scalar(gmtime)." UTC";
logit "STARTING HERE"; # first line logged, for scripts to trigger on
logit 'TRANSFER CONTROL ==== 1120 CHAR LINE' . $str1066os . 'LINE_END';
logit "NAME = $name";
logit "EMAIL = $email";
logit "DESC = $desc";
logit "NOTES = $notes";
logit "CONFOPTS = $confopts";
logit "RUNTESTOPTS = ".$runtestopts;
logit "CPPFLAGS = ".$ENV{CPPFLAGS};
logit "CFLAGS = ".$ENV{CFLAGS};
logit "LDFLAGS = ".$ENV{LDFLAGS};
logit "LIBS = ".$ENV{LIBS};
logit "CC = ".$ENV{CC};
logit "TMPDIR = ".$ENV{TMPDIR};
logit "MAKEFLAGS = ".$ENV{MAKEFLAGS};
logit "ACLOCAL_FLAGS = ".$ENV{ACLOCAL_FLAGS};
logit "PKG_CONFIG_PATH = ".$ENV{PKG_CONFIG_PATH};
logit "DYLD_LIBRARY_PATH = ".$ENV{DYLD_LIBRARY_PATH};
logit "LD_LIBRARY_PATH = ".$ENV{LD_LIBRARY_PATH};
logit "LIBRARY_PATH = ".$ENV{LIBRARY_PATH};
logit "SHLIB_PATH = ".$ENV{SHLIB_PATH};
logit "LIBPATH = ".$ENV{LIBPATH};
logit "target = ".$targetos;
logit "version = $version"; # script version
logit "date = $timestamp"; # When the test build starts
$str1066os = undef;
# Make $pwd to become the path without newline. We'll use that in order to cut
# off that path from all possible logs and error messages etc.
$pwd = getcwd();
my $have_embedded_ares = 0;
if (-d $CURLDIR) {
if ($git && -d "$CURLDIR/.git") {
logit "$CURLDIR is verified to be a fine git source dir";
# remove the generated sources to force them to be re-generated each
# time we run this test
unlink "$CURLDIR/src/tool_hugehelp.c";
# find out if curl source dir has an in-tree c-ares repo
$have_embedded_ares = 1 if (-f "$CURLDIR/ares/GIT-INFO");
} elsif (!$git && -f "$CURLDIR/tests/testcurl.pl") {
logit "$CURLDIR is verified to be a fine daily source dir";
# find out if curl source dir has an in-tree c-ares extracted tarball
$have_embedded_ares = 1 if (-f "$CURLDIR/ares/ares_build.h");
} else {
mydie "$CURLDIR is not a daily source dir or checked out from git!"
}
}
# make the path absolute so we can use it everywhere
$CURLDIR = File::Spec->rel2abs("$CURLDIR");
$build="build-$$";
$buildlogname="buildlog-$$";
$buildlog="$pwd/$buildlogname";
# remove any previous left-overs
rmtree "build-*";
rmtree "buildlog-*";
# this is to remove old build logs that ended up in the wrong dir
foreach (glob("$CURLDIR/buildlog-*")) { unlink $_; }
# create a dir to build in
mkdir $build, 0777;
if (-d $build) {
logit "build dir $build was created fine";
} else {
mydie "failed to create dir $build";
}
# get in the curl source tree root
chdir $CURLDIR;
# Do the git thing, or not...
if ($git) {
my $gitstat = 0;
my @commits;
# update quietly to the latest git
if($nogitpull) {
logit "skipping git pull (--nogitpull)";
} else {
logit "run git pull in curl";
system("git pull 2>&1");
$gitstat += $?;
logit "failed to update from curl git ($?), continue anyway" if ($?);
# Set timestamp to the UTC the git update took place.
$timestamp = scalar(gmtime)." UTC" if (!$gitstat);
}
# get the last 5 commits for show (even if no pull was made)
@commits=`git log --pretty=oneline --abbrev-commit -5`;
logit "The most recent curl git commits:";
for (@commits) {
chomp ($_);
logit " $_";
}
if (-d "ares/.git") {
chdir "ares";
if($nogitpull) {
logit "skipping git pull (--nogitpull) in ares";
} else {
logit "run git pull in ares";
system("git pull 2>&1");
$gitstat += $?;
logit "failed to update from ares git ($?), continue anyway" if ($?);
# Set timestamp to the UTC the git update took place.
$timestamp = scalar(gmtime)." UTC" if (!$gitstat);
}
# get the last 5 commits for show (even if no pull was made)
@commits=`git log --pretty=oneline --abbrev-commit -5`;
logit "The most recent ares git commits:";
for (@commits) {
chomp ($_);
logit " $_";
}
chdir "$CURLDIR";
}
if($nobuildconf) {
logit "told to not run buildconf";
}
elsif ($configurebuild) {
# remove possible left-overs from the past
unlink "configure";
unlink "autom4te.cache";
# generate the build files
logit "invoke buildconf";
open(F, "./buildconf 2>&1 |") or die;
open(LOG, ">$buildlog") or die;
while (<F>) {
my $ll = $_;
print $ll;
print LOG $ll;
}
close(F);
close(LOG);
logit "buildconf was successful";
}
else {
logit "buildconf was successful (dummy message)";
}
}
# Set timestamp to the one in curlver.h if this isn't a git test build.
if ((-f "include/curl/curlver.h") &&
(open(F, "<include/curl/curlver.h"))) {
while (<F>) {
chomp;
if ($_ =~ /^\#define\s+LIBCURL_TIMESTAMP\s+\"(.+)\".*$/) {
my $stampstring = $1;
if ($stampstring !~ /DEV/) {
$stampstring =~ s/\s+UTC//;
$timestamp = $stampstring." UTC";
}
last;
}
}
close(F);
}
# Show timestamp we are using for this test build.
logit "timestamp = $timestamp";
if ($configurebuild) {
if (-f "configure") {
logit "configure created (at least it exists)";
} else {
mydie "no configure created/found";
}
} else {
logit "configure created (dummy message)"; # dummy message to feign success
}
sub findinpath {
my $c;
my $e;
my $x = ($^O eq 'MSWin32') ? '.exe' : '';
my $s = ($^O eq 'MSWin32') ? ';' : ':';
my $p=$ENV{'PATH'};
my @pa = split($s, $p);
for $c (@_) {
for $e (@pa) {
if( -x "$e/$c$x") {
return $c;
}
}
}
}
my $make = findinpath("gmake", "make", "nmake");
if(!$make) {
mydie "Couldn't find make in the PATH";
}
# force to 'nmake' for VC builds
$make = "nmake" if ($targetos =~ /vc/);
# force to 'wmake' for Watcom builds
$make = "wmake" if ($targetos =~ /watcom/);
logit "going with $make as make";
# change to build dir
chdir "$pwd/$build";
if ($configurebuild) {
# run configure script
print `$CURLDIR/configure $confopts 2>&1`;
if (-f "lib/Makefile") {
logit "configure seems to have finished fine";
} else {
mydie "configure didn't work";
}
} else {
logit "copying files to build dir ...";
if (($^O eq 'MSWin32') && ($targetos !~ /netware/)) {
system("xcopy /s /q \"$CURLDIR\" .");
system("buildconf.bat");
}
elsif ($targetos =~ /netware/) {
system("cp -afr $CURLDIR/* .");
system("cp -af $CURLDIR/Makefile.dist Makefile");
system("$make -i -C lib -f Makefile.netware prebuild");
system("$make -i -C src -f Makefile.netware prebuild");
if (-d "$CURLDIR/ares") {
system("$make -i -C ares -f Makefile.netware prebuild");
}
}
elsif ($^O eq 'linux') {
system("cp -afr $CURLDIR/* .");
system("cp -af $CURLDIR/Makefile.dist Makefile");
system("$make -i -C lib -f Makefile.$targetos prebuild");
system("$make -i -C src -f Makefile.$targetos prebuild");
if (-d "$CURLDIR/ares") {
system("cp -af $CURLDIR/ares/ares_build.h.dist ./ares/ares_build.h");
system("$make -i -C ares -f Makefile.$targetos prebuild");
}
}
}
if(-f "./libcurl.pc") {
logit_spaced "display libcurl.pc";
if(open(F, "<./libcurl.pc")) {
while(<F>) {
my $ll = $_;
print $ll if(($ll !~ /^ *#/) && ($ll !~ /^ *$/));
}
close(F);
}
}
logit_spaced "display lib/$confheader";
open(F, "lib/$confheader") or die "lib/$confheader: $!";
while (<F>) {
print if /^ *#/;
}
close(F);
if (($have_embedded_ares) &&
(grepfile("^#define USE_ARES", "lib/$confheader"))) {
print "\n";
logit "setup to build ares";
if(-f "./ares/libcares.pc") {
logit_spaced "display ares/libcares.pc";
if(open(F, "<./ares/libcares.pc")) {
while(<F>) {
my $ll = $_;
print $ll if(($ll !~ /^ *#/) && ($ll !~ /^ *$/));
}
close(F);
}
}
if(-f "./ares/ares_build.h") {
logit_spaced "display ares/ares_build.h";
if(open(F, "<./ares/ares_build.h")) {
while(<F>) {
my $ll = $_;
print $ll if(($ll =~ /^ *# *define *CARES_/) && ($ll !~ /__CARES_BUILD_H/));
}
close(F);
}
}
else {
mydie "no ares_build.h created/found";
}
$confheader =~ s/curl/ares/;
logit_spaced "display ares/$confheader";
if(open(F, "ares/$confheader")) {
while (<F>) {
print if /^ *#/;
}
close(F);
}
print "\n";
logit "build ares";
chdir "ares";
if ($targetos && !$configurebuild) {
logit "$make -f Makefile.$targetos";
open(F, "$make -f Makefile.$targetos 2>&1 |") or die;
}
else {
logit "$make";
open(F, "$make 2>&1 |") or die;
}
while (<F>) {
s/$pwd//g;
print;
}
close(F);
if (-f "libcares$libext") {
logit "ares is now built successfully (libcares$libext)";
} else {
mydie "ares build failed (libcares$libext)";
}
# cd back to the curl build dir
chdir "$pwd/$build";
}
my $mkcmd = "$make -i" . ($targetos && !$configurebuild ? " $targetos" : "");
logit "$mkcmd";
open(F, "$mkcmd 2>&1 |") or die;
while (<F>) {
s/$pwd//g;
print;
}
close(F);
if (-f "lib/libcurl$libext") {
logit "libcurl was created fine (libcurl$libext)";
}
else {
mydie "libcurl was not created (libcurl$libext)";
}
if (-f "src/curl$binext") {
logit "curl was created fine (curl$binext)";
}
else {
mydie "curl was not created (curl$binext)";
}
if (!$crosscompile || (($extvercmd ne '') && (-x $extvercmd))) {
logit "display curl${binext} --version output";
my $cmd = ($extvercmd ne '' ? $extvercmd.' ' : '')."./src/curl${binext} --version|";
open(F, $cmd);
while(<F>) {
# strip CR from output on non-win32 platforms (wine on Linux)
s/\r// if ($^O ne 'MSWin32');
print;
}
close(F);
}
if ($configurebuild && !$crosscompile) {
my $host_triplet = get_host_triplet();
# build example programs for selected build targets
if(($host_triplet =~ /([^-]+)-([^-]+)-irix(.*)/) ||
($host_triplet =~ /([^-]+)-([^-]+)-aix(.*)/) ||
($host_triplet =~ /([^-]+)-([^-]+)-osf(.*)/) ||
($host_triplet =~ /([^-]+)-([^-]+)-solaris2(.*)/)) {
chdir "$pwd/$build/docs/examples";
logit_spaced "build examples";
open(F, "$make -i 2>&1 |") or die;
open(LOG, ">$buildlog") or die;
while (<F>) {
s/$pwd//g;
print;
print LOG;
}
close(F);
close(LOG);
chdir "$pwd/$build";
}
# build and run full test suite
my $o;
if($runtestopts) {
$o = "TEST_F=\"$runtestopts\" ";
}
logit "$make -k ${o}test-full";
open(F, "$make -k ${o}test-full 2>&1 |") or die;
open(LOG, ">$buildlog") or die;
while (<F>) {
s/$pwd//g;
print;
print LOG;
}
close(F);
close(LOG);
if (grepfile("^TEST", $buildlog)) {
logit "tests were run";
} else {
mydie "test suite failure";
}
if (grepfile("^TESTFAIL:", $buildlog)) {
logit "the tests were not successful";
} else {
logit "the tests were successful!";
}
}
else {
if($crosscompile) {
my $host_triplet = get_host_triplet();
# build example programs for selected cross-compiles
if(($host_triplet =~ /([^-]+)-([^-]+)-mingw(.*)/) ||
($host_triplet =~ /([^-]+)-([^-]+)-android(.*)/)) {
chdir "$pwd/$build/docs/examples";
logit_spaced "build examples";
open(F, "$make -i 2>&1 |") or die;
open(LOG, ">$buildlog") or die;
while (<F>) {
s/$pwd//g;
print;
print LOG;
}
close(F);
close(LOG);
chdir "$pwd/$build";
}
# build test harness programs for selected cross-compiles
if($host_triplet =~ /([^-]+)-([^-]+)-mingw(.*)/) {
chdir "$pwd/$build/tests";
logit_spaced "build test harness";
open(F, "$make -i 2>&1 |") or die;
open(LOG, ">$buildlog") or die;
while (<F>) {
s/$pwd//g;
print;
print LOG;
}
close(F);
close(LOG);
chdir "$pwd/$build";
}
logit_spaced "cross-compiling, can't run tests";
}
# dummy message to feign success
print "TESTDONE: 1 tests out of 0 (dummy message)\n";
}
# create a tarball if we got that option.
if (($mktarball ne '') && (-x $mktarball)) {
system($mktarball);
}
# mydie to cleanup
mydie "ending nicely";
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/sshserver.pl | #!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
#***************************************************************************
# Starts sshd for use in the SCP and SFTP curl test harness tests.
# Also creates the ssh configuration files needed for these tests.
use strict;
use warnings;
use Cwd;
use Cwd 'abs_path';
use Digest::MD5;
use Digest::MD5 'md5_hex';
use Digest::SHA;
use Digest::SHA 'sha256_base64';
use MIME::Base64;
#***************************************************************************
# Variables and subs imported from sshhelp module
#
use sshhelp qw(
$sshdexe
$sshexe
$sftpsrvexe
$sftpexe
$sshkeygenexe
$sshdconfig
$sshconfig
$sftpconfig
$knownhosts
$sshdlog
$sshlog
$sftplog
$sftpcmds
$hstprvkeyf
$hstpubkeyf
$hstpubmd5f
$hstpubsha256f
$cliprvkeyf
$clipubkeyf
display_sshdconfig
display_sshconfig
display_sftpconfig
display_sshdlog
display_sshlog
display_sftplog
dump_array
find_sshd
find_ssh
find_sftpsrv
find_sftp
find_sshkeygen
logmsg
sshversioninfo
);
#***************************************************************************
# Subs imported from serverhelp module
#
use serverhelp qw(
server_pidfilename
server_logfilename
);
use pathhelp;
#***************************************************************************
my $verbose = 0; # set to 1 for debugging
my $debugprotocol = 0; # set to 1 for protocol debugging
my $port = 8999; # our default SCP/SFTP server port
my $listenaddr = '127.0.0.1'; # default address on which to listen
my $ipvnum = 4; # default IP version of listener address
my $idnum = 1; # default ssh daemon instance number
my $proto = 'ssh'; # protocol the ssh daemon speaks
my $path = getcwd(); # current working directory
my $logdir = $path .'/log'; # directory for log files
my $username = $ENV{USER}; # default user
my $pidfile; # ssh daemon pid file
my $identity = 'curl_client_key'; # default identity file
my $error;
my @cfgarr;
#***************************************************************************
# Parse command line options
#
while(@ARGV) {
if($ARGV[0] eq '--verbose') {
$verbose = 1;
}
elsif($ARGV[0] eq '--debugprotocol') {
$verbose = 1;
$debugprotocol = 1;
}
elsif($ARGV[0] eq '--user') {
if($ARGV[1]) {
$username = $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--id') {
if($ARGV[1]) {
if($ARGV[1] =~ /^(\d+)$/) {
$idnum = $1 if($1 > 0);
shift @ARGV;
}
}
}
elsif($ARGV[0] eq '--ipv4') {
$ipvnum = 4;
$listenaddr = '127.0.0.1' if($listenaddr eq '::1');
}
elsif($ARGV[0] eq '--ipv6') {
$ipvnum = 6;
$listenaddr = '::1' if($listenaddr eq '127.0.0.1');
}
elsif($ARGV[0] eq '--addr') {
if($ARGV[1]) {
my $tmpstr = $ARGV[1];
if($tmpstr =~ /^(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)$/) {
$listenaddr = "$1.$2.$3.$4" if($ipvnum == 4);
shift @ARGV;
}
elsif($ipvnum == 6) {
$listenaddr = $tmpstr;
$listenaddr =~ s/^\[(.*)\]$/$1/;
shift @ARGV;
}
}
}
elsif($ARGV[0] eq '--pidfile') {
if($ARGV[1]) {
$pidfile = "$path/". $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--sshport') {
if($ARGV[1]) {
if($ARGV[1] =~ /^(\d+)$/) {
$port = $1;
shift @ARGV;
}
}
}
else {
print STDERR "\nWarning: sshserver.pl unknown parameter: $ARGV[0]\n";
}
shift @ARGV;
}
#***************************************************************************
# Default ssh daemon pid file name
#
if(!$pidfile) {
$pidfile = "$path/". server_pidfilename($proto, $ipvnum, $idnum);
}
#***************************************************************************
# ssh and sftp server log file names
#
$sshdlog = server_logfilename($logdir, 'ssh', $ipvnum, $idnum);
$sftplog = server_logfilename($logdir, 'sftp', $ipvnum, $idnum);
#***************************************************************************
# Logging level for ssh server and client
#
my $loglevel = $debugprotocol?'DEBUG3':'DEBUG2';
#***************************************************************************
# Validate username
#
if(!$username) {
$error = 'Will not run ssh server without a user name';
}
elsif($username eq 'root') {
$error = 'Will not run ssh server as root to mitigate security risks';
}
if($error) {
logmsg $error;
exit 1;
}
#***************************************************************************
# Find out ssh daemon canonical file name
#
my $sshd = find_sshd();
if(!$sshd) {
logmsg "cannot find $sshdexe";
exit 1;
}
#***************************************************************************
# Find out ssh daemon version info
#
my ($sshdid, $sshdvernum, $sshdverstr, $sshderror) = sshversioninfo($sshd);
if(!$sshdid) {
# Not an OpenSSH or SunSSH ssh daemon
logmsg $sshderror if($verbose);
logmsg 'SCP and SFTP tests require OpenSSH 2.9.9 or later';
exit 1;
}
logmsg "ssh server found $sshd is $sshdverstr" if($verbose);
#***************************************************************************
# ssh daemon command line options we might use and version support
#
# -e: log stderr : OpenSSH 2.9.0 and later
# -f: sshd config file : OpenSSH 1.2.1 and later
# -D: no daemon forking : OpenSSH 2.5.0 and later
# -o: command-line option : OpenSSH 3.1.0 and later
# -t: test config file : OpenSSH 2.9.9 and later
# -?: sshd version info : OpenSSH 1.2.1 and later
#
# -e: log stderr : SunSSH 1.0.0 and later
# -f: sshd config file : SunSSH 1.0.0 and later
# -D: no daemon forking : SunSSH 1.0.0 and later
# -o: command-line option : SunSSH 1.0.0 and later
# -t: test config file : SunSSH 1.0.0 and later
# -?: sshd version info : SunSSH 1.0.0 and later
#***************************************************************************
# Verify minimum ssh daemon version
#
if((($sshdid =~ /OpenSSH/) && ($sshdvernum < 299)) ||
(($sshdid =~ /SunSSH/) && ($sshdvernum < 100))) {
logmsg 'SCP and SFTP tests require OpenSSH 2.9.9 or later';
exit 1;
}
#***************************************************************************
# Find out sftp server plugin canonical file name
#
my $sftpsrv = find_sftpsrv();
if(!$sftpsrv) {
logmsg "cannot find $sftpsrvexe";
exit 1;
}
logmsg "sftp server plugin found $sftpsrv" if($verbose);
#***************************************************************************
# Find out sftp client canonical file name
#
my $sftp = find_sftp();
if(!$sftp) {
logmsg "cannot find $sftpexe";
exit 1;
}
logmsg "sftp client found $sftp" if($verbose);
#***************************************************************************
# Find out ssh keygen canonical file name
#
my $sshkeygen = find_sshkeygen();
if(!$sshkeygen) {
logmsg "cannot find $sshkeygenexe";
exit 1;
}
logmsg "ssh keygen found $sshkeygen" if($verbose);
#***************************************************************************
# Find out ssh client canonical file name
#
my $ssh = find_ssh();
if(!$ssh) {
logmsg "cannot find $sshexe";
exit 1;
}
#***************************************************************************
# Find out ssh client version info
#
my ($sshid, $sshvernum, $sshverstr, $ssherror) = sshversioninfo($ssh);
if(!$sshid) {
# Not an OpenSSH or SunSSH ssh client
logmsg $ssherror if($verbose);
logmsg 'SCP and SFTP tests require OpenSSH 2.9.9 or later';
exit 1;
}
logmsg "ssh client found $ssh is $sshverstr" if($verbose);
#***************************************************************************
# ssh client command line options we might use and version support
#
# -D: dynamic app port forwarding : OpenSSH 2.9.9 and later
# -F: ssh config file : OpenSSH 2.9.9 and later
# -N: no shell/command : OpenSSH 2.1.0 and later
# -p: connection port : OpenSSH 1.2.1 and later
# -v: verbose messages : OpenSSH 1.2.1 and later
# -vv: increase verbosity : OpenSSH 2.3.0 and later
# -V: ssh version info : OpenSSH 1.2.1 and later
#
# -D: dynamic app port forwarding : SunSSH 1.0.0 and later
# -F: ssh config file : SunSSH 1.0.0 and later
# -N: no shell/command : SunSSH 1.0.0 and later
# -p: connection port : SunSSH 1.0.0 and later
# -v: verbose messages : SunSSH 1.0.0 and later
# -vv: increase verbosity : SunSSH 1.0.0 and later
# -V: ssh version info : SunSSH 1.0.0 and later
#***************************************************************************
# Verify minimum ssh client version
#
if((($sshid =~ /OpenSSH/) && ($sshvernum < 299)) ||
(($sshid =~ /SunSSH/) && ($sshvernum < 100))) {
logmsg 'SCP and SFTP tests require OpenSSH 2.9.9 or later';
exit 1;
}
#***************************************************************************
# ssh keygen command line options we actually use and version support
#
# -C: identity comment : OpenSSH 1.2.1 and later
# -f: key filename : OpenSSH 1.2.1 and later
# -N: new passphrase : OpenSSH 1.2.1 and later
# -q: quiet keygen : OpenSSH 1.2.1 and later
# -t: key type : OpenSSH 2.5.0 and later
#
# -C: identity comment : SunSSH 1.0.0 and later
# -f: key filename : SunSSH 1.0.0 and later
# -N: new passphrase : SunSSH 1.0.0 and later
# -q: quiet keygen : SunSSH 1.0.0 and later
# -t: key type : SunSSH 1.0.0 and later
#***************************************************************************
# Generate host and client key files for curl's tests
#
if((! -e $hstprvkeyf) || (! -s $hstprvkeyf) ||
(! -e $hstpubkeyf) || (! -s $hstpubkeyf) ||
(! -e $hstpubmd5f) || (! -s $hstpubmd5f) ||
(! -e $hstpubsha256f) || (! -s $hstpubsha256f) ||
(! -e $cliprvkeyf) || (! -s $cliprvkeyf) ||
(! -e $clipubkeyf) || (! -s $clipubkeyf)) {
# Make sure all files are gone so ssh-keygen doesn't complain
unlink($hstprvkeyf, $hstpubkeyf, $hstpubmd5f, $hstpubsha256f,
$cliprvkeyf, $clipubkeyf);
logmsg 'generating host keys...' if($verbose);
if(system "\"$sshkeygen\" -q -t rsa -f $hstprvkeyf -C 'curl test server' -N ''") {
logmsg 'Could not generate host key';
exit 1;
}
logmsg 'generating client keys...' if($verbose);
if(system "\"$sshkeygen\" -q -t rsa -f $cliprvkeyf -C 'curl test client' -N ''") {
logmsg 'Could not generate client key';
exit 1;
}
# Make sure that permissions are restricted so openssh doesn't complain
system "chmod 600 $hstprvkeyf";
system "chmod 600 $cliprvkeyf";
# Save md5 and sha256 hashes of public host key
open(RSAKEYFILE, "<$hstpubkeyf");
my @rsahostkey = do { local $/ = ' '; <RSAKEYFILE> };
close(RSAKEYFILE);
if(!$rsahostkey[1]) {
logmsg 'Failed parsing base64 encoded RSA host key';
exit 1;
}
open(PUBMD5FILE, ">$hstpubmd5f");
print PUBMD5FILE md5_hex(decode_base64($rsahostkey[1]));
close(PUBMD5FILE);
if((! -e $hstpubmd5f) || (! -s $hstpubmd5f)) {
logmsg 'Failed writing md5 hash of RSA host key';
exit 1;
}
open(PUBSHA256FILE, ">$hstpubsha256f");
print PUBSHA256FILE sha256_base64(decode_base64($rsahostkey[1]));
close(PUBSHA256FILE);
if((! -e $hstpubsha256f) || (! -s $hstpubsha256f)) {
logmsg 'Failed writing sha256 hash of RSA host key';
exit 1;
}
}
#***************************************************************************
# Convert paths for curl's tests running on Windows with Cygwin/Msys OpenSSH
#
my $clipubkeyf_config = abs_path("$path/$clipubkeyf");
my $hstprvkeyf_config = abs_path("$path/$hstprvkeyf");
my $pidfile_config = $pidfile;
my $sftpsrv_config = $sftpsrv;
if (pathhelp::os_is_win()) {
# Ensure to use MinGW/Cygwin paths
$clipubkeyf_config = pathhelp::build_sys_abs_path($clipubkeyf_config);
$hstprvkeyf_config = pathhelp::build_sys_abs_path($hstprvkeyf_config);
$pidfile_config = pathhelp::build_sys_abs_path($pidfile_config);
$sftpsrv_config = "internal-sftp";
}
if ($sshdid =~ /OpenSSH-Windows/) {
# Ensure to use native Windows paths with OpenSSH for Windows
$clipubkeyf_config = pathhelp::sys_native_abs_path($clipubkeyf);
$hstprvkeyf_config = pathhelp::sys_native_abs_path($hstprvkeyf);
$pidfile_config = pathhelp::sys_native_abs_path($pidfile);
$sftpsrv_config = pathhelp::sys_native_abs_path($sftpsrv);
$sshdconfig = pathhelp::sys_native_abs_path($sshdconfig);
$sshconfig = pathhelp::sys_native_abs_path($sshconfig);
$sftpconfig = pathhelp::sys_native_abs_path($sftpconfig);
}
#***************************************************************************
# ssh daemon configuration file options we might use and version support
#
# AFSTokenPassing : OpenSSH 1.2.1 and later [1]
# AddressFamily : OpenSSH 4.0.0 and later
# AllowTcpForwarding : OpenSSH 2.3.0 and later
# AllowUsers : OpenSSH 1.2.1 and later
# AuthorizedKeysFile : OpenSSH 2.9.9 and later
# AuthorizedKeysFile2 : OpenSSH 2.9.9 and later
# Banner : OpenSSH 2.5.0 and later
# ChallengeResponseAuthentication : OpenSSH 2.5.0 and later
# Ciphers : OpenSSH 2.1.0 and later [3]
# ClientAliveCountMax : OpenSSH 2.9.0 and later
# ClientAliveInterval : OpenSSH 2.9.0 and later
# Compression : OpenSSH 3.3.0 and later
# DenyUsers : OpenSSH 1.2.1 and later
# ForceCommand : OpenSSH 4.4.0 and later [3]
# GatewayPorts : OpenSSH 2.1.0 and later
# GSSAPIAuthentication : OpenSSH 3.7.0 and later [1]
# GSSAPICleanupCredentials : OpenSSH 3.8.0 and later [1]
# GSSAPIKeyExchange : SunSSH 1.0.0 and later [1]
# GSSAPIStoreDelegatedCredentials : SunSSH 1.0.0 and later [1]
# GSSCleanupCreds : SunSSH 1.0.0 and later [1]
# GSSUseSessionCredCache : SunSSH 1.0.0 and later [1]
# HostbasedAuthentication : OpenSSH 2.9.0 and later
# HostbasedUsesNameFromPacketOnly : OpenSSH 2.9.0 and later
# HostKey : OpenSSH 1.2.1 and later
# IgnoreRhosts : OpenSSH 1.2.1 and later
# IgnoreUserKnownHosts : OpenSSH 1.2.1 and later
# KbdInteractiveAuthentication : OpenSSH 2.3.0 and later
# KeepAlive : OpenSSH 1.2.1 and later
# KerberosAuthentication : OpenSSH 1.2.1 and later [1]
# KerberosGetAFSToken : OpenSSH 3.8.0 and later [1]
# KerberosOrLocalPasswd : OpenSSH 1.2.1 and later [1]
# KerberosTgtPassing : OpenSSH 1.2.1 and later [1]
# KerberosTicketCleanup : OpenSSH 1.2.1 and later [1]
# KeyRegenerationInterval : OpenSSH 1.2.1 and later
# ListenAddress : OpenSSH 1.2.1 and later
# LoginGraceTime : OpenSSH 1.2.1 and later
# LogLevel : OpenSSH 1.2.1 and later
# LookupClientHostnames : SunSSH 1.0.0 and later
# MACs : OpenSSH 2.5.0 and later [3]
# Match : OpenSSH 4.4.0 and later [3]
# MaxAuthTries : OpenSSH 3.9.0 and later
# MaxStartups : OpenSSH 2.2.0 and later
# PAMAuthenticationViaKbdInt : OpenSSH 2.9.0 and later [2]
# PasswordAuthentication : OpenSSH 1.2.1 and later
# PermitEmptyPasswords : OpenSSH 1.2.1 and later
# PermitOpen : OpenSSH 4.4.0 and later [3]
# PermitRootLogin : OpenSSH 1.2.1 and later
# PermitTunnel : OpenSSH 4.3.0 and later
# PermitUserEnvironment : OpenSSH 3.5.0 and later
# PidFile : OpenSSH 2.1.0 and later
# Port : OpenSSH 1.2.1 and later
# PrintLastLog : OpenSSH 2.9.0 and later
# PrintMotd : OpenSSH 1.2.1 and later
# Protocol : OpenSSH 2.1.0 and later
# PubkeyAuthentication : OpenSSH 2.5.0 and later
# RhostsAuthentication : OpenSSH 1.2.1 and later
# RhostsRSAAuthentication : OpenSSH 1.2.1 and later
# RSAAuthentication : OpenSSH 1.2.1 and later
# ServerKeyBits : OpenSSH 1.2.1 and later
# SkeyAuthentication : OpenSSH 1.2.1 and later [1]
# StrictModes : OpenSSH 1.2.1 and later
# Subsystem : OpenSSH 2.2.0 and later
# SyslogFacility : OpenSSH 1.2.1 and later
# TCPKeepAlive : OpenSSH 3.8.0 and later
# UseDNS : OpenSSH 3.7.0 and later
# UseLogin : OpenSSH 1.2.1 and later
# UsePAM : OpenSSH 3.7.0 and later [1][2]
# UsePrivilegeSeparation : OpenSSH 3.2.2 and later
# VerifyReverseMapping : OpenSSH 3.1.0 and later
# X11DisplayOffset : OpenSSH 1.2.1 and later [3]
# X11Forwarding : OpenSSH 1.2.1 and later
# X11UseLocalhost : OpenSSH 3.1.0 and later
# XAuthLocation : OpenSSH 2.1.1 and later [3]
#
# [1] Option only available if activated at compile time
# [2] Option specific for portable versions
# [3] Option not used in our ssh server config file
#***************************************************************************
# Initialize sshd config with options actually supported in OpenSSH 2.9.9
#
logmsg 'generating ssh server config file...' if($verbose);
@cfgarr = ();
push @cfgarr, '# This is a generated file. Do not edit.';
push @cfgarr, "# $sshdverstr sshd configuration file for curl testing";
push @cfgarr, '#';
# AllowUsers and DenyUsers options should use lowercase on Windows
# and do not support quotes around values for some unknown reason.
if ($sshdid =~ /OpenSSH-Windows/) {
my $username_lc = lc $username;
if (exists $ENV{USERDOMAIN}) {
my $userdomain_lc = lc $ENV{USERDOMAIN};
$username_lc = "$userdomain_lc\\$username_lc";
}
$username_lc =~ s/ /\?/g; # replace space with ?
push @cfgarr, "DenyUsers !$username_lc";
push @cfgarr, "AllowUsers $username_lc";
} else {
push @cfgarr, "DenyUsers !$username";
push @cfgarr, "AllowUsers $username";
}
push @cfgarr, "AuthorizedKeysFile $clipubkeyf_config";
push @cfgarr, "AuthorizedKeysFile2 $clipubkeyf_config";
push @cfgarr, "HostKey $hstprvkeyf_config";
if ($sshdid !~ /OpenSSH-Windows/) {
push @cfgarr, "PidFile $pidfile_config";
}
push @cfgarr, '#';
push @cfgarr, "Port $port";
push @cfgarr, "ListenAddress $listenaddr";
push @cfgarr, 'Protocol 2';
push @cfgarr, '#';
push @cfgarr, 'AllowTcpForwarding yes';
push @cfgarr, 'Banner none';
push @cfgarr, 'ChallengeResponseAuthentication no';
push @cfgarr, 'ClientAliveCountMax 3';
push @cfgarr, 'ClientAliveInterval 0';
push @cfgarr, 'GatewayPorts no';
push @cfgarr, 'HostbasedAuthentication no';
push @cfgarr, 'HostbasedUsesNameFromPacketOnly no';
push @cfgarr, 'IgnoreRhosts yes';
push @cfgarr, 'IgnoreUserKnownHosts yes';
push @cfgarr, 'KeyRegenerationInterval 0';
push @cfgarr, 'LoginGraceTime 30';
push @cfgarr, "LogLevel $loglevel";
push @cfgarr, 'MaxStartups 5';
push @cfgarr, 'PasswordAuthentication no';
push @cfgarr, 'PermitEmptyPasswords no';
push @cfgarr, 'PermitRootLogin no';
push @cfgarr, 'PrintLastLog no';
push @cfgarr, 'PrintMotd no';
push @cfgarr, 'PubkeyAuthentication yes';
push @cfgarr, 'RhostsRSAAuthentication no';
push @cfgarr, 'RSAAuthentication no';
push @cfgarr, 'ServerKeyBits 768';
push @cfgarr, 'StrictModes no';
push @cfgarr, "Subsystem sftp \"$sftpsrv_config\"";
push @cfgarr, 'SyslogFacility AUTH';
push @cfgarr, 'UseLogin no';
push @cfgarr, 'X11Forwarding no';
push @cfgarr, '#';
#***************************************************************************
# Write out initial sshd configuration file for curl's tests
#
$error = dump_array($sshdconfig, @cfgarr);
if($error) {
logmsg $error;
exit 1;
}
#***************************************************************************
# Verifies at run time if sshd supports a given configuration file option
#
sub sshd_supports_opt {
my ($option, $value) = @_;
my $err;
#
if((($sshdid =~ /OpenSSH/) && ($sshdvernum >= 310)) ||
($sshdid =~ /SunSSH/)) {
# ssh daemon supports command line options -t -f and -o
$err = grep /((Unsupported)|(Bad configuration)|(Deprecated)) option.*$option/,
qx("$sshd" -t -f $sshdconfig -o "$option=$value" 2>&1);
return !$err;
}
if(($sshdid =~ /OpenSSH/) && ($sshdvernum >= 299)) {
# ssh daemon supports command line options -t and -f
$err = dump_array($sshdconfig, (@cfgarr, "$option $value"));
if($err) {
logmsg $err;
return 0;
}
$err = grep /((Unsupported)|(Bad configuration)|(Deprecated)) option.*$option/,
qx("$sshd" -t -f $sshdconfig 2>&1);
unlink $sshdconfig;
return !$err;
}
return 0;
}
#***************************************************************************
# Kerberos Authentication support may have not been built into sshd
#
if(sshd_supports_opt('KerberosAuthentication','no')) {
push @cfgarr, 'KerberosAuthentication no';
}
if(sshd_supports_opt('KerberosGetAFSToken','no')) {
push @cfgarr, 'KerberosGetAFSToken no';
}
if(sshd_supports_opt('KerberosOrLocalPasswd','no')) {
push @cfgarr, 'KerberosOrLocalPasswd no';
}
if(sshd_supports_opt('KerberosTgtPassing','no')) {
push @cfgarr, 'KerberosTgtPassing no';
}
if(sshd_supports_opt('KerberosTicketCleanup','yes')) {
push @cfgarr, 'KerberosTicketCleanup yes';
}
#***************************************************************************
# Andrew File System support may have not been built into sshd
#
if(sshd_supports_opt('AFSTokenPassing','no')) {
push @cfgarr, 'AFSTokenPassing no';
}
#***************************************************************************
# S/Key authentication support may have not been built into sshd
#
if(sshd_supports_opt('SkeyAuthentication','no')) {
push @cfgarr, 'SkeyAuthentication no';
}
#***************************************************************************
# GSSAPI Authentication support may have not been built into sshd
#
my $sshd_builtwith_GSSAPI;
if(sshd_supports_opt('GSSAPIAuthentication','no')) {
push @cfgarr, 'GSSAPIAuthentication no';
$sshd_builtwith_GSSAPI = 1;
}
if(sshd_supports_opt('GSSAPICleanupCredentials','yes')) {
push @cfgarr, 'GSSAPICleanupCredentials yes';
}
if(sshd_supports_opt('GSSAPIKeyExchange','no')) {
push @cfgarr, 'GSSAPIKeyExchange no';
}
if(sshd_supports_opt('GSSAPIStoreDelegatedCredentials','no')) {
push @cfgarr, 'GSSAPIStoreDelegatedCredentials no';
}
if(sshd_supports_opt('GSSCleanupCreds','yes')) {
push @cfgarr, 'GSSCleanupCreds yes';
}
if(sshd_supports_opt('GSSUseSessionCredCache','no')) {
push @cfgarr, 'GSSUseSessionCredCache no';
}
push @cfgarr, '#';
#***************************************************************************
# Options that might be supported or not in sshd OpenSSH 2.9.9 and later
#
if(sshd_supports_opt('AddressFamily','any')) {
# Address family must be specified before ListenAddress
splice @cfgarr, 14, 0, 'AddressFamily any';
}
if(sshd_supports_opt('Compression','no')) {
push @cfgarr, 'Compression no';
}
if(sshd_supports_opt('KbdInteractiveAuthentication','no')) {
push @cfgarr, 'KbdInteractiveAuthentication no';
}
if(sshd_supports_opt('KeepAlive','no')) {
push @cfgarr, 'KeepAlive no';
}
if(sshd_supports_opt('LookupClientHostnames','no')) {
push @cfgarr, 'LookupClientHostnames no';
}
if(sshd_supports_opt('MaxAuthTries','10')) {
push @cfgarr, 'MaxAuthTries 10';
}
if(sshd_supports_opt('PAMAuthenticationViaKbdInt','no')) {
push @cfgarr, 'PAMAuthenticationViaKbdInt no';
}
if(sshd_supports_opt('PermitTunnel','no')) {
push @cfgarr, 'PermitTunnel no';
}
if(sshd_supports_opt('PermitUserEnvironment','no')) {
push @cfgarr, 'PermitUserEnvironment no';
}
if(sshd_supports_opt('RhostsAuthentication','no')) {
push @cfgarr, 'RhostsAuthentication no';
}
if(sshd_supports_opt('TCPKeepAlive','no')) {
push @cfgarr, 'TCPKeepAlive no';
}
if(sshd_supports_opt('UseDNS','no')) {
push @cfgarr, 'UseDNS no';
}
if(sshd_supports_opt('UsePAM','no')) {
push @cfgarr, 'UsePAM no';
}
if($sshdid =~ /OpenSSH/) {
# http://bugs.opensolaris.org/bugdatabase/view_bug.do?bug_id=6492415
if(sshd_supports_opt('UsePrivilegeSeparation','no')) {
push @cfgarr, 'UsePrivilegeSeparation no';
}
}
if(sshd_supports_opt('VerifyReverseMapping','no')) {
push @cfgarr, 'VerifyReverseMapping no';
}
if(sshd_supports_opt('X11UseLocalhost','yes')) {
push @cfgarr, 'X11UseLocalhost yes';
}
push @cfgarr, '#';
#***************************************************************************
# Write out resulting sshd configuration file for curl's tests
#
$error = dump_array($sshdconfig, @cfgarr);
if($error) {
logmsg $error;
exit 1;
}
#***************************************************************************
# Verify that sshd actually supports our generated configuration file
#
if(system "\"$sshd\" -t -f $sshdconfig > $sshdlog 2>&1") {
logmsg "sshd configuration file $sshdconfig failed verification";
display_sshdlog();
display_sshdconfig();
exit 1;
}
#***************************************************************************
# Generate ssh client host key database file for curl's tests
#
if((! -e $knownhosts) || (! -s $knownhosts)) {
logmsg 'generating ssh client known hosts file...' if($verbose);
unlink($knownhosts);
if(open(RSAKEYFILE, "<$hstpubkeyf")) {
my @rsahostkey = do { local $/ = ' '; <RSAKEYFILE> };
if(close(RSAKEYFILE)) {
if(open(KNOWNHOSTS, ">$knownhosts")) {
print KNOWNHOSTS "$listenaddr ssh-rsa $rsahostkey[1]\n";
if(!close(KNOWNHOSTS)) {
$error = "Error: cannot close file $knownhosts";
}
}
else {
$error = "Error: cannot write file $knownhosts";
}
}
else {
$error = "Error: cannot close file $hstpubkeyf";
}
}
else {
$error = "Error: cannot read file $hstpubkeyf";
}
if($error) {
logmsg $error;
exit 1;
}
}
#***************************************************************************
# Convert paths for curl's tests running on Windows using Cygwin OpenSSH
#
my $identity_config = abs_path("$path/$identity");
my $knownhosts_config = abs_path("$path/$knownhosts");
if (pathhelp::os_is_win()) {
# Ensure to use MinGW/Cygwin paths
$identity_config = pathhelp::build_sys_abs_path($identity_config);
$knownhosts_config = pathhelp::build_sys_abs_path($knownhosts_config);
}
if ($sshdid =~ /OpenSSH-Windows/) {
# Ensure to use native Windows paths with OpenSSH for Windows
$identity_config = pathhelp::sys_native_abs_path($identity);
$knownhosts_config = pathhelp::sys_native_abs_path($knownhosts);
}
#***************************************************************************
# ssh client configuration file options we might use and version support
#
# AddressFamily : OpenSSH 3.7.0 and later
# BatchMode : OpenSSH 1.2.1 and later
# BindAddress : OpenSSH 2.9.9 and later
# ChallengeResponseAuthentication : OpenSSH 2.5.0 and later
# CheckHostIP : OpenSSH 1.2.1 and later
# Cipher : OpenSSH 1.2.1 and later [3]
# Ciphers : OpenSSH 2.1.0 and later [3]
# ClearAllForwardings : OpenSSH 2.9.9 and later
# Compression : OpenSSH 1.2.1 and later
# CompressionLevel : OpenSSH 1.2.1 and later [3]
# ConnectionAttempts : OpenSSH 1.2.1 and later
# ConnectTimeout : OpenSSH 3.7.0 and later
# ControlMaster : OpenSSH 3.9.0 and later
# ControlPath : OpenSSH 3.9.0 and later
# DisableBanner : SunSSH 1.2.0 and later
# DynamicForward : OpenSSH 2.9.0 and later
# EnableSSHKeysign : OpenSSH 3.6.0 and later
# EscapeChar : OpenSSH 1.2.1 and later [3]
# ExitOnForwardFailure : OpenSSH 4.4.0 and later
# ForwardAgent : OpenSSH 1.2.1 and later
# ForwardX11 : OpenSSH 1.2.1 and later
# ForwardX11Trusted : OpenSSH 3.8.0 and later
# GatewayPorts : OpenSSH 1.2.1 and later
# GlobalKnownHostsFile : OpenSSH 1.2.1 and later
# GSSAPIAuthentication : OpenSSH 3.7.0 and later [1]
# GSSAPIDelegateCredentials : OpenSSH 3.7.0 and later [1]
# HashKnownHosts : OpenSSH 4.0.0 and later
# Host : OpenSSH 1.2.1 and later
# HostbasedAuthentication : OpenSSH 2.9.0 and later
# HostKeyAlgorithms : OpenSSH 2.9.0 and later [3]
# HostKeyAlias : OpenSSH 2.5.0 and later [3]
# HostName : OpenSSH 1.2.1 and later
# IdentitiesOnly : OpenSSH 3.9.0 and later
# IdentityFile : OpenSSH 1.2.1 and later
# IgnoreIfUnknown : SunSSH 1.2.0 and later
# KeepAlive : OpenSSH 1.2.1 and later
# KbdInteractiveAuthentication : OpenSSH 2.3.0 and later
# KbdInteractiveDevices : OpenSSH 2.3.0 and later [3]
# LocalCommand : OpenSSH 4.3.0 and later [3]
# LocalForward : OpenSSH 1.2.1 and later [3]
# LogLevel : OpenSSH 1.2.1 and later
# MACs : OpenSSH 2.5.0 and later [3]
# NoHostAuthenticationForLocalhost : OpenSSH 3.0.0 and later
# NumberOfPasswordPrompts : OpenSSH 1.2.1 and later
# PasswordAuthentication : OpenSSH 1.2.1 and later
# PermitLocalCommand : OpenSSH 4.3.0 and later
# Port : OpenSSH 1.2.1 and later
# PreferredAuthentications : OpenSSH 2.5.2 and later
# Protocol : OpenSSH 2.1.0 and later
# ProxyCommand : OpenSSH 1.2.1 and later [3]
# PubkeyAuthentication : OpenSSH 2.5.0 and later
# RekeyLimit : OpenSSH 3.7.0 and later
# RemoteForward : OpenSSH 1.2.1 and later [3]
# RhostsRSAAuthentication : OpenSSH 1.2.1 and later
# RSAAuthentication : OpenSSH 1.2.1 and later
# ServerAliveCountMax : OpenSSH 3.8.0 and later
# ServerAliveInterval : OpenSSH 3.8.0 and later
# SmartcardDevice : OpenSSH 2.9.9 and later [1][3]
# StrictHostKeyChecking : OpenSSH 1.2.1 and later
# TCPKeepAlive : OpenSSH 3.8.0 and later
# Tunnel : OpenSSH 4.3.0 and later
# TunnelDevice : OpenSSH 4.3.0 and later [3]
# UsePAM : OpenSSH 3.7.0 and later [1][2][3]
# UsePrivilegedPort : OpenSSH 1.2.1 and later
# User : OpenSSH 1.2.1 and later
# UserKnownHostsFile : OpenSSH 1.2.1 and later
# VerifyHostKeyDNS : OpenSSH 3.8.0 and later
# XAuthLocation : OpenSSH 2.1.1 and later [3]
#
# [1] Option only available if activated at compile time
# [2] Option specific for portable versions
# [3] Option not used in our ssh client config file
#***************************************************************************
# Initialize ssh config with options actually supported in OpenSSH 2.9.9
#
logmsg 'generating ssh client config file...' if($verbose);
@cfgarr = ();
push @cfgarr, '# This is a generated file. Do not edit.';
push @cfgarr, "# $sshverstr ssh client configuration file for curl testing";
push @cfgarr, '#';
push @cfgarr, 'Host *';
push @cfgarr, '#';
push @cfgarr, "Port $port";
push @cfgarr, "HostName $listenaddr";
push @cfgarr, "User $username";
push @cfgarr, 'Protocol 2';
push @cfgarr, '#';
# BindAddress option is not supported by OpenSSH for Windows
if (!($sshdid =~ /OpenSSH-Windows/)) {
push @cfgarr, "BindAddress $listenaddr";
}
push @cfgarr, '#';
push @cfgarr, "IdentityFile $identity_config";
push @cfgarr, "UserKnownHostsFile $knownhosts_config";
push @cfgarr, '#';
push @cfgarr, 'BatchMode yes';
push @cfgarr, 'ChallengeResponseAuthentication no';
push @cfgarr, 'CheckHostIP no';
push @cfgarr, 'ClearAllForwardings no';
push @cfgarr, 'Compression no';
push @cfgarr, 'ConnectionAttempts 3';
push @cfgarr, 'ForwardAgent no';
push @cfgarr, 'ForwardX11 no';
push @cfgarr, 'GatewayPorts no';
push @cfgarr, 'GlobalKnownHostsFile /dev/null';
push @cfgarr, 'HostbasedAuthentication no';
push @cfgarr, 'KbdInteractiveAuthentication no';
push @cfgarr, "LogLevel $loglevel";
push @cfgarr, 'NumberOfPasswordPrompts 0';
push @cfgarr, 'PasswordAuthentication no';
push @cfgarr, 'PreferredAuthentications publickey';
push @cfgarr, 'PubkeyAuthentication yes';
# RSA authentication options are not supported by OpenSSH for Windows
if (!($sshdid =~ /OpenSSH-Windows/)) {
push @cfgarr, 'RhostsRSAAuthentication no';
push @cfgarr, 'RSAAuthentication no';
}
# Disabled StrictHostKeyChecking since it makes the tests fail on my
# OpenSSH_6.0p1 on Debian Linux / Daniel
push @cfgarr, 'StrictHostKeyChecking no';
push @cfgarr, 'UsePrivilegedPort no';
push @cfgarr, '#';
#***************************************************************************
# Options supported in ssh client newer than OpenSSH 2.9.9
#
if(($sshid =~ /OpenSSH/) && ($sshvernum >= 370)) {
push @cfgarr, 'AddressFamily any';
}
if((($sshid =~ /OpenSSH/) && ($sshvernum >= 370)) ||
(($sshid =~ /SunSSH/) && ($sshvernum >= 120))) {
push @cfgarr, 'ConnectTimeout 30';
}
if(($sshid =~ /OpenSSH/) && ($sshvernum >= 390)) {
push @cfgarr, 'ControlMaster no';
}
if(($sshid =~ /OpenSSH/) && ($sshvernum >= 420)) {
push @cfgarr, 'ControlPath none';
}
if(($sshid =~ /SunSSH/) && ($sshvernum >= 120)) {
push @cfgarr, 'DisableBanner yes';
}
if(($sshid =~ /OpenSSH/) && ($sshvernum >= 360)) {
push @cfgarr, 'EnableSSHKeysign no';
}
if(($sshid =~ /OpenSSH/) && ($sshvernum >= 440)) {
push @cfgarr, 'ExitOnForwardFailure yes';
}
if((($sshid =~ /OpenSSH/) && ($sshvernum >= 380)) ||
(($sshid =~ /SunSSH/) && ($sshvernum >= 120))) {
push @cfgarr, 'ForwardX11Trusted no';
}
if(($sshd_builtwith_GSSAPI) && ($sshdid eq $sshid) &&
($sshdvernum == $sshvernum)) {
push @cfgarr, 'GSSAPIAuthentication no';
push @cfgarr, 'GSSAPIDelegateCredentials no';
if($sshid =~ /SunSSH/) {
push @cfgarr, 'GSSAPIKeyExchange no';
}
}
if((($sshid =~ /OpenSSH/) && ($sshvernum >= 400)) ||
(($sshid =~ /SunSSH/) && ($sshvernum >= 120))) {
push @cfgarr, 'HashKnownHosts no';
}
if(($sshid =~ /OpenSSH/) && ($sshvernum >= 390)) {
push @cfgarr, 'IdentitiesOnly yes';
}
if(($sshid =~ /SunSSH/) && ($sshvernum >= 120)) {
push @cfgarr, 'IgnoreIfUnknown no';
}
if((($sshid =~ /OpenSSH/) && ($sshvernum < 380)) ||
($sshid =~ /SunSSH/)) {
push @cfgarr, 'KeepAlive no';
}
if((($sshid =~ /OpenSSH/) && ($sshvernum >= 300)) ||
($sshid =~ /SunSSH/)) {
push @cfgarr, 'NoHostAuthenticationForLocalhost no';
}
if(($sshid =~ /OpenSSH/) && ($sshvernum >= 430)) {
push @cfgarr, 'PermitLocalCommand no';
}
if((($sshid =~ /OpenSSH/) && ($sshvernum >= 370)) ||
(($sshid =~ /SunSSH/) && ($sshvernum >= 120))) {
push @cfgarr, 'RekeyLimit 1G';
}
if((($sshid =~ /OpenSSH/) && ($sshvernum >= 380)) ||
(($sshid =~ /SunSSH/) && ($sshvernum >= 120))) {
push @cfgarr, 'ServerAliveCountMax 3';
push @cfgarr, 'ServerAliveInterval 0';
}
if(($sshid =~ /OpenSSH/) && ($sshvernum >= 380)) {
push @cfgarr, 'TCPKeepAlive no';
}
if(($sshid =~ /OpenSSH/) && ($sshvernum >= 430)) {
push @cfgarr, 'Tunnel no';
}
if(($sshid =~ /OpenSSH/) && ($sshvernum >= 380)) {
push @cfgarr, 'VerifyHostKeyDNS no';
}
push @cfgarr, '#';
#***************************************************************************
# Write out resulting ssh client configuration file for curl's tests
#
$error = dump_array($sshconfig, @cfgarr);
if($error) {
logmsg $error;
exit 1;
}
#***************************************************************************
# Initialize client sftp config with options actually supported.
#
logmsg 'generating sftp client config file...' if($verbose);
splice @cfgarr, 1, 1, "# $sshverstr sftp client configuration file for curl testing";
#
for(my $i = scalar(@cfgarr) - 1; $i > 0; $i--) {
if($cfgarr[$i] =~ /^DynamicForward/) {
splice @cfgarr, $i, 1;
next;
}
if($cfgarr[$i] =~ /^ClearAllForwardings/) {
splice @cfgarr, $i, 1, "ClearAllForwardings yes";
next;
}
}
#***************************************************************************
# Write out resulting sftp client configuration file for curl's tests
#
$error = dump_array($sftpconfig, @cfgarr);
if($error) {
logmsg $error;
exit 1;
}
@cfgarr = ();
#***************************************************************************
# Generate client sftp commands batch file for sftp server verification
#
logmsg 'generating sftp client commands file...' if($verbose);
push @cfgarr, 'pwd';
push @cfgarr, 'quit';
$error = dump_array($sftpcmds, @cfgarr);
if($error) {
logmsg $error;
exit 1;
}
@cfgarr = ();
#***************************************************************************
# Prepare command line of ssh server daemon
#
my $cmd = "\"$sshd\" -e -D -f $sshdconfig > $sshdlog 2>&1";
logmsg "SCP/SFTP server listening on port $port" if($verbose);
logmsg "RUN: $cmd" if($verbose);
#***************************************************************************
# Start the ssh server daemon on Windows without forking it
#
if ($sshdid =~ /OpenSSH-Windows/) {
# Fake pidfile for ssh server on Windows.
if(open(OUT, ">$pidfile")) {
print OUT $$ . "\n";
close(OUT);
}
# Flush output.
$| = 1;
# Put an "exec" in front of the command so that the child process
# keeps this child's process ID by being tied to the spawned shell.
exec("exec $cmd") || die "Can't exec() $cmd: $!";
# exec() will create a new process, but ties the existence of the
# new process to the parent waiting perl.exe and sh.exe processes.
# exec() should never return back here to this process. We protect
# ourselves by calling die() just in case something goes really bad.
die "error: exec() has returned";
}
#***************************************************************************
# Start the ssh server daemon without forking it
#
my $rc = system($cmd);
if($rc == -1) {
logmsg "\"$sshd\" failed with: $!";
}
elsif($rc & 127) {
logmsg sprintf("\"$sshd\" died with signal %d, and %s coredump",
($rc & 127), ($rc & 128)?'a':'no');
}
elsif($verbose && ($rc >> 8)) {
logmsg sprintf("\"$sshd\" exited with %d", $rc >> 8);
}
#***************************************************************************
# Clean up once the server has stopped
#
unlink($hstprvkeyf, $hstpubkeyf, $hstpubmd5f, $hstpubsha256f,
$cliprvkeyf, $clipubkeyf, $knownhosts,
$sshdconfig, $sshconfig, $sftpconfig);
exit 0;
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/secureserver.pl | #!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
#***************************************************************************
# This is the HTTPS, FTPS, POP3S, IMAPS, SMTPS, server used for curl test
# harness. Actually just a layer that runs stunnel properly using the
# non-secure test harness servers.
BEGIN {
push(@INC, $ENV{'srcdir'}) if(defined $ENV{'srcdir'});
push(@INC, ".");
}
use strict;
use warnings;
use Cwd;
use Cwd 'abs_path';
use serverhelp qw(
server_pidfilename
server_logfilename
);
use pathhelp;
my $stunnel = "stunnel";
my $verbose=0; # set to 1 for debugging
my $accept_port = 8991; # just our default, weird enough
my $target_port = 8999; # default test http-server port
my $stuncert;
my $ver_major;
my $ver_minor;
my $fips_support;
my $stunnel_version;
my $tstunnel_windows;
my $socketopt;
my $cmd;
my $pidfile; # stunnel pid file
my $logfile; # stunnel log file
my $loglevel = 5; # stunnel log level
my $ipvnum = 4; # default IP version of stunneled server
my $idnum = 1; # default stunneled server instance number
my $proto = 'https'; # default secure server protocol
my $conffile; # stunnel configuration file
my $capath; # certificate chain PEM folder
my $certfile; # certificate chain PEM file
#***************************************************************************
# stunnel requires full path specification for several files.
#
my $path = getcwd();
my $srcdir = $path;
my $logdir = $path .'/log';
#***************************************************************************
# Signal handler to remove our stunnel 4.00 and newer configuration file.
#
sub exit_signal_handler {
my $signame = shift;
local $!; # preserve errno
local $?; # preserve exit status
unlink($conffile) if($conffile && (-f $conffile));
exit;
}
#***************************************************************************
# Process command line options
#
while(@ARGV) {
if($ARGV[0] eq '--verbose') {
$verbose = 1;
}
elsif($ARGV[0] eq '--proto') {
if($ARGV[1]) {
$proto = $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--accept') {
if($ARGV[1]) {
if($ARGV[1] =~ /^(\d+)$/) {
$accept_port = $1;
shift @ARGV;
}
}
}
elsif($ARGV[0] eq '--connect') {
if($ARGV[1]) {
if($ARGV[1] =~ /^(\d+)$/) {
$target_port = $1;
shift @ARGV;
}
}
}
elsif($ARGV[0] eq '--stunnel') {
if($ARGV[1]) {
if($ARGV[1] =~ /^([\w\/]+)$/) {
$stunnel = $ARGV[1];
}
else {
$stunnel = "\"". $ARGV[1] ."\"";
}
shift @ARGV;
}
}
elsif($ARGV[0] eq '--srcdir') {
if($ARGV[1]) {
$srcdir = $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--certfile') {
if($ARGV[1]) {
$stuncert = $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--id') {
if($ARGV[1]) {
if($ARGV[1] =~ /^(\d+)$/) {
$idnum = $1 if($1 > 0);
shift @ARGV;
}
}
}
elsif($ARGV[0] eq '--ipv4') {
$ipvnum = 4;
}
elsif($ARGV[0] eq '--ipv6') {
$ipvnum = 6;
}
elsif($ARGV[0] eq '--pidfile') {
if($ARGV[1]) {
$pidfile = "$path/". $ARGV[1];
shift @ARGV;
}
}
elsif($ARGV[0] eq '--logfile') {
if($ARGV[1]) {
$logfile = "$path/". $ARGV[1];
shift @ARGV;
}
}
else {
print STDERR "\nWarning: secureserver.pl unknown parameter: $ARGV[0]\n";
}
shift @ARGV;
}
#***************************************************************************
# Initialize command line option dependent variables
#
if(!$pidfile) {
$pidfile = "$path/". server_pidfilename($proto, $ipvnum, $idnum);
}
if(!$logfile) {
$logfile = server_logfilename($logdir, $proto, $ipvnum, $idnum);
}
$conffile = "$path/${proto}_stunnel.conf";
$capath = abs_path($path);
$certfile = "$srcdir/". ($stuncert?"certs/$stuncert":"stunnel.pem");
$certfile = abs_path($certfile);
my $ssltext = uc($proto) ." SSL/TLS:";
#***************************************************************************
# Find out version info for the given stunnel binary
#
foreach my $veropt (('-version', '-V')) {
foreach my $verstr (qx($stunnel $veropt 2>&1)) {
if($verstr =~ /^stunnel (\d+)\.(\d+) on /) {
$ver_major = $1;
$ver_minor = $2;
}
elsif($verstr =~ /^sslVersion.*fips *= *yes/) {
# the fips option causes an error if stunnel doesn't support it
$fips_support = 1;
last
}
}
last if($ver_major);
}
if((!$ver_major) || (!$ver_minor)) {
if(-x "$stunnel" && ! -d "$stunnel") {
print "$ssltext Unknown stunnel version\n";
}
else {
print "$ssltext No stunnel\n";
}
exit 1;
}
$stunnel_version = (100*$ver_major) + $ver_minor;
#***************************************************************************
# Verify minimum stunnel required version
#
if($stunnel_version < 310) {
print "$ssltext Unsupported stunnel version $ver_major.$ver_minor\n";
exit 1;
}
#***************************************************************************
# Find out if we are running on Windows using the tstunnel binary
#
if($stunnel =~ /tstunnel(\.exe)?"?$/) {
$tstunnel_windows = 1;
# convert Cygwin/MinGW paths to Win32 format
$capath = pathhelp::sys_native_abs_path($capath);
$certfile = pathhelp::sys_native_abs_path($certfile);
}
#***************************************************************************
# Build command to execute for stunnel 3.X versions
#
if($stunnel_version < 400) {
if($stunnel_version >= 319) {
$socketopt = "-O a:SO_REUSEADDR=1";
}
$cmd = "$stunnel -p $certfile -P $pidfile ";
$cmd .= "-d $accept_port -r $target_port -f -D $loglevel ";
$cmd .= ($socketopt) ? "$socketopt " : "";
$cmd .= ">$logfile 2>&1";
if($verbose) {
print uc($proto) ." server (stunnel $ver_major.$ver_minor)\n";
print "cmd: $cmd\n";
print "pem cert file: $certfile\n";
print "pid file: $pidfile\n";
print "log file: $logfile\n";
print "log level: $loglevel\n";
print "listen on port: $accept_port\n";
print "connect to port: $target_port\n";
}
}
#***************************************************************************
# Build command to execute for stunnel 4.00 and newer
#
if($stunnel_version >= 400) {
$socketopt = "a:SO_REUSEADDR=1";
if(($stunnel_version >= 534) && $tstunnel_windows) {
# SO_EXCLUSIVEADDRUSE is on by default on Vista or newer,
# but does not work together with SO_REUSEADDR being on.
$socketopt .= "\nsocket = a:SO_EXCLUSIVEADDRUSE=0";
}
$cmd = "$stunnel $conffile ";
$cmd .= ">$logfile 2>&1";
# setup signal handler
$SIG{INT} = \&exit_signal_handler;
$SIG{TERM} = \&exit_signal_handler;
# stunnel configuration file
if(open(STUNCONF, ">$conffile")) {
print STUNCONF "CApath = $capath\n";
print STUNCONF "cert = $certfile\n";
print STUNCONF "debug = $loglevel\n";
print STUNCONF "socket = $socketopt\n";
if($fips_support) {
# disable fips in case OpenSSL doesn't support it
print STUNCONF "fips = no\n";
}
if(!$tstunnel_windows) {
# do not use Linux-specific options on Windows
print STUNCONF "output = $logfile\n";
print STUNCONF "pid = $pidfile\n";
print STUNCONF "foreground = yes\n";
}
print STUNCONF "\n";
print STUNCONF "[curltest]\n";
print STUNCONF "accept = $accept_port\n";
print STUNCONF "connect = $target_port\n";
if(!close(STUNCONF)) {
print "$ssltext Error closing file $conffile\n";
exit 1;
}
}
else {
print "$ssltext Error writing file $conffile\n";
exit 1;
}
if($verbose) {
print uc($proto) ." server (stunnel $ver_major.$ver_minor)\n";
print "cmd: $cmd\n";
print "CApath = $capath\n";
print "cert = $certfile\n";
print "debug = $loglevel\n";
print "socket = $socketopt\n";
if($fips_support) {
print "fips = no\n";
}
if(!$tstunnel_windows) {
print "pid = $pidfile\n";
print "output = $logfile\n";
print "foreground = yes\n";
}
print "\n";
print "[curltest]\n";
print "accept = $accept_port\n";
print "connect = $target_port\n";
}
}
#***************************************************************************
# Set file permissions on certificate pem file.
#
chmod(0600, $certfile) if(-f $certfile);
print STDERR "RUN: $cmd\n" if($verbose);
#***************************************************************************
# Run tstunnel on Windows.
#
if($tstunnel_windows) {
# Fake pidfile for tstunnel on Windows.
if(open(OUT, ">$pidfile")) {
print OUT $$ . "\n";
close(OUT);
}
# Flush output.
$| = 1;
# Put an "exec" in front of the command so that the child process
# keeps this child's process ID by being tied to the spawned shell.
exec("exec $cmd") || die "Can't exec() $cmd: $!";
# exec() will create a new process, but ties the existence of the
# new process to the parent waiting perl.exe and sh.exe processes.
# exec() should never return back here to this process. We protect
# ourselves by calling die() just in case something goes really bad.
die "error: exec() has returned";
}
#***************************************************************************
# Run stunnel.
#
my $rc = system($cmd);
$rc >>= 8;
unlink($conffile) if($conffile && -f $conffile);
exit $rc;
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/util.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 2017 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
"""Module for extracting test data from the test data folder and other utils"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import logging
import os
import re
log = logging.getLogger(__name__)
REPLY_DATA = re.compile("<reply>[ \t\n\r]*<data[^<]*>(.*?)</data>", re.MULTILINE | re.DOTALL)
class ClosingFileHandler(logging.StreamHandler):
def __init__(self, filename):
super(ClosingFileHandler, self).__init__()
self.filename = os.path.abspath(filename)
self.setStream(None)
def emit(self, record):
with open(self.filename, "a") as fp:
self.setStream(fp)
super(ClosingFileHandler, self).emit(record)
self.setStream(None)
def setStream(self, stream):
setStream = getattr(super(ClosingFileHandler, self), 'setStream', None)
if callable(setStream):
return setStream(stream)
if stream is self.stream:
result = None
else:
result = self.stream
self.acquire()
try:
self.flush()
self.stream = stream
finally:
self.release()
return result
class TestData(object):
def __init__(self, data_folder):
self.data_folder = data_folder
def get_test_data(self, test_number):
# Create the test file name
filename = os.path.join(self.data_folder,
"test{0}".format(test_number))
log.debug("Parsing file %s", filename)
with open(filename, "rb") as f:
contents = f.read().decode("utf-8")
m = REPLY_DATA.search(contents)
if not m:
raise Exception("Couldn't find a <reply><data> section")
# Left-strip the data so we don't get a newline before our data.
return m.group(1).lstrip()
if __name__ == '__main__':
td = TestData("./data")
data = td.get_test_data(1)
print(data)
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/manpage-syntax.pl | #!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 2019 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
#
# Scan man page(s) and detect some simple and yet common formatting mistakes.
#
# Output all deviances to stderr.
use strict;
use warnings;
# get the file name first
my $symbolsinversions=shift @ARGV;
# we may get the dir roots pointed out
my @manpages=@ARGV;
my $errors = 0;
my %optblessed;
my %funcblessed;
my @optorder = (
'NAME',
'SYNOPSIS',
'DESCRIPTION',
#'DEFAULT', # CURLINFO_ has no default
'PROTOCOLS',
'EXAMPLE',
'AVAILABILITY',
'RETURN VALUE',
'SEE ALSO'
);
my @funcorder = (
'NAME',
'SYNOPSIS',
'DESCRIPTION',
'EXAMPLE',
'AVAILABILITY',
'RETURN VALUE',
'SEE ALSO'
);
my %shline; # section => line number
my %symbol;
sub allsymbols {
open(F, "<$symbolsinversions") ||
die "$symbolsinversions: $|";
while(<F>) {
if($_ =~ /^([^ ]*)/) {
$symbol{$1}=$1;
}
}
close(F);
}
sub scanmanpage {
my ($file) = @_;
my $reqex = 0;
my $inex = 0;
my $exsize = 0;
my $shc = 0;
my $optpage = 0; # option or function
my @sh;
open(M, "<$file") || die "no such file: $file";
if($file =~ /[\/\\](CURL|curl_)[^\/\\]*.3/) {
# This is the man page for an libcurl option. It requires an example!
$reqex = 1;
if($1 eq "CURL") {
$optpage = 1;
}
}
my $line = 1;
while(<M>) {
chomp;
if($_ =~ /^.so /) {
# this man page is just a referral
close(M);
return;
}
if($_ =~ /^\.SH EXAMPLE/i) {
$inex = 1;
}
elsif($_ =~ /^\.SH/i) {
$inex = 0;
}
elsif($inex) {
$exsize++;
if($_ =~ /[^\\]\\n/) {
print STDERR "$file:$line '\\n' need to be '\\\\n'!\n";
}
}
if($_ =~ /^\.SH ([^\r\n]*)/i) {
my $n = $1;
# remove enclosing quotes
$n =~ s/\"(.*)\"\z/$1/;
push @sh, $n;
$shline{$n} = $line;
}
if($_ =~ /^\'/) {
print STDERR "$file:$line line starts with single quote!\n";
$errors++;
}
if($_ =~ /\\f([BI])(.*)/) {
my ($format, $rest) = ($1, $2);
if($rest !~ /\\fP/) {
print STDERR "$file:$line missing \\f${format} terminator!\n";
$errors++;
}
}
if($_ =~ /[ \t]+$/) {
print STDERR "$file:$line trailing whitespace\n";
$errors++;
}
if($_ =~ /\\f([BI])([^\\]*)\\fP/) {
my $r = $2;
if($r =~ /^(CURL.*)\(3\)/) {
my $rr = $1;
if(!$symbol{$rr}) {
print STDERR "$file:$line link to non-libcurl option $rr!\n";
$errors++;
}
}
}
$line++;
}
close(M);
if($reqex) {
# only for libcurl options man-pages
my $shcount = scalar(@sh); # before @sh gets shifted
if($exsize < 2) {
print STDERR "$file:$line missing EXAMPLE section\n";
$errors++;
}
if($shcount < 3) {
print STDERR "$file:$line too few man page sections!\n";
$errors++;
return;
}
my $got = "start";
my $i = 0;
my $shused = 1;
my @shorig = @sh;
my @order = $optpage ? @optorder : @funcorder;
my $blessed = $optpage ? \%optblessed : \%funcblessed;
while($got) {
my $finesh;
$got = shift(@sh);
if($got) {
if($$blessed{$got}) {
$i = $$blessed{$got};
$finesh = $got; # a mandatory one
}
}
if($i && defined($finesh)) {
# mandatory section
if($i != $shused) {
printf STDERR "$file:%u Got %s, when %s was expected\n",
$shline{$finesh},
$finesh,
$order[$shused-1];
$errors++;
return;
}
$shused++;
if($i == scalar(@order)) {
# last mandatory one, exit
last;
}
}
}
if($i != scalar(@order)) {
printf STDERR "$file:$line missing mandatory section: %s\n",
$order[$i];
printf STDERR "$file:$line section found at index %u: '%s'\n",
$i, $shorig[$i];
printf STDERR " Found %u used sections\n", $shcount;
$errors++;
}
}
}
allsymbols();
if(!$symbol{'CURLALTSVC_H1'}) {
print STDERR "didn't get the symbols-in-version!\n";
exit;
}
my $ind = 1;
for my $s (@optorder) {
$optblessed{$s} = $ind++
}
$ind = 1;
for my $s (@funcorder) {
$funcblessed{$s} = $ind++
}
for my $m (@manpages) {
scanmanpage($m);
}
print STDERR "ok\n" if(!$errors);
exit $errors;
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/manpage-scan.pl | #!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 2016 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
#
# Scan symbols-in-version (which is verified to be correct by test 1119), then
# verify that each option mention in there that should have its own man page
# actually does.
#
# In addition, make sure that every current option to curl_easy_setopt,
# curl_easy_getinfo and curl_multi_setopt are also mentioned in their
# corresponding main (index) man page.
#
# src/tool_getparam.c lists all options curl can parse
# docs/curl.1 documents all command line options
# src/tool_listhelp.c outputs all options with curl -h
# - make sure they're all in sync
#
# Output all deviances to stderr.
use strict;
use warnings;
# we may get the dir roots pointed out
my $root=$ARGV[0] || ".";
my $buildroot=$ARGV[1] || ".";
my $syms = "$root/docs/libcurl/symbols-in-versions";
my $curlh = "$root/include/curl/curl.h";
my $errors=0;
# the prepopulated alias list is the CURLINFO_* defines that are used for the
# debug function callback and the fact that they use the same prefix as the
# curl_easy_getinfo options was a mistake.
my %alias = (
'CURLINFO_DATA_IN' => 'none',
'CURLINFO_DATA_OUT' => 'none',
'CURLINFO_END' => 'none',
'CURLINFO_HEADER_IN' => 'none',
'CURLINFO_HEADER_OUT' => 'none',
'CURLINFO_LASTONE' => 'none',
'CURLINFO_NONE' => 'none',
'CURLINFO_SSL_DATA_IN' => 'none',
'CURLINFO_SSL_DATA_OUT' => 'none',
'CURLINFO_TEXT' => 'none'
);
sub scanmanpage {
my ($file, @words) = @_;
open(M, "<$file");
my @m;
while(<M>) {
if($_ =~ /^\.IP (.*)/) {
my $w = $1;
# "unquote" minuses
$w =~ s/\\-/-/g;
push @m, $w;
}
}
close(M);
foreach my $m (@words) {
my @g = grep(/$m/, @m);
if(!$g[0]) {
print STDERR "Missing mention of $m in $file\n";
$errors++;
}
}
}
# check for define alises
open(R, "<$curlh") ||
die "no curl.h";
while(<R>) {
if(/^\#define (CURL(OPT|INFO|MOPT)_\w+) (.*)/) {
$alias{$1}=$3;
}
}
close(R);
my @curlopt;
my @curlinfo;
my @curlmopt;
open(R, "<$syms") ||
die "no input file";
while(<R>) {
chomp;
my $l= $_;
if($l =~ /(CURL(OPT|INFO|MOPT)_\w+) *([0-9.]*) *([0-9.-]*) *([0-9.]*)/) {
my ($opt, $type, $add, $dep, $rem) = ($1, $2, $3, $4, $5);
if($alias{$opt}) {
#print "$opt => $alias{$opt}\n";
}
elsif($rem) {
# $opt was removed in $rem
# so don't check for that
}
else {
if($type eq "OPT") {
push @curlopt, $opt,
}
elsif($type eq "INFO") {
push @curlinfo, $opt,
}
elsif($type eq "MOPT") {
push @curlmopt, $opt,
}
if(! -f "$root/docs/libcurl/opts/$opt.3") {
print STDERR "Missing $opt.3\n";
$errors++;
}
}
}
}
close(R);
scanmanpage("$root/docs/libcurl/curl_easy_setopt.3", @curlopt);
scanmanpage("$root/docs/libcurl/curl_easy_getinfo.3", @curlinfo);
scanmanpage("$root/docs/libcurl/curl_multi_setopt.3", @curlmopt);
# using this hash array, we can skip specific options
my %opts = (
# pretend these --no options exists in tool_getparam.c
'--no-alpn' => 1,
'--no-npn' => 1,
'-N, --no-buffer' => 1,
'--no-sessionid' => 1,
'--no-keepalive' => 1,
'--no-progress-meter' => 1,
# pretend these options without -no exist in curl.1 and tool_listhelp.c
'--alpn' => 6,
'--npn' => 6,
'--eprt' => 6,
'--epsv' => 6,
'--keepalive' => 6,
'-N, --buffer' => 6,
'--sessionid' => 6,
'--progress-meter' => 6,
# deprecated options do not need to be in tool_listhelp.c nor curl.1
'--krb4' => 6,
'--ftp-ssl' => 6,
'--ftp-ssl-reqd' => 6,
# for tests and debug only, can remain hidden
'--test-event' => 6,
'--wdebug' => 6,
);
#########################################################################
# parse the curl code that parses the command line arguments!
open(R, "<$root/src/tool_getparam.c") ||
die "no input file";
my $list;
my @getparam; # store all parsed parameters
while(<R>) {
chomp;
my $l= $_;
if(/struct LongShort aliases/) {
$list=1;
}
elsif($list) {
if( /^ \{([^,]*), *([^ ]*)/) {
my ($s, $l)=($1, $2);
my $sh;
my $lo;
my $title;
if($l =~ /\"(.*)\"/) {
# long option
$lo = $1;
$title="--$lo";
}
if($s =~ /\"(.)\"/) {
# a short option
$sh = $1;
$title="-$sh, $title";
}
push @getparam, $title;
$opts{$title} |= 1;
}
}
}
close(R);
#########################################################################
# parse the curl.1 man page, extract all documented command line options
# The man page may or may not be rebuilt, so check both possible locations
open(R, "<$buildroot/docs/curl.1") || open(R, "<$root/docs/curl.1") ||
die "no input file";
my @manpage; # store all parsed parameters
while(<R>) {
chomp;
my $l= $_;
$l =~ s/\\-/-/g;
if($l =~ /^\.IP \"(-[^\"]*)\"/) {
my $str = $1;
my $combo;
if($str =~ /^-(.), --([a-z0-9.-]*)/) {
# figure out the -short, --long combo
$combo = "-$1, --$2";
}
elsif($str =~ /^--([a-z0-9.-]*)/) {
# figure out the --long name
$combo = "--$1";
}
if($combo) {
push @manpage, $combo;
$opts{$combo} |= 2;
}
}
}
close(R);
#########################################################################
# parse the curl code that outputs the curl -h list
open(R, "<$root/src/tool_listhelp.c") ||
die "no input file";
my @toolhelp; # store all parsed parameters
while(<R>) {
chomp;
my $l= $_;
if(/^ \{\" *(.*)/) {
my $str=$1;
my $combo;
if($str =~ /^-(.), --([a-z0-9.-]*)/) {
# figure out the -short, --long combo
$combo = "-$1, --$2";
}
elsif($str =~ /^--([a-z0-9.-]*)/) {
# figure out the --long name
$combo = "--$1";
}
if($combo) {
push @toolhelp, $combo;
$opts{$combo} |= 4;
}
}
}
close(R);
#
# Now we have three arrays with options to cross-reference.
foreach my $o (keys %opts) {
my $where = $opts{$o};
if($where != 7) {
# this is not in all three places
$errors++;
my $exists;
my $missing;
if($where & 1) {
$exists=" tool_getparam.c";
}
else {
$missing=" tool_getparam.c";
}
if($where & 2) {
$exists.= " curl.1";
}
else {
$missing.= " curl.1";
}
if($where & 4) {
$exists .= " tool_listhelp.c";
}
else {
$missing .= " tool_listhelp.c";
}
print STDERR "$o is not in$missing (but in$exists)\n";
}
}
print STDERR "$errors\n";
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl | repos/gpt4all.zig/src/zig-libcurl/curl/tests/convsrctest.pl | #!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
#***************************************************************************
#=======================================================================
# Read a test definition which exercises curl's --libcurl option.
# Generate either compilable source code for a new test tool,
# or a new test definition which runs the tool and expects the
# same output.
# This should verify that the --libcurl code really does perform
# the same actions as the original curl invocation.
#-----------------------------------------------------------------------
# The output of curl's --libcurl option differs in several ways from
# the code needed to integrate with the test tool environment:
# - #include "test.h"
# - no call of curl_global_init & curl_global_cleanup
# - main() function vs. test() function
# - no checking of curl_easy_setopt calls vs. test_setopt wrapper
# - handling of stdout
# - variable names ret & hnd vs. res & curl
# - URL as literal string vs. passed as argument
#=======================================================================
use strict;
require "getpart.pm";
# Boilerplate code for test tool
my $head =
'#include "test.h"
#include "memdebug.h"
int test(char *URL)
{
CURLcode res;
CURL *curl;
';
# Other declarations from --libcurl come here
# e.g. curl_slist
my $init =
'
if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) {
fprintf(stderr, "curl_global_init() failed\n");
return TEST_ERR_MAJOR_BAD;
}
if ((curl = curl_easy_init()) == NULL) {
fprintf(stderr, "curl_easy_init() failed\n");
curl_global_cleanup();
return TEST_ERR_MAJOR_BAD;
}
';
# Option setting, perform and cleanup come here
my $exit =
' curl_global_cleanup();
return (int)res;
}
';
my $myname = leaf($0);
sub usage {die "Usage: $myname -c|-test=num testfile\n";}
sub main {
@ARGV == 2
or usage;
my($opt,$testfile) = @ARGV;
if(loadtest($testfile)) {
die "$myname: $testfile doesn't look like a test case\n";
}
my $comment = sprintf("DO NOT EDIT - generated from %s by %s",
leaf($testfile), $myname);
if($opt eq '-c') {
generate_c($comment);
}
elsif(my($num) = $opt =~ /^-test=(\d+)$/) {
generate_test($comment, $num);
}
else {
usage;
}
}
sub generate_c {
my($comment) = @_;
# Fetch the generated code, which is the output file checked by
# the old test.
my @libcurl = getpart("verify", "file")
or die "$myname: no <verify><file> section found\n";
# Mangle the code into a suitable form for a test tool.
# We want to extract the important parts (declarations,
# URL, setopt calls, cleanup code) from the --libcurl
# boilerplate and insert them into a new boilerplate.
my(@decl,@code);
# First URL passed in as argument, others as global
my @urlvars = ('URL', 'libtest_arg2', 'libtest_arg3');
my($seen_main,$seen_setopt,$seen_return);
foreach (@libcurl) {
# Check state changes first (even though it
# duplicates some matches) so that the other tests
# are in a logical order).
if(/^int main/) {
$seen_main = 1;
}
if($seen_main and /curl_easy_setopt/) {
# Don't match 'curl_easy_setopt' in comment!
$seen_setopt = 1;
}
if(/^\s*return/) {
$seen_return = 1;
}
# Now filter the code according to purpose
if(! $seen_main) {
next;
}
elsif(! $seen_setopt) {
if(/^\s*(int main|\{|CURLcode |CURL |hnd = curl_easy_init)/) {
# Initialisations handled by boilerplate
next;
}
else {
push @decl, $_;
}
}
elsif(! $seen_return) {
if(/CURLOPT_URL/) {
# URL is passed in as argument or by global
my $var = shift @urlvars;
s/\"[^\"]*\"/$var/;
}
s/\bhnd\b/curl/;
# Convert to macro wrapper
s/curl_easy_setopt/test_setopt/;
if(/curl_easy_perform/) {
s/\bret\b/res/;
push @code, $_;
push @code, "test_cleanup:\n";
}
else {
push @code, $_;
}
}
}
print ("/* $comment */\n",
$head,
@decl,
$init,
@code,
$exit);
}
# Read the original test data file and transform it
# - add a "DO NOT EDIT comment"
# - replace CURLOPT_URL string with URL variable
# - remove <verify><file> section (was the --libcurl output)
# - insert a <client><tool> section with our new C program name
# - replace <client><command> section with the URL
sub generate_test {
my($comment,$newnumber) = @_;
my @libcurl = getpart("verify", "file")
or die "$myname: no <verify><file> section found\n";
# Scan the --libcurl code to find the URL used.
my $url;
foreach (@libcurl) {
if(my($u) = /CURLOPT_URL, \"([^\"]*)\"/) {
$url = $u;
}
}
die "$myname: CURLOPT_URL not found\n"
unless defined $url;
# Traverse the pseudo-XML transforming as required
my @new;
my(@path,$path,$skip);
foreach (getall()) {
if(my($end) = /\s*<(\/?)testcase>/) {
push @new, $_;
push @new, "# $comment\n"
unless $end;
}
elsif(my($tag) = /^\s*<(\w+)/) {
push @path, $tag;
$path = join '/', @path;
if($path eq 'verify/file') {
$skip = 1;
}
push @new, $_
unless $skip;
if($path eq 'client') {
push @new, ("<tool>\n",
"lib$newnumber\n",
"</tool>\n");
}
elsif($path eq 'client/command') {
push @new, sh_quote($url)."\n";
}
}
elsif(my($etag) = /^\s*<\/(\w+)/) {
my $tag = pop @path;
die "$myname: mismatched </$etag>\n"
unless $tag eq $etag;
push @new, $_
unless $skip;
$skip --
if $path eq 'verify/file';
$path = join '/', @path;
}
else {
if($path eq 'client/command') {
# Replaced above
}
else {
push @new, $_
unless $skip;
}
}
}
print @new;
}
sub leaf {
# Works for POSIX filenames
(my $path = shift) =~ s!.*/!!;
return $path;
}
sub sh_quote {
my $word = shift;
$word =~ s/[\$\"\'\\]/\\$&/g;
return '"' . $word . '"';
}
main;
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/fuzz/download_fuzzer.sh | #!/bin/bash
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
# If any commands fail, fail the script immediately.
set -ex
# Clone the curl-fuzzer repository to the specified directory.
git clone --depth=1 https://github.com/curl/curl-fuzzer "$1"
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/data/CMakeLists.txt | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
# Loads 'TESTCASES' from for the 'make show' target in runtests.pl
transform_makefile_inc("Makefile.inc" "${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake")
include("${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake")
# Prints all available test cases. Do not quote TESTCASES, it must be displayed
# as a space-separated string rather than comma-separated (a list in CMake).
add_custom_target(show COMMAND echo ${TESTCASES})
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/data/Makefile.inc | #***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
# this list is in numerical order
TESTCASES = test1 test2 test3 test4 test5 test6 test7 test8 test9 \
test10 test11 test12 test13 test14 test15 test16 test17 test18 test19 \
test20 test21 test22 test23 test24 test25 test26 test27 test28 test29 \
test30 test31 test32 test33 test34 test35 test36 test37 test38 test39 \
test40 test41 test42 test43 test44 test45 test46 test47 test48 test49 \
test50 test51 test52 test53 test54 test55 test56 test57 test58 test59 \
test60 test61 test62 test63 test64 test65 test66 test67 test68 test69 \
test70 test71 test72 test73 test74 test75 test76 test77 test78 test79 \
test80 test81 test82 test83 test84 test85 test86 test87 test88 test89 \
test90 test91 test92 test93 test94 test95 test96 test97 test98 test99 \
test100 test101 test102 test103 test104 test105 test106 test107 test108 \
test109 test110 test111 test112 test113 test114 test115 test116 test117 \
test118 test119 test120 test121 test122 test123 test124 test125 test126 \
test127 test128 test129 test130 test131 test132 test133 test134 test135 \
test136 test137 test138 test139 test140 test141 test142 test143 test144 \
test145 test146 test147 test148 test149 test150 test151 test152 test153 \
test154 test155 test156 test157 test158 test159 test160 test161 test162 \
test163 test164 test165 test166 test167 test168 test169 test170 test171 \
test172 test173 test174 test175 test176 test177 test178 test179 test180 \
test181 test182 test183 test184 test185 test186 test187 test188 test189 \
test190 test191 test192 test193 test194 test195 test196 test197 test198 \
test199 test200 test201 test202 test203 test204 test205 test206 test207 \
test208 test209 test210 test211 test212 test213 test214 test215 test216 \
test217 test218 test219 test220 test221 test222 test223 test224 test225 \
test226 test227 test228 test229 test230 test231 test232 test233 test234 \
test235 test236 test237 test238 test239 test240 test241 test242 test243 \
test244 test245 test246 test247 test248 test249 test250 test251 test252 \
test253 test254 test255 test256 test257 test258 test259 test260 test261 \
test262 test263 test264 test265 test266 test267 test268 test269 test270 \
test271 test272 test273 test274 test275 test276 test277 test278 test279 \
test280 test281 test282 test283 test284 test285 test286 test287 test288 \
test289 test290 test291 test292 test293 test294 test295 test296 test297 \
test298 test299 test300 test301 test302 test303 test304 test305 test306 \
test307 test308 test309 test310 test311 test312 test313 test314 test315 \
test316 test317 test318 test319 test320 test321 test322 test323 test324 \
test325 test326 test327 test328 test329 test330 test331 test332 test333 \
test334 test335 test336 test337 test338 test339 test340 test341 test342 \
test343 test344 test345 test346 test347 test348 test349 test350 test351 \
test352 test353 test354 test355 test356 test357 test358 test359 test360 \
test361 test362 test363 test364 test365 test366 test367 test368 test369 \
test370 \
\
test392 test393 test394 test395 test396 test397 \
\
test400 test401 test402 test403 test404 test405 test406 test407 test408 \
test409 test410 \
\
test430 test431 test432 test433 test434 test435 \
\
test490 test491 test492 test493 test494 \
\
test500 test501 test502 test503 test504 test505 test506 test507 test508 \
test509 test510 test511 test512 test513 test514 test515 test516 test517 \
test518 test519 test520 test521 test522 test523 test524 test525 test526 \
test527 test528 test529 test531 test532 test533 test534 test535 \
test537 test538 test539 test540 test541 test542 test543 test544 \
test545 test546 test547 test548 test549 test550 test551 test552 test553 \
test554 test555 test556 test557 test558 test559 test560 test561 test562 \
test563 test564 test565 test566 test567 test568 test569 test570 test571 \
test572 test573 test574 test575 test576 test577 test578 test579 test580 \
test581 test582 test583 test584 test585 test586 test587 test588 test589 \
test590 test591 test592 test593 test594 test595 test596 test597 test598 \
test599 test600 test601 test602 test603 test604 test605 test606 test607 \
test608 test609 test610 test611 test612 test613 test614 test615 test616 \
test617 test618 test619 test620 test621 test622 test623 test624 test625 \
test626 test627 test628 test629 test630 test631 test632 test633 test634 \
test635 test636 test637 test638 test639 test640 test641 test642 \
test643 test645 test646 test647 test648 test649 test650 test651 \
test652 test653 test654 test655 test656 test658 test659 test660 test661 \
test662 test663 test664 test665 test666 test667 test668 test669 \
test670 test671 test672 test673 test674 test675 test676 test677 test678 \
\
test700 test701 test702 test703 test704 test705 test706 test707 test708 \
test709 test710 test711 test712 test713 test714 test715 test716 test717 \
test718 \
\
test800 test801 test802 test803 test804 test805 test806 test807 test808 \
test809 test810 test811 test812 test813 test814 test815 test816 test817 \
test818 test819 test820 test821 test822 test823 test824 test825 test826 \
test827 test828 test829 test830 test831 test832 test833 test834 test835 \
test836 test837 test838 test839 test840 test841 test842 test843 test844 \
test845 test846 test847 test848 test849 test850 test851 test852 test853 \
test854 test855 test856 test857 test858 test859 test860 test861 test862 \
test863 test864 test865 test866 test867 test868 test869 test870 test871 \
test872 test873 test874 test875 test876 test877 test878 test879 test880 \
test881 test882 test883 test884 test885 test886 test887 test888 test889 \
test890 test891 test892 test893 test894 test895 test896 test897 \
\
test900 test901 test902 test903 test904 test905 test906 test907 test908 \
test909 test910 test911 test912 test913 test914 test915 test916 test917 \
test918 test919 test920 test921 test922 test923 test924 test925 test926 \
test927 test928 test929 test930 test931 test932 test933 test934 test935 \
test936 test937 test938 test939 test940 test941 test942 test943 test944 \
test945 test946 test947 test948 test949 test950 test951 test952 test953 \
test954 test955 test956 test957 test958 test959 test960 test961 test962 \
test963 test964 test965 test966 test967 test968 test969 test970 test971 \
test972 \
\
test980 test981 test982 test983 test984 test985 test986 \
\
test1000 test1001 test1002 test1003 test1004 test1005 test1006 test1007 \
test1008 test1009 test1010 test1011 test1012 test1013 test1014 test1015 \
test1016 test1017 test1018 test1019 test1020 test1021 test1022 test1023 \
test1024 test1025 test1026 test1027 test1028 test1029 test1030 test1031 \
test1032 test1033 test1034 test1035 test1036 test1037 test1038 test1039 \
test1040 test1041 test1042 test1043 test1044 test1045 test1046 test1047 \
test1048 test1049 test1050 test1051 test1052 test1053 test1054 test1055 \
test1056 test1057 test1058 test1059 test1060 test1061 test1062 test1063 \
test1064 test1065 test1066 test1067 test1068 test1069 test1070 test1071 \
test1072 test1073 test1074 test1075 test1076 test1077 test1078 test1079 \
test1080 test1081 test1082 test1083 test1084 test1085 test1086 test1087 \
test1088 test1089 test1090 test1091 test1092 test1093 test1094 test1095 \
test1096 test1097 test1098 test1099 test1100 test1101 test1102 test1103 \
test1104 test1105 test1106 test1107 test1108 test1109 test1110 test1111 \
test1112 test1113 test1114 test1115 test1116 test1117 test1118 test1119 \
test1120 test1121 test1122 test1123 test1124 test1125 test1126 test1127 \
test1128 test1129 test1130 test1131 test1132 test1133 test1134 test1135 \
test1136 test1137 test1138 test1139 test1140 test1141 test1142 test1143 \
test1144 test1145 test1146 test1147 test1148 test1149 test1150 test1151 \
test1152 test1153 test1154 test1155 test1156 test1157 test1158 test1159 \
test1160 test1161 test1162 test1163 test1164 test1165 test1166 test1167 \
test1168 test1169 test1170 test1171 test1172 test1173 test1174 test1175 \
test1176 test1177 test1178 test1179 test1180 test1181 test1182 test1183 \
test1184 test1185 \
test1188 \
\
test1190 test1191 test1192 test1193 test1194 test1195 test1196 test1197 \
test1198 test1199 \
test1200 test1201 test1202 test1203 test1204 test1205 test1206 test1207 \
test1208 test1209 test1210 test1211 test1212 test1213 test1214 test1215 \
test1216 test1217 test1218 test1219 test1220 test1223 \
test1224 test1225 test1226 test1227 test1228 test1229 test1230 test1231 \
test1232 test1233 test1234 test1235 test1236 test1237 test1238 test1239 \
test1240 test1241 test1242 test1243 test1244 test1245 test1246 test1247 \
test1248 test1249 test1250 test1251 test1252 test1253 test1254 test1255 \
test1256 test1257 test1258 test1259 test1260 test1261 test1262 test1263 \
test1264 test1265 test1266 test1267 test1268 test1269 test1270 test1271 \
test1272 test1273 \
\
test1280 test1281 test1282 test1283 test1284 test1285 test1286 test1287 \
test1288 test1289 test1290 test1291 test1292 test1293 test1294 test1295 \
test1296 test1297 test1298 test1299 test1300 test1301 test1302 test1303 \
test1304 test1305 test1306 test1307 test1308 test1309 test1310 test1311 \
test1312 test1313 test1314 test1315 test1316 test1317 test1318 test1319 \
test1320 test1321 test1322 test1323 test1324 test1325 test1326 test1327 \
test1328 test1329 test1330 test1331 test1332 test1333 test1334 test1335 \
test1336 test1337 test1338 test1339 test1340 test1341 test1342 test1343 \
test1344 test1345 test1346 test1347 test1348 test1349 test1350 test1351 \
test1352 test1353 test1354 test1355 test1356 test1357 test1358 test1359 \
test1360 test1361 test1362 test1363 test1364 test1365 test1366 test1367 \
test1368 test1369 test1370 test1371 test1372 test1373 test1374 test1375 \
test1376 test1377 test1378 test1379 test1380 test1381 test1382 test1383 \
test1384 test1385 test1386 test1387 test1388 test1389 test1390 test1391 \
test1392 test1393 test1394 test1395 test1396 test1397 test1398 test1399 \
test1400 test1401 test1402 test1403 test1404 test1405 test1406 test1407 \
test1408 test1409 test1410 test1411 test1412 test1413 test1414 test1415 \
test1416 test1417 test1418 test1419 test1420 test1421 test1422 test1423 \
test1424 test1425 test1426 test1427 test1428 test1429 test1430 test1431 \
test1432 test1433 test1434 test1435 test1436 test1437 test1438 test1439 \
test1440 test1441 test1442 test1443 test1444 test1445 test1446 test1447 \
test1448 test1449 test1450 test1451 test1452 test1453 test1454 test1455 \
test1456 test1457 test1458 test1459 test1460 test1461 test1462 test1463 \
test1464 test1465 test1466 \
\
test1500 test1501 test1502 test1503 test1504 test1505 test1506 test1507 \
test1508 test1509 test1510 test1511 test1512 test1513 test1514 test1515 \
test1516 test1517 test1518 test1519 test1520 test1521 test1522 test1523 \
test1524 test1525 test1526 test1527 test1528 test1529 test1530 test1531 \
test1532 test1533 test1534 test1535 test1536 test1537 test1538 test1539 \
test1540 test1542 \
\
test1550 test1551 test1552 test1553 test1554 test1555 test1556 test1557 \
test1558 test1559 test1560 test1561 test1562 test1563 test1564 test1565 \
test1566 test1567 test1568 test1569 test1570 \
\
test1590 test1591 test1592 test1593 test1594 test1595 test1596 \
\
test1600 test1601 test1602 test1603 test1604 test1605 test1606 test1607 \
test1608 test1609 test1610 test1611 test1612 test1613 \
\
test1620 test1621 \
\
test1630 test1631 test1632 test1633 test1634 \
\
test1650 test1651 test1652 test1653 test1654 test1655 \
test1660 test1661 \
\
test1700 test1701 test1702 test1703 \
\
test1800 test1801 \
\
test1904 test1905 test1906 test1907 \
test1908 test1909 test1910 test1911 test1912 test1913 test1914 test1915 \
test1916 test1917 test1918 \
\
test1933 test1934 test1935 test1936 test1937 test1938 \
\
test2000 test2001 test2002 test2003 test2004 \
\
test2023 \
test2024 test2025 test2026 test2027 test2028 test2029 test2030 test2031 \
test2032 test2033 test2034 test2035 test2036 test2037 test2038 test2039 \
test2040 test2041 test2042 test2043 test2044 test2045 test2046 test2047 \
test2048 test2049 test2050 test2051 test2052 test2053 test2054 test2055 \
test2056 test2057 test2058 test2059 test2060 test2061 test2062 test2063 \
test2064 test2065 test2066 test2067 test2068 test2069 test2070 test2071 \
test2072 test2073 test2074 test2075 test2076 test2077 test2078 test2079 \
test2080 test2081 test2082 test2083 test2084 test2085 test2086 test2087 \
\
test2100 \
\
test2200 test2201 test2202 test2203 test2204 test2205 \
\
test3000 test3001 test3002 test3003 test3004 test3005 test3006 test3007 \
test3008 test3009 test3010 test3011 test3012 test3013 test3014 test3015 \
test3016 test3017 test3018 test3019 test3020 test3021 test3022 test3023 \
test3024
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/lib590.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "test.h"
/*
Based on a bug report recipe by Rene Bernhardt in
https://curl.se/mail/lib-2011-10/0323.html
It is reproducible by the following steps:
- Use a proxy that offers NTLM and Negotiate ( CURLOPT_PROXY and
CURLOPT_PROXYPORT)
- Tell libcurl NOT to use Negotiate CURL_EASY_SETOPT(CURLOPT_PROXYAUTH,
CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_NTLM)
- Start the request
*/
#include "memdebug.h"
int test(char *URL)
{
CURLcode res;
CURL *curl;
if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) {
fprintf(stderr, "curl_global_init() failed\n");
return TEST_ERR_MAJOR_BAD;
}
curl = curl_easy_init();
if(!curl) {
fprintf(stderr, "curl_easy_init() failed\n");
curl_global_cleanup();
return TEST_ERR_MAJOR_BAD;
}
test_setopt(curl, CURLOPT_URL, URL);
test_setopt(curl, CURLOPT_HEADER, 1L);
test_setopt(curl, CURLOPT_PROXYAUTH,
(long) (CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_NTLM));
test_setopt(curl, CURLOPT_PROXY, libtest_arg2); /* set in first.c */
test_setopt(curl, CURLOPT_PROXYUSERPWD, "me:password");
res = curl_easy_perform(curl);
test_cleanup:
curl_easy_cleanup(curl);
curl_global_cleanup();
return (int)res;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/lib533.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* used for test case 533, 534 and 535 */
#include "test.h"
#include <fcntl.h>
#include "testutil.h"
#include "warnless.h"
#include "memdebug.h"
#define TEST_HANG_TIMEOUT 60 * 1000
int test(char *URL)
{
int res = 0;
CURL *curl = NULL;
int running;
CURLM *m = NULL;
int current = 0;
start_test_timing();
global_init(CURL_GLOBAL_ALL);
easy_init(curl);
easy_setopt(curl, CURLOPT_URL, URL);
easy_setopt(curl, CURLOPT_VERBOSE, 1L);
easy_setopt(curl, CURLOPT_FAILONERROR, 1L);
multi_init(m);
multi_add_handle(m, curl);
fprintf(stderr, "Start at URL 0\n");
for(;;) {
struct timeval interval;
fd_set rd, wr, exc;
int maxfd = -99;
interval.tv_sec = 1;
interval.tv_usec = 0;
multi_perform(m, &running);
abort_on_test_timeout();
if(!running) {
if(!current++) {
fprintf(stderr, "Advancing to URL 1\n");
/* remove the handle we use */
curl_multi_remove_handle(m, curl);
/* make us re-use the same handle all the time, and try resetting
the handle first too */
curl_easy_reset(curl);
easy_setopt(curl, CURLOPT_URL, libtest_arg2);
easy_setopt(curl, CURLOPT_VERBOSE, 1L);
easy_setopt(curl, CURLOPT_FAILONERROR, 1L);
/* re-add it */
multi_add_handle(m, curl);
}
else
break; /* done */
}
FD_ZERO(&rd);
FD_ZERO(&wr);
FD_ZERO(&exc);
multi_fdset(m, &rd, &wr, &exc, &maxfd);
/* At this point, maxfd is guaranteed to be greater or equal than -1. */
select_test(maxfd + 1, &rd, &wr, &exc, &interval);
abort_on_test_timeout();
}
test_cleanup:
/* undocumented cleanup sequence - type UB */
curl_easy_cleanup(curl);
curl_multi_cleanup(m);
curl_global_cleanup();
return res;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/lib1936.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "test.h"
#include "memdebug.h"
int test(char *URL)
{
CURL *curl;
CURLcode res = TEST_ERR_MAJOR_BAD;
struct curl_slist *list = NULL;
if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) {
fprintf(stderr, "curl_global_init() failed\n");
return TEST_ERR_MAJOR_BAD;
}
curl = curl_easy_init();
if(!curl) {
fprintf(stderr, "curl_easy_init() failed\n");
curl_global_cleanup();
return TEST_ERR_MAJOR_BAD;
}
test_setopt(curl, CURLOPT_VERBOSE, 1L);
test_setopt(curl, CURLOPT_AWS_SIGV4, "xxx:yyy:rrr:sss");
test_setopt(curl, CURLOPT_USERPWD, "xxx:yyy");
test_setopt(curl, CURLOPT_HEADER, 0L);
test_setopt(curl, CURLOPT_URL, URL);
list = curl_slist_append(list, "Content-Type: application/json");
test_setopt(curl, CURLOPT_HTTPHEADER, list);
res = curl_easy_perform(curl);
test_cleanup:
curl_slist_free_all(list);
curl_easy_cleanup(curl);
curl_global_cleanup();
return res;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/lib516.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "test.h"
#include "memdebug.h"
int test(char *URL)
{
CURL *curl;
CURLcode res = CURLE_OK;
if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) {
fprintf(stderr, "curl_global_init() failed\n");
return TEST_ERR_MAJOR_BAD;
}
curl = curl_easy_init();
if(!curl) {
fprintf(stderr, "curl_easy_init() failed\n");
curl_global_cleanup();
return TEST_ERR_MAJOR_BAD;
}
/* First set the URL that is about to receive our POST. */
test_setopt(curl, CURLOPT_URL, URL);
test_setopt(curl, CURLOPT_HTTPPOST, NULL);
test_setopt(curl, CURLOPT_VERBOSE, 1L); /* show verbose for debug */
test_setopt(curl, CURLOPT_HEADER, 1L); /* include header */
/* Now, we should be making a zero byte POST request */
res = curl_easy_perform(curl);
test_cleanup:
/* always cleanup */
curl_easy_cleanup(curl);
curl_global_cleanup();
return (int)res;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/lib555.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/* This test case is supposed to be identical to 547 except that this uses the
* multi interface and 547 is easy interface.
*
* argv1 = URL
* argv2 = proxy
* argv3 = proxyuser:password
*/
#include "test.h"
#include "testutil.h"
#include "warnless.h"
#include "memdebug.h"
#define TEST_HANG_TIMEOUT 60 * 1000
static const char uploadthis[] =
#ifdef CURL_DOES_CONVERSIONS
/* ASCII representation with escape sequences for non-ASCII platforms */
"\x74\x68\x69\x73\x20\x69\x73\x20\x74\x68\x65\x20\x62\x6c\x75\x72"
"\x62\x20\x77\x65\x20\x77\x61\x6e\x74\x20\x74\x6f\x20\x75\x70\x6c"
"\x6f\x61\x64\x0a";
#else
"this is the blurb we want to upload\n";
#endif
static size_t readcallback(char *ptr,
size_t size,
size_t nmemb,
void *clientp)
{
int *counter = (int *)clientp;
if(*counter) {
/* only do this once and then require a clearing of this */
fprintf(stderr, "READ ALREADY DONE!\n");
return 0;
}
(*counter)++; /* bump */
if(size * nmemb > strlen(uploadthis)) {
fprintf(stderr, "READ!\n");
strcpy(ptr, uploadthis);
return strlen(uploadthis);
}
fprintf(stderr, "READ NOT FINE!\n");
return 0;
}
static curlioerr ioctlcallback(CURL *handle,
int cmd,
void *clientp)
{
int *counter = (int *)clientp;
(void)handle; /* unused */
if(cmd == CURLIOCMD_RESTARTREAD) {
fprintf(stderr, "REWIND!\n");
*counter = 0; /* clear counter to make the read callback restart */
}
return CURLIOE_OK;
}
int test(char *URL)
{
int res = 0;
CURL *curl = NULL;
int counter = 0;
CURLM *m = NULL;
int running = 1;
start_test_timing();
global_init(CURL_GLOBAL_ALL);
easy_init(curl);
easy_setopt(curl, CURLOPT_URL, URL);
easy_setopt(curl, CURLOPT_VERBOSE, 1L);
easy_setopt(curl, CURLOPT_HEADER, 1L);
/* read the POST data from a callback */
easy_setopt(curl, CURLOPT_IOCTLFUNCTION, ioctlcallback);
easy_setopt(curl, CURLOPT_IOCTLDATA, &counter);
easy_setopt(curl, CURLOPT_READFUNCTION, readcallback);
easy_setopt(curl, CURLOPT_READDATA, &counter);
/* We CANNOT do the POST fine without setting the size (or choose
chunked)! */
easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(uploadthis));
easy_setopt(curl, CURLOPT_POST, 1L);
easy_setopt(curl, CURLOPT_PROXY, libtest_arg2);
easy_setopt(curl, CURLOPT_PROXYUSERPWD, libtest_arg3);
easy_setopt(curl, CURLOPT_PROXYAUTH,
(long) (CURLAUTH_NTLM | CURLAUTH_DIGEST | CURLAUTH_BASIC) );
multi_init(m);
multi_add_handle(m, curl);
while(running) {
struct timeval timeout;
fd_set fdread, fdwrite, fdexcep;
int maxfd = -99;
timeout.tv_sec = 0;
timeout.tv_usec = 100000L; /* 100 ms */
multi_perform(m, &running);
abort_on_test_timeout();
#ifdef TPF
sleep(1); /* avoid ctl-10 dump */
#endif
if(!running)
break; /* done */
FD_ZERO(&fdread);
FD_ZERO(&fdwrite);
FD_ZERO(&fdexcep);
multi_fdset(m, &fdread, &fdwrite, &fdexcep, &maxfd);
/* At this point, maxfd is guaranteed to be greater or equal than -1. */
select_test(maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout);
abort_on_test_timeout();
}
test_cleanup:
/* proper cleanup sequence - type PA */
curl_multi_remove_handle(m, curl);
curl_multi_cleanup(m);
curl_easy_cleanup(curl);
curl_global_cleanup();
return res;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/lib1514.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/*
* Make sure libcurl does not send a `Content-Length: -1` header when HTTP POST
* size is unknown.
*/
#include "test.h"
#include "memdebug.h"
static char data[]="dummy";
struct WriteThis {
char *readptr;
size_t sizeleft;
};
static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *userp)
{
struct WriteThis *pooh = (struct WriteThis *)userp;
if(size*nmemb < 1)
return 0;
if(pooh->sizeleft) {
*ptr = pooh->readptr[0]; /* copy one single byte */
pooh->readptr++; /* advance pointer */
pooh->sizeleft--; /* less data left */
return 1; /* we return 1 byte at a time! */
}
return 0; /* no more data left to deliver */
}
int test(char *URL)
{
CURL *curl;
CURLcode result = CURLE_OK;
int res = 0;
struct WriteThis pooh = { data, sizeof(data)-1 };
global_init(CURL_GLOBAL_ALL);
easy_init(curl);
easy_setopt(curl, CURLOPT_URL, URL);
easy_setopt(curl, CURLOPT_POST, 1L);
/* Purposely omit to set CURLOPT_POSTFIELDSIZE */
easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
easy_setopt(curl, CURLOPT_READDATA, &pooh);
#ifdef LIB1539
/* speak HTTP 1.0 - no chunked! */
easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
#endif
result = curl_easy_perform(curl);
test_cleanup:
curl_easy_cleanup(curl);
curl_global_cleanup();
return (int)result;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/lib1557.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "test.h"
#include "testutil.h"
#include "warnless.h"
#include "memdebug.h"
int test(char *URL)
{
CURLM *curlm = NULL;
CURL *curl1 = NULL;
CURL *curl2 = NULL;
int running_handles = 0;
int res = 0;
global_init(CURL_GLOBAL_ALL);
multi_init(curlm);
multi_setopt(curlm, CURLMOPT_MAX_HOST_CONNECTIONS, 1);
easy_init(curl1);
easy_setopt(curl1, CURLOPT_URL, URL);
multi_add_handle(curlm, curl1);
easy_init(curl2);
easy_setopt(curl2, CURLOPT_URL, URL);
multi_add_handle(curlm, curl2);
multi_perform(curlm, &running_handles);
multi_remove_handle(curlm, curl2);
/* If curl2 is still in the connect-pending list, this will crash */
multi_remove_handle(curlm, curl1);
test_cleanup:
curl_easy_cleanup(curl1);
curl_easy_cleanup(curl2);
curl_multi_cleanup(curlm);
curl_global_cleanup();
return res;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/lib539.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "test.h"
#include "memdebug.h"
int test(char *URL)
{
CURLcode res;
CURL *curl;
char *newURL = NULL;
struct curl_slist *slist = NULL;
if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) {
fprintf(stderr, "curl_global_init() failed\n");
return TEST_ERR_MAJOR_BAD;
}
curl = curl_easy_init();
if(!curl) {
fprintf(stderr, "curl_easy_init() failed\n");
curl_global_cleanup();
return TEST_ERR_MAJOR_BAD;
}
/*
* Begin with curl set to use a single CWD to the URL's directory.
*/
test_setopt(curl, CURLOPT_URL, URL);
test_setopt(curl, CURLOPT_VERBOSE, 1L);
test_setopt(curl, CURLOPT_FTP_FILEMETHOD, (long) CURLFTPMETHOD_SINGLECWD);
res = curl_easy_perform(curl);
/*
* Change the FTP_FILEMETHOD option to use full paths rather than a CWD
* command. Alter the URL's path a bit, appending a "./". Use an innocuous
* QUOTE command, after which curl will CWD to ftp_conn->entrypath and then
* (on the next call to ftp_statemach_act) find a non-zero ftpconn->dirdepth
* even though no directories are stored in the ftpconn->dirs array (after a
* call to freedirs).
*/
newURL = aprintf("%s./", URL);
if(!newURL) {
curl_easy_cleanup(curl);
curl_global_cleanup();
return TEST_ERR_MAJOR_BAD;
}
slist = curl_slist_append(NULL, "SYST");
if(!slist) {
free(newURL);
curl_easy_cleanup(curl);
curl_global_cleanup();
return TEST_ERR_MAJOR_BAD;
}
test_setopt(curl, CURLOPT_URL, newURL);
test_setopt(curl, CURLOPT_FTP_FILEMETHOD, (long) CURLFTPMETHOD_NOCWD);
test_setopt(curl, CURLOPT_QUOTE, slist);
res = curl_easy_perform(curl);
test_cleanup:
curl_slist_free_all(slist);
free(newURL);
curl_easy_cleanup(curl);
curl_global_cleanup();
return (int)res;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/notexists.pl | #!/usr/bin/env perl
#***************************************************************************
# _ _ ____ _
# Project ___| | | | _ \| |
# / __| | | | |_) | |
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
# Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
###########################################################################
# Check that given arguments do not exist on filesystem.
my $code = 0;
if ($#ARGV < 0) {
print "Usage: $0 file1 [fileN]\n";
exit 2;
}
while (@ARGV) {
my $fname = shift @ARGV;
if (-e $fname) {
print "Found '$fname' when not supposed to exist.\n";
$code = 1;
}
}
exit $code;
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/lib1532.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "test.h"
#include "memdebug.h"
/* Test CURLINFO_RESPONSE_CODE */
int test(char *URL)
{
CURL *curl;
long httpcode;
int res = CURLE_OK;
global_init(CURL_GLOBAL_ALL);
easy_init(curl);
easy_setopt(curl, CURLOPT_URL, URL);
res = curl_easy_perform(curl);
if(res) {
fprintf(stderr, "%s:%d curl_easy_perform() failed with code %d (%s)\n",
__FILE__, __LINE__, res, curl_easy_strerror(res));
goto test_cleanup;
}
res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpcode);
if(res) {
fprintf(stderr, "%s:%d curl_easy_getinfo() failed with code %d (%s)\n",
__FILE__, __LINE__, res, curl_easy_strerror(res));
goto test_cleanup;
}
if(httpcode != 200) {
fprintf(stderr, "%s:%d unexpected response code %ld\n",
__FILE__, __LINE__, httpcode);
res = CURLE_HTTP_RETURNED_ERROR;
goto test_cleanup;
}
/* Test for a regression of github bug 1017 (response code does not reset) */
curl_easy_reset(curl);
res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpcode);
if(res) {
fprintf(stderr, "%s:%d curl_easy_getinfo() failed with code %d (%s)\n",
__FILE__, __LINE__, res, curl_easy_strerror(res));
goto test_cleanup;
}
if(httpcode) {
fprintf(stderr, "%s:%d curl_easy_reset failed to zero the response code\n"
"possible regression of github bug 1017\n", __FILE__, __LINE__);
res = CURLE_HTTP_RETURNED_ERROR;
goto test_cleanup;
}
test_cleanup:
curl_easy_cleanup(curl);
curl_global_cleanup();
return res;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/lib1569.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "test.h"
#include "testtrace.h"
#include "memdebug.h"
int test(char *URL)
{
CURLcode ret;
CURL *hnd;
curl_global_init(CURL_GLOBAL_ALL);
hnd = curl_easy_init();
curl_easy_setopt(hnd, CURLOPT_URL, URL);
curl_easy_setopt(hnd, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(hnd, CURLOPT_HEADER, 1L);
ret = curl_easy_perform(hnd);
curl_easy_setopt(hnd, CURLOPT_URL, libtest_arg2);
ret = curl_easy_perform(hnd);
curl_easy_cleanup(hnd);
curl_global_cleanup();
return (int)ret;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/first.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "test.h"
#ifdef HAVE_LOCALE_H
# include <locale.h> /* for setlocale() */
#endif
#ifdef HAVE_IO_H
# include <io.h> /* for setmode() */
#endif
#ifdef HAVE_FCNTL_H
# include <fcntl.h> /* for setmode() */
#endif
#ifdef USE_NSS
#include <nspr.h>
#endif
#ifdef CURLDEBUG
# define MEMDEBUG_NODEFINES
# include "memdebug.h"
#endif
int select_wrapper(int nfds, fd_set *rd, fd_set *wr, fd_set *exc,
struct timeval *tv)
{
if(nfds < 0) {
SET_SOCKERRNO(EINVAL);
return -1;
}
#ifdef USE_WINSOCK
/*
* Winsock select() requires that at least one of the three fd_set
* pointers is not NULL and points to a non-empty fdset. IOW Winsock
* select() can not be used to sleep without a single fd_set.
*/
if(!nfds) {
Sleep((1000*tv->tv_sec) + (DWORD)(((double)tv->tv_usec)/1000.0));
return 0;
}
#endif
return select(nfds, rd, wr, exc, tv);
}
void wait_ms(int ms)
{
struct timeval t;
t.tv_sec = ms/1000;
ms -= (int)t.tv_sec * 1000;
t.tv_usec = ms * 1000;
select_wrapper(0, NULL, NULL, NULL, &t);
}
char *libtest_arg2 = NULL;
char *libtest_arg3 = NULL;
int test_argc;
char **test_argv;
struct timeval tv_test_start; /* for test timing */
#ifdef UNITTESTS
int unitfail; /* for unittests */
#endif
#ifdef CURLDEBUG
static void memory_tracking_init(void)
{
char *env;
/* if CURL_MEMDEBUG is set, this starts memory tracking message logging */
env = curl_getenv("CURL_MEMDEBUG");
if(env) {
/* use the value as file name */
char fname[CURL_MT_LOGFNAME_BUFSIZE];
if(strlen(env) >= CURL_MT_LOGFNAME_BUFSIZE)
env[CURL_MT_LOGFNAME_BUFSIZE-1] = '\0';
strcpy(fname, env);
curl_free(env);
curl_dbg_memdebug(fname);
/* this weird stuff here is to make curl_free() get called before
curl_dbg_memdebug() as otherwise memory tracking will log a free()
without an alloc! */
}
/* if CURL_MEMLIMIT is set, this enables fail-on-alloc-number-N feature */
env = curl_getenv("CURL_MEMLIMIT");
if(env) {
char *endptr;
long num = strtol(env, &endptr, 10);
if((endptr != env) && (endptr == env + strlen(env)) && (num > 0))
curl_dbg_memlimit(num);
curl_free(env);
}
}
#else
# define memory_tracking_init() Curl_nop_stmt
#endif
/* returns a hexdump in a static memory area */
char *hexdump(const unsigned char *buffer, size_t len)
{
static char dump[200 * 3 + 1];
char *p = dump;
size_t i;
if(len > 200)
return NULL;
for(i = 0; i<len; i++, p += 3)
msnprintf(p, 4, "%02x ", buffer[i]);
return dump;
}
int main(int argc, char **argv)
{
char *URL;
int result;
#ifdef O_BINARY
# ifdef __HIGHC__
_setmode(stdout, O_BINARY);
# else
setmode(fileno(stdout), O_BINARY);
# endif
#endif
memory_tracking_init();
/*
* Setup proper locale from environment. This is needed to enable locale-
* specific behavior by the C library in order to test for undesired side
* effects that could cause in libcurl.
*/
#ifdef HAVE_SETLOCALE
setlocale(LC_ALL, "");
#endif
if(argc< 2) {
fprintf(stderr, "Pass URL as argument please\n");
return 1;
}
test_argc = argc;
test_argv = argv;
if(argc>2)
libtest_arg2 = argv[2];
if(argc>3)
libtest_arg3 = argv[3];
URL = argv[1]; /* provide this to the rest */
fprintf(stderr, "URL: %s\n", URL);
result = test(URL);
#ifdef USE_NSS
if(PR_Initialized())
/* prevent valgrind from reporting possibly lost memory (fd cache, ...) */
PR_Cleanup();
#endif
return result;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/lib582.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "test.h"
#include <fcntl.h>
#include "testutil.h"
#include "warnless.h"
#include "memdebug.h"
#define TEST_HANG_TIMEOUT 60 * 1000
struct Sockets
{
curl_socket_t *sockets;
int count; /* number of sockets actually stored in array */
int max_count; /* max number of sockets that fit in allocated array */
};
struct ReadWriteSockets
{
struct Sockets read, write;
};
/**
* Remove a file descriptor from a sockets array.
*/
static void removeFd(struct Sockets *sockets, curl_socket_t fd, int mention)
{
int i;
if(mention)
fprintf(stderr, "Remove socket fd %d\n", (int) fd);
for(i = 0; i < sockets->count; ++i) {
if(sockets->sockets[i] == fd) {
if(i < sockets->count - 1)
memmove(&sockets->sockets[i], &sockets->sockets[i + 1],
sizeof(curl_socket_t) * (sockets->count - (i + 1)));
--sockets->count;
}
}
}
/**
* Add a file descriptor to a sockets array.
*/
static void addFd(struct Sockets *sockets, curl_socket_t fd, const char *what)
{
/**
* To ensure we only have each file descriptor once, we remove it then add
* it again.
*/
fprintf(stderr, "Add socket fd %d for %s\n", (int) fd, what);
removeFd(sockets, fd, 0);
/*
* Allocate array storage when required.
*/
if(!sockets->sockets) {
sockets->sockets = malloc(sizeof(curl_socket_t) * 20U);
if(!sockets->sockets)
return;
sockets->max_count = 20;
}
else if(sockets->count + 1 > sockets->max_count) {
curl_socket_t *oldptr = sockets->sockets;
sockets->sockets = realloc(oldptr, sizeof(curl_socket_t) *
(sockets->max_count + 20));
if(!sockets->sockets) {
/* cleanup in test_cleanup */
sockets->sockets = oldptr;
return;
}
sockets->max_count += 20;
}
/*
* Add file descriptor to array.
*/
sockets->sockets[sockets->count] = fd;
++sockets->count;
}
/**
* Callback invoked by curl to poll reading / writing of a socket.
*/
static int curlSocketCallback(CURL *easy, curl_socket_t s, int action,
void *userp, void *socketp)
{
struct ReadWriteSockets *sockets = userp;
(void)easy; /* unused */
(void)socketp; /* unused */
if(action == CURL_POLL_IN || action == CURL_POLL_INOUT)
addFd(&sockets->read, s, "read");
if(action == CURL_POLL_OUT || action == CURL_POLL_INOUT)
addFd(&sockets->write, s, "write");
if(action == CURL_POLL_REMOVE) {
removeFd(&sockets->read, s, 1);
removeFd(&sockets->write, s, 0);
}
return 0;
}
/**
* Callback invoked by curl to set a timeout.
*/
static int curlTimerCallback(CURLM *multi, long timeout_ms, void *userp)
{
struct timeval *timeout = userp;
(void)multi; /* unused */
if(timeout_ms != -1) {
*timeout = tutil_tvnow();
timeout->tv_usec += timeout_ms * 1000;
}
else {
timeout->tv_sec = -1;
}
return 0;
}
/**
* Check for curl completion.
*/
static int checkForCompletion(CURLM *curl, int *success)
{
int numMessages;
CURLMsg *message;
int result = 0;
*success = 0;
while((message = curl_multi_info_read(curl, &numMessages)) != NULL) {
if(message->msg == CURLMSG_DONE) {
result = 1;
if(message->data.result == CURLE_OK)
*success = 1;
else
*success = 0;
}
else {
fprintf(stderr, "Got an unexpected message from curl: %i\n",
(int)message->msg);
result = 1;
*success = 0;
}
}
return result;
}
static int getMicroSecondTimeout(struct timeval *timeout)
{
struct timeval now;
ssize_t result;
now = tutil_tvnow();
result = (ssize_t)((timeout->tv_sec - now.tv_sec) * 1000000 +
timeout->tv_usec - now.tv_usec);
if(result < 0)
result = 0;
return curlx_sztosi(result);
}
/**
* Update a fd_set with all of the sockets in use.
*/
static void updateFdSet(struct Sockets *sockets, fd_set* fdset,
curl_socket_t *maxFd)
{
int i;
for(i = 0; i < sockets->count; ++i) {
FD_SET(sockets->sockets[i], fdset);
if(*maxFd < sockets->sockets[i] + 1) {
*maxFd = sockets->sockets[i] + 1;
}
}
}
static void notifyCurl(CURLM *curl, curl_socket_t s, int evBitmask,
const char *info)
{
int numhandles = 0;
CURLMcode result = curl_multi_socket_action(curl, s, evBitmask, &numhandles);
if(result != CURLM_OK) {
fprintf(stderr, "Curl error on %s: %i (%s)\n",
info, result, curl_multi_strerror(result));
}
}
/**
* Invoke curl when a file descriptor is set.
*/
static void checkFdSet(CURLM *curl, struct Sockets *sockets, fd_set *fdset,
int evBitmask, const char *name)
{
int i;
for(i = 0; i < sockets->count; ++i) {
if(FD_ISSET(sockets->sockets[i], fdset)) {
notifyCurl(curl, sockets->sockets[i], evBitmask, name);
}
}
}
int test(char *URL)
{
int res = 0;
CURL *curl = NULL;
FILE *hd_src = NULL;
int hd;
struct_stat file_info;
CURLM *m = NULL;
struct ReadWriteSockets sockets = {{NULL, 0, 0}, {NULL, 0, 0}};
struct timeval timeout = {-1, 0};
int success = 0;
start_test_timing();
if(!libtest_arg3) {
fprintf(stderr, "Usage: lib582 [url] [filename] [username]\n");
return TEST_ERR_USAGE;
}
hd_src = fopen(libtest_arg2, "rb");
if(NULL == hd_src) {
fprintf(stderr, "fopen() failed with error: %d (%s)\n",
errno, strerror(errno));
fprintf(stderr, "Error opening file: (%s)\n", libtest_arg2);
return TEST_ERR_FOPEN;
}
/* get the file size of the local file */
hd = fstat(fileno(hd_src), &file_info);
if(hd == -1) {
/* can't open file, bail out */
fprintf(stderr, "fstat() failed with error: %d (%s)\n",
errno, strerror(errno));
fprintf(stderr, "ERROR: cannot open file (%s)\n", libtest_arg2);
fclose(hd_src);
return TEST_ERR_FSTAT;
}
fprintf(stderr, "Set to upload %d bytes\n", (int)file_info.st_size);
res_global_init(CURL_GLOBAL_ALL);
if(res) {
fclose(hd_src);
return res;
}
easy_init(curl);
/* enable uploading */
easy_setopt(curl, CURLOPT_UPLOAD, 1L);
/* specify target */
easy_setopt(curl, CURLOPT_URL, URL);
/* go verbose */
easy_setopt(curl, CURLOPT_VERBOSE, 1L);
/* now specify which file to upload */
easy_setopt(curl, CURLOPT_READDATA, hd_src);
easy_setopt(curl, CURLOPT_USERPWD, libtest_arg3);
easy_setopt(curl, CURLOPT_SSH_PUBLIC_KEYFILE, "curl_client_key.pub");
easy_setopt(curl, CURLOPT_SSH_PRIVATE_KEYFILE, "curl_client_key");
easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)file_info.st_size);
multi_init(m);
multi_setopt(m, CURLMOPT_SOCKETFUNCTION, curlSocketCallback);
multi_setopt(m, CURLMOPT_SOCKETDATA, &sockets);
multi_setopt(m, CURLMOPT_TIMERFUNCTION, curlTimerCallback);
multi_setopt(m, CURLMOPT_TIMERDATA, &timeout);
multi_add_handle(m, curl);
while(!checkForCompletion(m, &success)) {
fd_set readSet, writeSet;
curl_socket_t maxFd = 0;
struct timeval tv = {10, 0};
FD_ZERO(&readSet);
FD_ZERO(&writeSet);
updateFdSet(&sockets.read, &readSet, &maxFd);
updateFdSet(&sockets.write, &writeSet, &maxFd);
if(timeout.tv_sec != -1) {
int usTimeout = getMicroSecondTimeout(&timeout);
tv.tv_sec = usTimeout / 1000000;
tv.tv_usec = usTimeout % 1000000;
}
else if(maxFd <= 0) {
tv.tv_sec = 0;
tv.tv_usec = 100000;
}
select_test((int)maxFd, &readSet, &writeSet, NULL, &tv);
/* Check the sockets for reading / writing */
checkFdSet(m, &sockets.read, &readSet, CURL_CSELECT_IN, "read");
checkFdSet(m, &sockets.write, &writeSet, CURL_CSELECT_OUT, "write");
if(timeout.tv_sec != -1 && getMicroSecondTimeout(&timeout) == 0) {
/* Curl's timer has elapsed. */
notifyCurl(m, CURL_SOCKET_TIMEOUT, 0, "timeout");
}
abort_on_test_timeout();
}
if(!success) {
fprintf(stderr, "Error uploading file.\n");
res = TEST_ERR_MAJOR_BAD;
}
test_cleanup:
/* proper cleanup sequence - type PB */
curl_multi_remove_handle(m, curl);
curl_easy_cleanup(curl);
curl_multi_cleanup(m);
curl_global_cleanup();
/* close the local file */
fclose(hd_src);
/* free local memory */
free(sockets.read.sockets);
free(sockets.write.sockets);
return res;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/lib503.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "test.h"
#include "testutil.h"
#include "warnless.h"
#include "memdebug.h"
#define TEST_HANG_TIMEOUT 60 * 1000
/*
* Source code in here hugely as reported in bug report 651460 by
* Christopher R. Palmer.
*
* Use multi interface to get HTTPS document over proxy, and provide
* auth info.
*/
int test(char *URL)
{
CURL *c = NULL;
CURLM *m = NULL;
int res = 0;
int running;
start_test_timing();
global_init(CURL_GLOBAL_ALL);
easy_init(c);
easy_setopt(c, CURLOPT_PROXY, libtest_arg2); /* set in first.c */
easy_setopt(c, CURLOPT_URL, URL);
easy_setopt(c, CURLOPT_USERPWD, "test:ing");
easy_setopt(c, CURLOPT_PROXYUSERPWD, "test:ing");
easy_setopt(c, CURLOPT_HTTPPROXYTUNNEL, 1L);
easy_setopt(c, CURLOPT_HEADER, 1L);
easy_setopt(c, CURLOPT_VERBOSE, 1L);
multi_init(m);
multi_add_handle(m, c);
for(;;) {
struct timeval interval;
fd_set rd, wr, exc;
int maxfd = -99;
interval.tv_sec = 1;
interval.tv_usec = 0;
multi_perform(m, &running);
abort_on_test_timeout();
if(!running)
break; /* done */
FD_ZERO(&rd);
FD_ZERO(&wr);
FD_ZERO(&exc);
multi_fdset(m, &rd, &wr, &exc, &maxfd);
/* At this point, maxfd is guaranteed to be greater or equal than -1. */
select_test(maxfd + 1, &rd, &wr, &exc, &interval);
abort_on_test_timeout();
}
test_cleanup:
/* proper cleanup sequence - type PA */
curl_multi_remove_handle(m, c);
curl_multi_cleanup(m);
curl_easy_cleanup(c);
curl_global_cleanup();
return res;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/lib1534.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "test.h"
#include "memdebug.h"
/* Test CURLINFO_FILETIME */
int test(char *URL)
{
CURL *curl, *dupe = NULL;
long filetime;
int res = CURLE_OK;
global_init(CURL_GLOBAL_ALL);
easy_init(curl);
/* Test that a filetime is properly initialized on curl_easy_init.
*/
res = curl_easy_getinfo(curl, CURLINFO_FILETIME, &filetime);
if(res) {
fprintf(stderr, "%s:%d curl_easy_getinfo() failed with code %d (%s)\n",
__FILE__, __LINE__, res, curl_easy_strerror(res));
goto test_cleanup;
}
if(filetime != -1) {
fprintf(stderr, "%s:%d filetime init failed; expected -1 but is %ld\n",
__FILE__, __LINE__, filetime);
res = CURLE_FAILED_INIT;
goto test_cleanup;
}
easy_setopt(curl, CURLOPT_URL, URL);
easy_setopt(curl, CURLOPT_FILETIME, 1L);
res = curl_easy_perform(curl);
if(res) {
fprintf(stderr, "%s:%d curl_easy_perform() failed with code %d (%s)\n",
__FILE__, __LINE__, res, curl_easy_strerror(res));
goto test_cleanup;
}
/* Test that a filetime is properly set after receiving an HTTP resource.
*/
res = curl_easy_getinfo(curl, CURLINFO_FILETIME, &filetime);
if(res) {
fprintf(stderr, "%s:%d curl_easy_getinfo() failed with code %d (%s)\n",
__FILE__, __LINE__, res, curl_easy_strerror(res));
goto test_cleanup;
}
if(filetime != 30) {
fprintf(stderr, "%s:%d filetime of http resource is incorrect; "
"expected 30 but is %ld\n",
__FILE__, __LINE__, filetime);
res = CURLE_HTTP_RETURNED_ERROR;
goto test_cleanup;
}
/* Test that a filetime is properly initialized on curl_easy_duphandle.
*/
dupe = curl_easy_duphandle(curl);
if(!dupe) {
fprintf(stderr, "%s:%d curl_easy_duphandle() failed\n",
__FILE__, __LINE__);
res = CURLE_FAILED_INIT;
goto test_cleanup;
}
res = curl_easy_getinfo(dupe, CURLINFO_FILETIME, &filetime);
if(res) {
fprintf(stderr, "%s:%d curl_easy_getinfo() failed with code %d (%s)\n",
__FILE__, __LINE__, res, curl_easy_strerror(res));
goto test_cleanup;
}
if(filetime != -1) {
fprintf(stderr, "%s:%d filetime init failed; expected -1 but is %ld\n",
__FILE__, __LINE__, filetime);
res = CURLE_FAILED_INIT;
goto test_cleanup;
}
/* Test that a filetime is properly initialized on curl_easy_reset.
*/
curl_easy_reset(curl);
res = curl_easy_getinfo(curl, CURLINFO_FILETIME, &filetime);
if(res) {
fprintf(stderr, "%s:%d curl_easy_getinfo() failed with code %d (%s)\n",
__FILE__, __LINE__, res, curl_easy_strerror(res));
goto test_cleanup;
}
if(filetime != -1) {
fprintf(stderr, "%s:%d filetime init failed; expected -1 but is %ld\n",
__FILE__, __LINE__, filetime);
res = CURLE_FAILED_INIT;
goto test_cleanup;
}
test_cleanup:
curl_easy_cleanup(curl);
curl_easy_cleanup(dupe);
curl_global_cleanup();
return res;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/lib569.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "test.h"
#include "memdebug.h"
/* build request url */
static char *suburl(const char *base, int i)
{
return curl_maprintf("%s%.4d", base, i);
}
/*
* Test Session ID capture
*/
int test(char *URL)
{
int res;
CURL *curl;
char *stream_uri = NULL;
char *rtsp_session_id;
int request = 1;
int i;
FILE *idfile = fopen(libtest_arg2, "wb");
if(!idfile) {
fprintf(stderr, "couldn't open the Session ID File\n");
return TEST_ERR_MAJOR_BAD;
}
if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) {
fprintf(stderr, "curl_global_init() failed\n");
fclose(idfile);
return TEST_ERR_MAJOR_BAD;
}
curl = curl_easy_init();
if(!curl) {
fprintf(stderr, "curl_easy_init() failed\n");
curl_global_cleanup();
fclose(idfile);
return TEST_ERR_MAJOR_BAD;
}
test_setopt(curl, CURLOPT_HEADERDATA, stdout);
test_setopt(curl, CURLOPT_WRITEDATA, stdout);
test_setopt(curl, CURLOPT_VERBOSE, 1L);
test_setopt(curl, CURLOPT_URL, URL);
test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_SETUP);
res = curl_easy_perform(curl);
if(res != (int)CURLE_BAD_FUNCTION_ARGUMENT) {
fprintf(stderr, "This should have failed. "
"Cannot setup without a Transport: header");
res = TEST_ERR_MAJOR_BAD;
goto test_cleanup;
}
/* Go through the various Session IDs */
for(i = 0; i < 3; i++) {
stream_uri = suburl(URL, request++);
if(!stream_uri) {
res = TEST_ERR_MAJOR_BAD;
goto test_cleanup;
}
test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri);
free(stream_uri);
stream_uri = NULL;
test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_SETUP);
test_setopt(curl, CURLOPT_RTSP_TRANSPORT,
"Fake/NotReal/JustATest;foo=baz");
res = curl_easy_perform(curl);
if(res)
goto test_cleanup;
curl_easy_getinfo(curl, CURLINFO_RTSP_SESSION_ID, &rtsp_session_id);
fprintf(idfile, "Got Session ID: [%s]\n", rtsp_session_id);
rtsp_session_id = NULL;
stream_uri = suburl(URL, request++);
if(!stream_uri) {
res = TEST_ERR_MAJOR_BAD;
goto test_cleanup;
}
test_setopt(curl, CURLOPT_RTSP_STREAM_URI, stream_uri);
free(stream_uri);
stream_uri = NULL;
test_setopt(curl, CURLOPT_RTSP_REQUEST, CURL_RTSPREQ_TEARDOWN);
res = curl_easy_perform(curl);
/* Clear for the next go-round */
test_setopt(curl, CURLOPT_RTSP_SESSION_ID, NULL);
}
test_cleanup:
if(idfile)
fclose(idfile);
free(stream_uri);
curl_easy_cleanup(curl);
curl_global_cleanup();
return res;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/lib557.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/*
* The purpose of this test is to minimally exercise libcurl's internal
* curl_m*printf formatting capabilities and handling of some data types.
*/
#include "test.h"
#include <limits.h>
#ifdef HAVE_LOCALE_H
# include <locale.h> /* for setlocale() */
#endif
#include "memdebug.h"
#if (SIZEOF_CURL_OFF_T > SIZEOF_LONG)
# define MPRNT_SUFFIX_CURL_OFF_T LL
#else
# define MPRNT_SUFFIX_CURL_OFF_T L
#endif
#ifdef CURL_ISOCPP
# define MPRNT_OFF_T_C_HELPER2(Val,Suffix) Val ## Suffix
#else
# define MPRNT_OFF_T_C_HELPER2(Val,Suffix) Val/**/Suffix
#endif
#define MPRNT_OFF_T_C_HELPER1(Val,Suffix) MPRNT_OFF_T_C_HELPER2(Val,Suffix)
#define MPRNT_OFF_T_C(Val) MPRNT_OFF_T_C_HELPER1(Val,MPRNT_SUFFIX_CURL_OFF_T)
#define BUFSZ 256
#define USHORT_TESTS_ARRSZ 1 + 100
#define SSHORT_TESTS_ARRSZ 1 + 100
#define UINT_TESTS_ARRSZ 1 + 100
#define SINT_TESTS_ARRSZ 1 + 100
#define ULONG_TESTS_ARRSZ 1 + 100
#define SLONG_TESTS_ARRSZ 1 + 100
#define COFFT_TESTS_ARRSZ 1 + 100
struct unsshort_st {
unsigned short num; /* unsigned short */
const char *expected; /* expected string */
char result[BUFSZ]; /* result string */
};
struct sigshort_st {
short num; /* signed short */
const char *expected; /* expected string */
char result[BUFSZ]; /* result string */
};
struct unsint_st {
unsigned int num; /* unsigned int */
const char *expected; /* expected string */
char result[BUFSZ]; /* result string */
};
struct sigint_st {
int num; /* signed int */
const char *expected; /* expected string */
char result[BUFSZ]; /* result string */
};
struct unslong_st {
unsigned long num; /* unsigned long */
const char *expected; /* expected string */
char result[BUFSZ]; /* result string */
};
struct siglong_st {
long num; /* signed long */
const char *expected; /* expected string */
char result[BUFSZ]; /* result string */
};
struct curloff_st {
curl_off_t num; /* curl_off_t */
const char *expected; /* expected string */
char result[BUFSZ]; /* result string */
};
static struct unsshort_st us_test[USHORT_TESTS_ARRSZ];
static struct sigshort_st ss_test[SSHORT_TESTS_ARRSZ];
static struct unsint_st ui_test[UINT_TESTS_ARRSZ];
static struct sigint_st si_test[SINT_TESTS_ARRSZ];
static struct unslong_st ul_test[ULONG_TESTS_ARRSZ];
static struct siglong_st sl_test[SLONG_TESTS_ARRSZ];
static struct curloff_st co_test[COFFT_TESTS_ARRSZ];
static int test_unsigned_short_formatting(void)
{
int i, j;
int num_ushort_tests = 0;
int failed = 0;
#if (SIZEOF_SHORT == 1)
i = 1; us_test[i].num = 0xFFU; us_test[i].expected = "256";
i++; us_test[i].num = 0xF0U; us_test[i].expected = "240";
i++; us_test[i].num = 0x0FU; us_test[i].expected = "15";
i++; us_test[i].num = 0xE0U; us_test[i].expected = "224";
i++; us_test[i].num = 0x0EU; us_test[i].expected = "14";
i++; us_test[i].num = 0xC0U; us_test[i].expected = "192";
i++; us_test[i].num = 0x0CU; us_test[i].expected = "12";
i++; us_test[i].num = 0x01U; us_test[i].expected = "1";
i++; us_test[i].num = 0x00U; us_test[i].expected = "0";
num_ushort_tests = i;
#elif (SIZEOF_SHORT == 2)
i = 1; us_test[i].num = 0xFFFFU; us_test[i].expected = "65535";
i++; us_test[i].num = 0xFF00U; us_test[i].expected = "65280";
i++; us_test[i].num = 0x00FFU; us_test[i].expected = "255";
i++; us_test[i].num = 0xF000U; us_test[i].expected = "61440";
i++; us_test[i].num = 0x0F00U; us_test[i].expected = "3840";
i++; us_test[i].num = 0x00F0U; us_test[i].expected = "240";
i++; us_test[i].num = 0x000FU; us_test[i].expected = "15";
i++; us_test[i].num = 0xC000U; us_test[i].expected = "49152";
i++; us_test[i].num = 0x0C00U; us_test[i].expected = "3072";
i++; us_test[i].num = 0x00C0U; us_test[i].expected = "192";
i++; us_test[i].num = 0x000CU; us_test[i].expected = "12";
i++; us_test[i].num = 0x0001U; us_test[i].expected = "1";
i++; us_test[i].num = 0x0000U; us_test[i].expected = "0";
num_ushort_tests = i;
#elif (SIZEOF_SHORT == 4)
i = 1; us_test[i].num = 0xFFFFFFFFU; us_test[i].expected = "4294967295";
i++; us_test[i].num = 0xFFFF0000U; us_test[i].expected = "4294901760";
i++; us_test[i].num = 0x0000FFFFU; us_test[i].expected = "65535";
i++; us_test[i].num = 0xFF000000U; us_test[i].expected = "4278190080";
i++; us_test[i].num = 0x00FF0000U; us_test[i].expected = "16711680";
i++; us_test[i].num = 0x0000FF00U; us_test[i].expected = "65280";
i++; us_test[i].num = 0x000000FFU; us_test[i].expected = "255";
i++; us_test[i].num = 0xF0000000U; us_test[i].expected = "4026531840";
i++; us_test[i].num = 0x0F000000U; us_test[i].expected = "251658240";
i++; us_test[i].num = 0x00F00000U; us_test[i].expected = "15728640";
i++; us_test[i].num = 0x000F0000U; us_test[i].expected = "983040";
i++; us_test[i].num = 0x0000F000U; us_test[i].expected = "61440";
i++; us_test[i].num = 0x00000F00U; us_test[i].expected = "3840";
i++; us_test[i].num = 0x000000F0U; us_test[i].expected = "240";
i++; us_test[i].num = 0x0000000FU; us_test[i].expected = "15";
i++; us_test[i].num = 0xC0000000U; us_test[i].expected = "3221225472";
i++; us_test[i].num = 0x0C000000U; us_test[i].expected = "201326592";
i++; us_test[i].num = 0x00C00000U; us_test[i].expected = "12582912";
i++; us_test[i].num = 0x000C0000U; us_test[i].expected = "786432";
i++; us_test[i].num = 0x0000C000U; us_test[i].expected = "49152";
i++; us_test[i].num = 0x00000C00U; us_test[i].expected = "3072";
i++; us_test[i].num = 0x000000C0U; us_test[i].expected = "192";
i++; us_test[i].num = 0x0000000CU; us_test[i].expected = "12";
i++; us_test[i].num = 0x00000001U; us_test[i].expected = "1";
i++; us_test[i].num = 0x00000000U; us_test[i].expected = "0";
num_ushort_tests = i;
#endif
for(i = 1; i <= num_ushort_tests; i++) {
for(j = 0; j<BUFSZ; j++)
us_test[i].result[j] = 'X';
us_test[i].result[BUFSZ-1] = '\0';
(void)curl_msprintf(us_test[i].result, "%hu", us_test[i].num);
if(memcmp(us_test[i].result,
us_test[i].expected,
strlen(us_test[i].expected))) {
printf("unsigned short test #%.2d: Failed (Expected: %s Got: %s)\n",
i, us_test[i].expected, us_test[i].result);
failed++;
}
}
if(!failed)
printf("All curl_mprintf() unsigned short tests OK!\n");
else
printf("Some curl_mprintf() unsigned short tests Failed!\n");
return failed;
}
static int test_signed_short_formatting(void)
{
int i, j;
int num_sshort_tests = 0;
int failed = 0;
#if (SIZEOF_SHORT == 1)
i = 1; ss_test[i].num = 0x7F; ss_test[i].expected = "127";
i++; ss_test[i].num = 0x70; ss_test[i].expected = "112";
i++; ss_test[i].num = 0x07; ss_test[i].expected = "7";
i++; ss_test[i].num = 0x50; ss_test[i].expected = "80";
i++; ss_test[i].num = 0x05; ss_test[i].expected = "5";
i++; ss_test[i].num = 0x01; ss_test[i].expected = "1";
i++; ss_test[i].num = 0x00; ss_test[i].expected = "0";
i++; ss_test[i].num = -0x7F -1; ss_test[i].expected = "-128";
i++; ss_test[i].num = -0x70 -1; ss_test[i].expected = "-113";
i++; ss_test[i].num = -0x07 -1; ss_test[i].expected = "-8";
i++; ss_test[i].num = -0x50 -1; ss_test[i].expected = "-81";
i++; ss_test[i].num = -0x05 -1; ss_test[i].expected = "-6";
i++; ss_test[i].num = 0x00 -1; ss_test[i].expected = "-1";
num_sshort_tests = i;
#elif (SIZEOF_SHORT == 2)
i = 1; ss_test[i].num = 0x7FFF; ss_test[i].expected = "32767";
i++; ss_test[i].num = 0x7FFE; ss_test[i].expected = "32766";
i++; ss_test[i].num = 0x7FFD; ss_test[i].expected = "32765";
i++; ss_test[i].num = 0x7F00; ss_test[i].expected = "32512";
i++; ss_test[i].num = 0x07F0; ss_test[i].expected = "2032";
i++; ss_test[i].num = 0x007F; ss_test[i].expected = "127";
i++; ss_test[i].num = 0x7000; ss_test[i].expected = "28672";
i++; ss_test[i].num = 0x0700; ss_test[i].expected = "1792";
i++; ss_test[i].num = 0x0070; ss_test[i].expected = "112";
i++; ss_test[i].num = 0x0007; ss_test[i].expected = "7";
i++; ss_test[i].num = 0x5000; ss_test[i].expected = "20480";
i++; ss_test[i].num = 0x0500; ss_test[i].expected = "1280";
i++; ss_test[i].num = 0x0050; ss_test[i].expected = "80";
i++; ss_test[i].num = 0x0005; ss_test[i].expected = "5";
i++; ss_test[i].num = 0x0001; ss_test[i].expected = "1";
i++; ss_test[i].num = 0x0000; ss_test[i].expected = "0";
i++; ss_test[i].num = -0x7FFF -1; ss_test[i].expected = "-32768";
i++; ss_test[i].num = -0x7FFE -1; ss_test[i].expected = "-32767";
i++; ss_test[i].num = -0x7FFD -1; ss_test[i].expected = "-32766";
i++; ss_test[i].num = -0x7F00 -1; ss_test[i].expected = "-32513";
i++; ss_test[i].num = -0x07F0 -1; ss_test[i].expected = "-2033";
i++; ss_test[i].num = -0x007F -1; ss_test[i].expected = "-128";
i++; ss_test[i].num = -0x7000 -1; ss_test[i].expected = "-28673";
i++; ss_test[i].num = -0x0700 -1; ss_test[i].expected = "-1793";
i++; ss_test[i].num = -0x0070 -1; ss_test[i].expected = "-113";
i++; ss_test[i].num = -0x0007 -1; ss_test[i].expected = "-8";
i++; ss_test[i].num = -0x5000 -1; ss_test[i].expected = "-20481";
i++; ss_test[i].num = -0x0500 -1; ss_test[i].expected = "-1281";
i++; ss_test[i].num = -0x0050 -1; ss_test[i].expected = "-81";
i++; ss_test[i].num = -0x0005 -1; ss_test[i].expected = "-6";
i++; ss_test[i].num = 0x0000 -1; ss_test[i].expected = "-1";
num_sshort_tests = i;
#elif (SIZEOF_SHORT == 4)
i = 1; ss_test[i].num = 0x7FFFFFFF; ss_test[i].expected = "2147483647";
i++; ss_test[i].num = 0x7FFFFFFE; ss_test[i].expected = "2147483646";
i++; ss_test[i].num = 0x7FFFFFFD; ss_test[i].expected = "2147483645";
i++; ss_test[i].num = 0x7FFF0000; ss_test[i].expected = "2147418112";
i++; ss_test[i].num = 0x00007FFF; ss_test[i].expected = "32767";
i++; ss_test[i].num = 0x7F000000; ss_test[i].expected = "2130706432";
i++; ss_test[i].num = 0x007F0000; ss_test[i].expected = "8323072";
i++; ss_test[i].num = 0x00007F00; ss_test[i].expected = "32512";
i++; ss_test[i].num = 0x0000007F; ss_test[i].expected = "127";
i++; ss_test[i].num = 0x70000000; ss_test[i].expected = "1879048192";
i++; ss_test[i].num = 0x07000000; ss_test[i].expected = "117440512";
i++; ss_test[i].num = 0x00700000; ss_test[i].expected = "7340032";
i++; ss_test[i].num = 0x00070000; ss_test[i].expected = "458752";
i++; ss_test[i].num = 0x00007000; ss_test[i].expected = "28672";
i++; ss_test[i].num = 0x00000700; ss_test[i].expected = "1792";
i++; ss_test[i].num = 0x00000070; ss_test[i].expected = "112";
i++; ss_test[i].num = 0x00000007; ss_test[i].expected = "7";
i++; ss_test[i].num = 0x50000000; ss_test[i].expected = "1342177280";
i++; ss_test[i].num = 0x05000000; ss_test[i].expected = "83886080";
i++; ss_test[i].num = 0x00500000; ss_test[i].expected = "5242880";
i++; ss_test[i].num = 0x00050000; ss_test[i].expected = "327680";
i++; ss_test[i].num = 0x00005000; ss_test[i].expected = "20480";
i++; ss_test[i].num = 0x00000500; ss_test[i].expected = "1280";
i++; ss_test[i].num = 0x00000050; ss_test[i].expected = "80";
i++; ss_test[i].num = 0x00000005; ss_test[i].expected = "5";
i++; ss_test[i].num = 0x00000001; ss_test[i].expected = "1";
i++; ss_test[i].num = 0x00000000; ss_test[i].expected = "0";
i++; ss_test[i].num = -0x7FFFFFFF -1; ss_test[i].expected = "-2147483648";
i++; ss_test[i].num = -0x7FFFFFFE -1; ss_test[i].expected = "-2147483647";
i++; ss_test[i].num = -0x7FFFFFFD -1; ss_test[i].expected = "-2147483646";
i++; ss_test[i].num = -0x7FFF0000 -1; ss_test[i].expected = "-2147418113";
i++; ss_test[i].num = -0x00007FFF -1; ss_test[i].expected = "-32768";
i++; ss_test[i].num = -0x7F000000 -1; ss_test[i].expected = "-2130706433";
i++; ss_test[i].num = -0x007F0000 -1; ss_test[i].expected = "-8323073";
i++; ss_test[i].num = -0x00007F00 -1; ss_test[i].expected = "-32513";
i++; ss_test[i].num = -0x0000007F -1; ss_test[i].expected = "-128";
i++; ss_test[i].num = -0x70000000 -1; ss_test[i].expected = "-1879048193";
i++; ss_test[i].num = -0x07000000 -1; ss_test[i].expected = "-117440513";
i++; ss_test[i].num = -0x00700000 -1; ss_test[i].expected = "-7340033";
i++; ss_test[i].num = -0x00070000 -1; ss_test[i].expected = "-458753";
i++; ss_test[i].num = -0x00007000 -1; ss_test[i].expected = "-28673";
i++; ss_test[i].num = -0x00000700 -1; ss_test[i].expected = "-1793";
i++; ss_test[i].num = -0x00000070 -1; ss_test[i].expected = "-113";
i++; ss_test[i].num = -0x00000007 -1; ss_test[i].expected = "-8";
i++; ss_test[i].num = -0x50000000 -1; ss_test[i].expected = "-1342177281";
i++; ss_test[i].num = -0x05000000 -1; ss_test[i].expected = "-83886081";
i++; ss_test[i].num = -0x00500000 -1; ss_test[i].expected = "-5242881";
i++; ss_test[i].num = -0x00050000 -1; ss_test[i].expected = "-327681";
i++; ss_test[i].num = -0x00005000 -1; ss_test[i].expected = "-20481";
i++; ss_test[i].num = -0x00000500 -1; ss_test[i].expected = "-1281";
i++; ss_test[i].num = -0x00000050 -1; ss_test[i].expected = "-81";
i++; ss_test[i].num = -0x00000005 -1; ss_test[i].expected = "-6";
i++; ss_test[i].num = 0x00000000 -1; ss_test[i].expected = "-1";
num_sshort_tests = i;
#endif
for(i = 1; i <= num_sshort_tests; i++) {
for(j = 0; j<BUFSZ; j++)
ss_test[i].result[j] = 'X';
ss_test[i].result[BUFSZ-1] = '\0';
(void)curl_msprintf(ss_test[i].result, "%hd", ss_test[i].num);
if(memcmp(ss_test[i].result,
ss_test[i].expected,
strlen(ss_test[i].expected))) {
printf("signed short test #%.2d: Failed (Expected: %s Got: %s)\n",
i, ss_test[i].expected, ss_test[i].result);
failed++;
}
}
if(!failed)
printf("All curl_mprintf() signed short tests OK!\n");
else
printf("Some curl_mprintf() signed short tests Failed!\n");
return failed;
}
static int test_unsigned_int_formatting(void)
{
int i, j;
int num_uint_tests = 0;
int failed = 0;
#if (SIZEOF_INT == 2)
i = 1; ui_test[i].num = 0xFFFFU; ui_test[i].expected = "65535";
i++; ui_test[i].num = 0xFF00U; ui_test[i].expected = "65280";
i++; ui_test[i].num = 0x00FFU; ui_test[i].expected = "255";
i++; ui_test[i].num = 0xF000U; ui_test[i].expected = "61440";
i++; ui_test[i].num = 0x0F00U; ui_test[i].expected = "3840";
i++; ui_test[i].num = 0x00F0U; ui_test[i].expected = "240";
i++; ui_test[i].num = 0x000FU; ui_test[i].expected = "15";
i++; ui_test[i].num = 0xC000U; ui_test[i].expected = "49152";
i++; ui_test[i].num = 0x0C00U; ui_test[i].expected = "3072";
i++; ui_test[i].num = 0x00C0U; ui_test[i].expected = "192";
i++; ui_test[i].num = 0x000CU; ui_test[i].expected = "12";
i++; ui_test[i].num = 0x0001U; ui_test[i].expected = "1";
i++; ui_test[i].num = 0x0000U; ui_test[i].expected = "0";
num_uint_tests = i;
#elif (SIZEOF_INT == 4)
i = 1; ui_test[i].num = 0xFFFFFFFFU; ui_test[i].expected = "4294967295";
i++; ui_test[i].num = 0xFFFF0000U; ui_test[i].expected = "4294901760";
i++; ui_test[i].num = 0x0000FFFFU; ui_test[i].expected = "65535";
i++; ui_test[i].num = 0xFF000000U; ui_test[i].expected = "4278190080";
i++; ui_test[i].num = 0x00FF0000U; ui_test[i].expected = "16711680";
i++; ui_test[i].num = 0x0000FF00U; ui_test[i].expected = "65280";
i++; ui_test[i].num = 0x000000FFU; ui_test[i].expected = "255";
i++; ui_test[i].num = 0xF0000000U; ui_test[i].expected = "4026531840";
i++; ui_test[i].num = 0x0F000000U; ui_test[i].expected = "251658240";
i++; ui_test[i].num = 0x00F00000U; ui_test[i].expected = "15728640";
i++; ui_test[i].num = 0x000F0000U; ui_test[i].expected = "983040";
i++; ui_test[i].num = 0x0000F000U; ui_test[i].expected = "61440";
i++; ui_test[i].num = 0x00000F00U; ui_test[i].expected = "3840";
i++; ui_test[i].num = 0x000000F0U; ui_test[i].expected = "240";
i++; ui_test[i].num = 0x0000000FU; ui_test[i].expected = "15";
i++; ui_test[i].num = 0xC0000000U; ui_test[i].expected = "3221225472";
i++; ui_test[i].num = 0x0C000000U; ui_test[i].expected = "201326592";
i++; ui_test[i].num = 0x00C00000U; ui_test[i].expected = "12582912";
i++; ui_test[i].num = 0x000C0000U; ui_test[i].expected = "786432";
i++; ui_test[i].num = 0x0000C000U; ui_test[i].expected = "49152";
i++; ui_test[i].num = 0x00000C00U; ui_test[i].expected = "3072";
i++; ui_test[i].num = 0x000000C0U; ui_test[i].expected = "192";
i++; ui_test[i].num = 0x0000000CU; ui_test[i].expected = "12";
i++; ui_test[i].num = 0x00000001U; ui_test[i].expected = "1";
i++; ui_test[i].num = 0x00000000U; ui_test[i].expected = "0";
num_uint_tests = i;
#elif (SIZEOF_INT == 8)
/* !checksrc! disable LONGLINE all */
i = 1; ui_test[i].num = 0xFFFFFFFFFFFFFFFFU; ui_test[i].expected = "18446744073709551615";
i++; ui_test[i].num = 0xFFFFFFFF00000000U; ui_test[i].expected = "18446744069414584320";
i++; ui_test[i].num = 0x00000000FFFFFFFFU; ui_test[i].expected = "4294967295";
i++; ui_test[i].num = 0xFFFF000000000000U; ui_test[i].expected = "18446462598732840960";
i++; ui_test[i].num = 0x0000FFFF00000000U; ui_test[i].expected = "281470681743360";
i++; ui_test[i].num = 0x00000000FFFF0000U; ui_test[i].expected = "4294901760";
i++; ui_test[i].num = 0x000000000000FFFFU; ui_test[i].expected = "65535";
i++; ui_test[i].num = 0xFF00000000000000U; ui_test[i].expected = "18374686479671623680";
i++; ui_test[i].num = 0x00FF000000000000U; ui_test[i].expected = "71776119061217280";
i++; ui_test[i].num = 0x0000FF0000000000U; ui_test[i].expected = "280375465082880";
i++; ui_test[i].num = 0x000000FF00000000U; ui_test[i].expected = "1095216660480";
i++; ui_test[i].num = 0x00000000FF000000U; ui_test[i].expected = "4278190080";
i++; ui_test[i].num = 0x0000000000FF0000U; ui_test[i].expected = "16711680";
i++; ui_test[i].num = 0x000000000000FF00U; ui_test[i].expected = "65280";
i++; ui_test[i].num = 0x00000000000000FFU; ui_test[i].expected = "255";
i++; ui_test[i].num = 0xF000000000000000U; ui_test[i].expected = "17293822569102704640";
i++; ui_test[i].num = 0x0F00000000000000U; ui_test[i].expected = "1080863910568919040";
i++; ui_test[i].num = 0x00F0000000000000U; ui_test[i].expected = "67553994410557440";
i++; ui_test[i].num = 0x000F000000000000U; ui_test[i].expected = "4222124650659840";
i++; ui_test[i].num = 0x0000F00000000000U; ui_test[i].expected = "263882790666240";
i++; ui_test[i].num = 0x00000F0000000000U; ui_test[i].expected = "16492674416640";
i++; ui_test[i].num = 0x000000F000000000U; ui_test[i].expected = "1030792151040";
i++; ui_test[i].num = 0x0000000F00000000U; ui_test[i].expected = "64424509440";
i++; ui_test[i].num = 0x00000000F0000000U; ui_test[i].expected = "4026531840";
i++; ui_test[i].num = 0x000000000F000000U; ui_test[i].expected = "251658240";
i++; ui_test[i].num = 0x0000000000F00000U; ui_test[i].expected = "15728640";
i++; ui_test[i].num = 0x00000000000F0000U; ui_test[i].expected = "983040";
i++; ui_test[i].num = 0x000000000000F000U; ui_test[i].expected = "61440";
i++; ui_test[i].num = 0x0000000000000F00U; ui_test[i].expected = "3840";
i++; ui_test[i].num = 0x00000000000000F0U; ui_test[i].expected = "240";
i++; ui_test[i].num = 0x000000000000000FU; ui_test[i].expected = "15";
i++; ui_test[i].num = 0xC000000000000000U; ui_test[i].expected = "13835058055282163712";
i++; ui_test[i].num = 0x0C00000000000000U; ui_test[i].expected = "864691128455135232";
i++; ui_test[i].num = 0x00C0000000000000U; ui_test[i].expected = "54043195528445952";
i++; ui_test[i].num = 0x000C000000000000U; ui_test[i].expected = "3377699720527872";
i++; ui_test[i].num = 0x0000C00000000000U; ui_test[i].expected = "211106232532992";
i++; ui_test[i].num = 0x00000C0000000000U; ui_test[i].expected = "13194139533312";
i++; ui_test[i].num = 0x000000C000000000U; ui_test[i].expected = "824633720832";
i++; ui_test[i].num = 0x0000000C00000000U; ui_test[i].expected = "51539607552";
i++; ui_test[i].num = 0x00000000C0000000U; ui_test[i].expected = "3221225472";
i++; ui_test[i].num = 0x000000000C000000U; ui_test[i].expected = "201326592";
i++; ui_test[i].num = 0x0000000000C00000U; ui_test[i].expected = "12582912";
i++; ui_test[i].num = 0x00000000000C0000U; ui_test[i].expected = "786432";
i++; ui_test[i].num = 0x000000000000C000U; ui_test[i].expected = "49152";
i++; ui_test[i].num = 0x0000000000000C00U; ui_test[i].expected = "3072";
i++; ui_test[i].num = 0x00000000000000C0U; ui_test[i].expected = "192";
i++; ui_test[i].num = 0x000000000000000CU; ui_test[i].expected = "12";
i++; ui_test[i].num = 0x00000001U; ui_test[i].expected = "1";
i++; ui_test[i].num = 0x00000000U; ui_test[i].expected = "0";
num_uint_tests = i;
#endif
for(i = 1; i <= num_uint_tests; i++) {
for(j = 0; j<BUFSZ; j++)
ui_test[i].result[j] = 'X';
ui_test[i].result[BUFSZ-1] = '\0';
(void)curl_msprintf(ui_test[i].result, "%u", ui_test[i].num);
if(memcmp(ui_test[i].result,
ui_test[i].expected,
strlen(ui_test[i].expected))) {
printf("unsigned int test #%.2d: Failed (Expected: %s Got: %s)\n",
i, ui_test[i].expected, ui_test[i].result);
failed++;
}
}
if(!failed)
printf("All curl_mprintf() unsigned int tests OK!\n");
else
printf("Some curl_mprintf() unsigned int tests Failed!\n");
return failed;
}
static int test_signed_int_formatting(void)
{
int i, j;
int num_sint_tests = 0;
int failed = 0;
#if (SIZEOF_INT == 2)
i = 1; si_test[i].num = 0x7FFF; si_test[i].expected = "32767";
i++; si_test[i].num = 0x7FFE; si_test[i].expected = "32766";
i++; si_test[i].num = 0x7FFD; si_test[i].expected = "32765";
i++; si_test[i].num = 0x7F00; si_test[i].expected = "32512";
i++; si_test[i].num = 0x07F0; si_test[i].expected = "2032";
i++; si_test[i].num = 0x007F; si_test[i].expected = "127";
i++; si_test[i].num = 0x7000; si_test[i].expected = "28672";
i++; si_test[i].num = 0x0700; si_test[i].expected = "1792";
i++; si_test[i].num = 0x0070; si_test[i].expected = "112";
i++; si_test[i].num = 0x0007; si_test[i].expected = "7";
i++; si_test[i].num = 0x5000; si_test[i].expected = "20480";
i++; si_test[i].num = 0x0500; si_test[i].expected = "1280";
i++; si_test[i].num = 0x0050; si_test[i].expected = "80";
i++; si_test[i].num = 0x0005; si_test[i].expected = "5";
i++; si_test[i].num = 0x0001; si_test[i].expected = "1";
i++; si_test[i].num = 0x0000; si_test[i].expected = "0";
i++; si_test[i].num = -0x7FFF -1; si_test[i].expected = "-32768";
i++; si_test[i].num = -0x7FFE -1; si_test[i].expected = "-32767";
i++; si_test[i].num = -0x7FFD -1; si_test[i].expected = "-32766";
i++; si_test[i].num = -0x7F00 -1; si_test[i].expected = "-32513";
i++; si_test[i].num = -0x07F0 -1; si_test[i].expected = "-2033";
i++; si_test[i].num = -0x007F -1; si_test[i].expected = "-128";
i++; si_test[i].num = -0x7000 -1; si_test[i].expected = "-28673";
i++; si_test[i].num = -0x0700 -1; si_test[i].expected = "-1793";
i++; si_test[i].num = -0x0070 -1; si_test[i].expected = "-113";
i++; si_test[i].num = -0x0007 -1; si_test[i].expected = "-8";
i++; si_test[i].num = -0x5000 -1; si_test[i].expected = "-20481";
i++; si_test[i].num = -0x0500 -1; si_test[i].expected = "-1281";
i++; si_test[i].num = -0x0050 -1; si_test[i].expected = "-81";
i++; si_test[i].num = -0x0005 -1; si_test[i].expected = "-6";
i++; si_test[i].num = 0x0000 -1; si_test[i].expected = "-1";
num_sint_tests = i;
#elif (SIZEOF_INT == 4)
i = 1; si_test[i].num = 0x7FFFFFFF; si_test[i].expected = "2147483647";
i++; si_test[i].num = 0x7FFFFFFE; si_test[i].expected = "2147483646";
i++; si_test[i].num = 0x7FFFFFFD; si_test[i].expected = "2147483645";
i++; si_test[i].num = 0x7FFF0000; si_test[i].expected = "2147418112";
i++; si_test[i].num = 0x00007FFF; si_test[i].expected = "32767";
i++; si_test[i].num = 0x7F000000; si_test[i].expected = "2130706432";
i++; si_test[i].num = 0x007F0000; si_test[i].expected = "8323072";
i++; si_test[i].num = 0x00007F00; si_test[i].expected = "32512";
i++; si_test[i].num = 0x0000007F; si_test[i].expected = "127";
i++; si_test[i].num = 0x70000000; si_test[i].expected = "1879048192";
i++; si_test[i].num = 0x07000000; si_test[i].expected = "117440512";
i++; si_test[i].num = 0x00700000; si_test[i].expected = "7340032";
i++; si_test[i].num = 0x00070000; si_test[i].expected = "458752";
i++; si_test[i].num = 0x00007000; si_test[i].expected = "28672";
i++; si_test[i].num = 0x00000700; si_test[i].expected = "1792";
i++; si_test[i].num = 0x00000070; si_test[i].expected = "112";
i++; si_test[i].num = 0x00000007; si_test[i].expected = "7";
i++; si_test[i].num = 0x50000000; si_test[i].expected = "1342177280";
i++; si_test[i].num = 0x05000000; si_test[i].expected = "83886080";
i++; si_test[i].num = 0x00500000; si_test[i].expected = "5242880";
i++; si_test[i].num = 0x00050000; si_test[i].expected = "327680";
i++; si_test[i].num = 0x00005000; si_test[i].expected = "20480";
i++; si_test[i].num = 0x00000500; si_test[i].expected = "1280";
i++; si_test[i].num = 0x00000050; si_test[i].expected = "80";
i++; si_test[i].num = 0x00000005; si_test[i].expected = "5";
i++; si_test[i].num = 0x00000001; si_test[i].expected = "1";
i++; si_test[i].num = 0x00000000; si_test[i].expected = "0";
i++; si_test[i].num = -0x7FFFFFFF -1; si_test[i].expected = "-2147483648";
i++; si_test[i].num = -0x7FFFFFFE -1; si_test[i].expected = "-2147483647";
i++; si_test[i].num = -0x7FFFFFFD -1; si_test[i].expected = "-2147483646";
i++; si_test[i].num = -0x7FFF0000 -1; si_test[i].expected = "-2147418113";
i++; si_test[i].num = -0x00007FFF -1; si_test[i].expected = "-32768";
i++; si_test[i].num = -0x7F000000 -1; si_test[i].expected = "-2130706433";
i++; si_test[i].num = -0x007F0000 -1; si_test[i].expected = "-8323073";
i++; si_test[i].num = -0x00007F00 -1; si_test[i].expected = "-32513";
i++; si_test[i].num = -0x0000007F -1; si_test[i].expected = "-128";
i++; si_test[i].num = -0x70000000 -1; si_test[i].expected = "-1879048193";
i++; si_test[i].num = -0x07000000 -1; si_test[i].expected = "-117440513";
i++; si_test[i].num = -0x00700000 -1; si_test[i].expected = "-7340033";
i++; si_test[i].num = -0x00070000 -1; si_test[i].expected = "-458753";
i++; si_test[i].num = -0x00007000 -1; si_test[i].expected = "-28673";
i++; si_test[i].num = -0x00000700 -1; si_test[i].expected = "-1793";
i++; si_test[i].num = -0x00000070 -1; si_test[i].expected = "-113";
i++; si_test[i].num = -0x00000007 -1; si_test[i].expected = "-8";
i++; si_test[i].num = -0x50000000 -1; si_test[i].expected = "-1342177281";
i++; si_test[i].num = -0x05000000 -1; si_test[i].expected = "-83886081";
i++; si_test[i].num = -0x00500000 -1; si_test[i].expected = "-5242881";
i++; si_test[i].num = -0x00050000 -1; si_test[i].expected = "-327681";
i++; si_test[i].num = -0x00005000 -1; si_test[i].expected = "-20481";
i++; si_test[i].num = -0x00000500 -1; si_test[i].expected = "-1281";
i++; si_test[i].num = -0x00000050 -1; si_test[i].expected = "-81";
i++; si_test[i].num = -0x00000005 -1; si_test[i].expected = "-6";
i++; si_test[i].num = 0x00000000 -1; si_test[i].expected = "-1";
num_sint_tests = i;
#elif (SIZEOF_INT == 8)
i = 1; si_test[i].num = 0x7FFFFFFFFFFFFFFF; si_test[i].expected = "9223372036854775807";
i++; si_test[i].num = 0x7FFFFFFFFFFFFFFE; si_test[i].expected = "9223372036854775806";
i++; si_test[i].num = 0x7FFFFFFFFFFFFFFD; si_test[i].expected = "9223372036854775805";
i++; si_test[i].num = 0x7FFFFFFF00000000; si_test[i].expected = "9223372032559808512";
i++; si_test[i].num = 0x000000007FFFFFFF; si_test[i].expected = "2147483647";
i++; si_test[i].num = 0x7FFF000000000000; si_test[i].expected = "9223090561878065152";
i++; si_test[i].num = 0x00007FFF00000000; si_test[i].expected = "140733193388032";
i++; si_test[i].num = 0x000000007FFF0000; si_test[i].expected = "2147418112";
i++; si_test[i].num = 0x0000000000007FFF; si_test[i].expected = "32767";
i++; si_test[i].num = 0x7F00000000000000; si_test[i].expected = "9151314442816847872";
i++; si_test[i].num = 0x007F000000000000; si_test[i].expected = "35747322042253312";
i++; si_test[i].num = 0x00007F0000000000; si_test[i].expected = "139637976727552";
i++; si_test[i].num = 0x0000007F00000000; si_test[i].expected = "545460846592";
i++; si_test[i].num = 0x000000007F000000; si_test[i].expected = "2130706432";
i++; si_test[i].num = 0x00000000007F0000; si_test[i].expected = "8323072";
i++; si_test[i].num = 0x0000000000007F00; si_test[i].expected = "32512";
i++; si_test[i].num = 0x000000000000007F; si_test[i].expected = "127";
i++; si_test[i].num = 0x7000000000000000; si_test[i].expected = "8070450532247928832";
i++; si_test[i].num = 0x0700000000000000; si_test[i].expected = "504403158265495552";
i++; si_test[i].num = 0x0070000000000000; si_test[i].expected = "31525197391593472";
i++; si_test[i].num = 0x0007000000000000; si_test[i].expected = "1970324836974592";
i++; si_test[i].num = 0x0000700000000000; si_test[i].expected = "123145302310912";
i++; si_test[i].num = 0x0000070000000000; si_test[i].expected = "7696581394432";
i++; si_test[i].num = 0x0000007000000000; si_test[i].expected = "481036337152";
i++; si_test[i].num = 0x0000000700000000; si_test[i].expected = "30064771072";
i++; si_test[i].num = 0x0000000070000000; si_test[i].expected = "1879048192";
i++; si_test[i].num = 0x0000000007000000; si_test[i].expected = "117440512";
i++; si_test[i].num = 0x0000000000700000; si_test[i].expected = "7340032";
i++; si_test[i].num = 0x0000000000070000; si_test[i].expected = "458752";
i++; si_test[i].num = 0x0000000000007000; si_test[i].expected = "28672";
i++; si_test[i].num = 0x0000000000000700; si_test[i].expected = "1792";
i++; si_test[i].num = 0x0000000000000070; si_test[i].expected = "112";
i++; si_test[i].num = 0x0000000000000007; si_test[i].expected = "7";
i++; si_test[i].num = 0x0000000000000001; si_test[i].expected = "1";
i++; si_test[i].num = 0x0000000000000000; si_test[i].expected = "0";
i++; si_test[i].num = -0x7FFFFFFFFFFFFFFF -1; si_test[i].expected = "-9223372036854775808";
i++; si_test[i].num = -0x7FFFFFFFFFFFFFFE -1; si_test[i].expected = "-9223372036854775807";
i++; si_test[i].num = -0x7FFFFFFFFFFFFFFD -1; si_test[i].expected = "-9223372036854775806";
i++; si_test[i].num = -0x7FFFFFFF00000000 -1; si_test[i].expected = "-9223372032559808513";
i++; si_test[i].num = -0x000000007FFFFFFF -1; si_test[i].expected = "-2147483648";
i++; si_test[i].num = -0x7FFF000000000000 -1; si_test[i].expected = "-9223090561878065153";
i++; si_test[i].num = -0x00007FFF00000000 -1; si_test[i].expected = "-140733193388033";
i++; si_test[i].num = -0x000000007FFF0000 -1; si_test[i].expected = "-2147418113";
i++; si_test[i].num = -0x0000000000007FFF -1; si_test[i].expected = "-32768";
i++; si_test[i].num = -0x7F00000000000000 -1; si_test[i].expected = "-9151314442816847873";
i++; si_test[i].num = -0x007F000000000000 -1; si_test[i].expected = "-35747322042253313";
i++; si_test[i].num = -0x00007F0000000000 -1; si_test[i].expected = "-139637976727553";
i++; si_test[i].num = -0x0000007F00000000 -1; si_test[i].expected = "-545460846593";
i++; si_test[i].num = -0x000000007F000000 -1; si_test[i].expected = "-2130706433";
i++; si_test[i].num = -0x00000000007F0000 -1; si_test[i].expected = "-8323073";
i++; si_test[i].num = -0x0000000000007F00 -1; si_test[i].expected = "-32513";
i++; si_test[i].num = -0x000000000000007F -1; si_test[i].expected = "-128";
i++; si_test[i].num = -0x7000000000000000 -1; si_test[i].expected = "-8070450532247928833";
i++; si_test[i].num = -0x0700000000000000 -1; si_test[i].expected = "-504403158265495553";
i++; si_test[i].num = -0x0070000000000000 -1; si_test[i].expected = "-31525197391593473";
i++; si_test[i].num = -0x0007000000000000 -1; si_test[i].expected = "-1970324836974593";
i++; si_test[i].num = -0x0000700000000000 -1; si_test[i].expected = "-123145302310913";
i++; si_test[i].num = -0x0000070000000000 -1; si_test[i].expected = "-7696581394433";
i++; si_test[i].num = -0x0000007000000000 -1; si_test[i].expected = "-481036337153";
i++; si_test[i].num = -0x0000000700000000 -1; si_test[i].expected = "-30064771073";
i++; si_test[i].num = -0x0000000070000000 -1; si_test[i].expected = "-1879048193";
i++; si_test[i].num = -0x0000000007000000 -1; si_test[i].expected = "-117440513";
i++; si_test[i].num = -0x0000000000700000 -1; si_test[i].expected = "-7340033";
i++; si_test[i].num = -0x0000000000070000 -1; si_test[i].expected = "-458753";
i++; si_test[i].num = -0x0000000000007000 -1; si_test[i].expected = "-28673";
i++; si_test[i].num = -0x0000000000000700 -1; si_test[i].expected = "-1793";
i++; si_test[i].num = -0x0000000000000070 -1; si_test[i].expected = "-113";
i++; si_test[i].num = -0x0000000000000007 -1; si_test[i].expected = "-8";
i++; si_test[i].num = 0x0000000000000000 -1; si_test[i].expected = "-1";
num_sint_tests = i;
#endif
for(i = 1; i <= num_sint_tests; i++) {
for(j = 0; j<BUFSZ; j++)
si_test[i].result[j] = 'X';
si_test[i].result[BUFSZ-1] = '\0';
(void)curl_msprintf(si_test[i].result, "%d", si_test[i].num);
if(memcmp(si_test[i].result,
si_test[i].expected,
strlen(si_test[i].expected))) {
printf("signed int test #%.2d: Failed (Expected: %s Got: %s)\n",
i, si_test[i].expected, si_test[i].result);
failed++;
}
}
if(!failed)
printf("All curl_mprintf() signed int tests OK!\n");
else
printf("Some curl_mprintf() signed int tests Failed!\n");
return failed;
}
static int test_unsigned_long_formatting(void)
{
int i, j;
int num_ulong_tests = 0;
int failed = 0;
#if (SIZEOF_LONG == 2)
i = 1; ul_test[i].num = 0xFFFFUL; ul_test[i].expected = "65535";
i++; ul_test[i].num = 0xFF00UL; ul_test[i].expected = "65280";
i++; ul_test[i].num = 0x00FFUL; ul_test[i].expected = "255";
i++; ul_test[i].num = 0xF000UL; ul_test[i].expected = "61440";
i++; ul_test[i].num = 0x0F00UL; ul_test[i].expected = "3840";
i++; ul_test[i].num = 0x00F0UL; ul_test[i].expected = "240";
i++; ul_test[i].num = 0x000FUL; ul_test[i].expected = "15";
i++; ul_test[i].num = 0xC000UL; ul_test[i].expected = "49152";
i++; ul_test[i].num = 0x0C00UL; ul_test[i].expected = "3072";
i++; ul_test[i].num = 0x00C0UL; ul_test[i].expected = "192";
i++; ul_test[i].num = 0x000CUL; ul_test[i].expected = "12";
i++; ul_test[i].num = 0x0001UL; ul_test[i].expected = "1";
i++; ul_test[i].num = 0x0000UL; ul_test[i].expected = "0";
num_ulong_tests = i;
#elif (SIZEOF_LONG == 4)
i = 1; ul_test[i].num = 0xFFFFFFFFUL; ul_test[i].expected = "4294967295";
i++; ul_test[i].num = 0xFFFF0000UL; ul_test[i].expected = "4294901760";
i++; ul_test[i].num = 0x0000FFFFUL; ul_test[i].expected = "65535";
i++; ul_test[i].num = 0xFF000000UL; ul_test[i].expected = "4278190080";
i++; ul_test[i].num = 0x00FF0000UL; ul_test[i].expected = "16711680";
i++; ul_test[i].num = 0x0000FF00UL; ul_test[i].expected = "65280";
i++; ul_test[i].num = 0x000000FFUL; ul_test[i].expected = "255";
i++; ul_test[i].num = 0xF0000000UL; ul_test[i].expected = "4026531840";
i++; ul_test[i].num = 0x0F000000UL; ul_test[i].expected = "251658240";
i++; ul_test[i].num = 0x00F00000UL; ul_test[i].expected = "15728640";
i++; ul_test[i].num = 0x000F0000UL; ul_test[i].expected = "983040";
i++; ul_test[i].num = 0x0000F000UL; ul_test[i].expected = "61440";
i++; ul_test[i].num = 0x00000F00UL; ul_test[i].expected = "3840";
i++; ul_test[i].num = 0x000000F0UL; ul_test[i].expected = "240";
i++; ul_test[i].num = 0x0000000FUL; ul_test[i].expected = "15";
i++; ul_test[i].num = 0xC0000000UL; ul_test[i].expected = "3221225472";
i++; ul_test[i].num = 0x0C000000UL; ul_test[i].expected = "201326592";
i++; ul_test[i].num = 0x00C00000UL; ul_test[i].expected = "12582912";
i++; ul_test[i].num = 0x000C0000UL; ul_test[i].expected = "786432";
i++; ul_test[i].num = 0x0000C000UL; ul_test[i].expected = "49152";
i++; ul_test[i].num = 0x00000C00UL; ul_test[i].expected = "3072";
i++; ul_test[i].num = 0x000000C0UL; ul_test[i].expected = "192";
i++; ul_test[i].num = 0x0000000CUL; ul_test[i].expected = "12";
i++; ul_test[i].num = 0x00000001UL; ul_test[i].expected = "1";
i++; ul_test[i].num = 0x00000000UL; ul_test[i].expected = "0";
num_ulong_tests = i;
#elif (SIZEOF_LONG == 8)
i = 1; ul_test[i].num = 0xFFFFFFFFFFFFFFFFUL; ul_test[i].expected = "18446744073709551615";
i++; ul_test[i].num = 0xFFFFFFFF00000000UL; ul_test[i].expected = "18446744069414584320";
i++; ul_test[i].num = 0x00000000FFFFFFFFUL; ul_test[i].expected = "4294967295";
i++; ul_test[i].num = 0xFFFF000000000000UL; ul_test[i].expected = "18446462598732840960";
i++; ul_test[i].num = 0x0000FFFF00000000UL; ul_test[i].expected = "281470681743360";
i++; ul_test[i].num = 0x00000000FFFF0000UL; ul_test[i].expected = "4294901760";
i++; ul_test[i].num = 0x000000000000FFFFUL; ul_test[i].expected = "65535";
i++; ul_test[i].num = 0xFF00000000000000UL; ul_test[i].expected = "18374686479671623680";
i++; ul_test[i].num = 0x00FF000000000000UL; ul_test[i].expected = "71776119061217280";
i++; ul_test[i].num = 0x0000FF0000000000UL; ul_test[i].expected = "280375465082880";
i++; ul_test[i].num = 0x000000FF00000000UL; ul_test[i].expected = "1095216660480";
i++; ul_test[i].num = 0x00000000FF000000UL; ul_test[i].expected = "4278190080";
i++; ul_test[i].num = 0x0000000000FF0000UL; ul_test[i].expected = "16711680";
i++; ul_test[i].num = 0x000000000000FF00UL; ul_test[i].expected = "65280";
i++; ul_test[i].num = 0x00000000000000FFUL; ul_test[i].expected = "255";
i++; ul_test[i].num = 0xF000000000000000UL; ul_test[i].expected = "17293822569102704640";
i++; ul_test[i].num = 0x0F00000000000000UL; ul_test[i].expected = "1080863910568919040";
i++; ul_test[i].num = 0x00F0000000000000UL; ul_test[i].expected = "67553994410557440";
i++; ul_test[i].num = 0x000F000000000000UL; ul_test[i].expected = "4222124650659840";
i++; ul_test[i].num = 0x0000F00000000000UL; ul_test[i].expected = "263882790666240";
i++; ul_test[i].num = 0x00000F0000000000UL; ul_test[i].expected = "16492674416640";
i++; ul_test[i].num = 0x000000F000000000UL; ul_test[i].expected = "1030792151040";
i++; ul_test[i].num = 0x0000000F00000000UL; ul_test[i].expected = "64424509440";
i++; ul_test[i].num = 0x00000000F0000000UL; ul_test[i].expected = "4026531840";
i++; ul_test[i].num = 0x000000000F000000UL; ul_test[i].expected = "251658240";
i++; ul_test[i].num = 0x0000000000F00000UL; ul_test[i].expected = "15728640";
i++; ul_test[i].num = 0x00000000000F0000UL; ul_test[i].expected = "983040";
i++; ul_test[i].num = 0x000000000000F000UL; ul_test[i].expected = "61440";
i++; ul_test[i].num = 0x0000000000000F00UL; ul_test[i].expected = "3840";
i++; ul_test[i].num = 0x00000000000000F0UL; ul_test[i].expected = "240";
i++; ul_test[i].num = 0x000000000000000FUL; ul_test[i].expected = "15";
i++; ul_test[i].num = 0xC000000000000000UL; ul_test[i].expected = "13835058055282163712";
i++; ul_test[i].num = 0x0C00000000000000UL; ul_test[i].expected = "864691128455135232";
i++; ul_test[i].num = 0x00C0000000000000UL; ul_test[i].expected = "54043195528445952";
i++; ul_test[i].num = 0x000C000000000000UL; ul_test[i].expected = "3377699720527872";
i++; ul_test[i].num = 0x0000C00000000000UL; ul_test[i].expected = "211106232532992";
i++; ul_test[i].num = 0x00000C0000000000UL; ul_test[i].expected = "13194139533312";
i++; ul_test[i].num = 0x000000C000000000UL; ul_test[i].expected = "824633720832";
i++; ul_test[i].num = 0x0000000C00000000UL; ul_test[i].expected = "51539607552";
i++; ul_test[i].num = 0x00000000C0000000UL; ul_test[i].expected = "3221225472";
i++; ul_test[i].num = 0x000000000C000000UL; ul_test[i].expected = "201326592";
i++; ul_test[i].num = 0x0000000000C00000UL; ul_test[i].expected = "12582912";
i++; ul_test[i].num = 0x00000000000C0000UL; ul_test[i].expected = "786432";
i++; ul_test[i].num = 0x000000000000C000UL; ul_test[i].expected = "49152";
i++; ul_test[i].num = 0x0000000000000C00UL; ul_test[i].expected = "3072";
i++; ul_test[i].num = 0x00000000000000C0UL; ul_test[i].expected = "192";
i++; ul_test[i].num = 0x000000000000000CUL; ul_test[i].expected = "12";
i++; ul_test[i].num = 0x00000001UL; ul_test[i].expected = "1";
i++; ul_test[i].num = 0x00000000UL; ul_test[i].expected = "0";
num_ulong_tests = i;
#endif
for(i = 1; i <= num_ulong_tests; i++) {
for(j = 0; j<BUFSZ; j++)
ul_test[i].result[j] = 'X';
ul_test[i].result[BUFSZ-1] = '\0';
(void)curl_msprintf(ul_test[i].result, "%lu", ul_test[i].num);
if(memcmp(ul_test[i].result,
ul_test[i].expected,
strlen(ul_test[i].expected))) {
printf("unsigned long test #%.2d: Failed (Expected: %s Got: %s)\n",
i, ul_test[i].expected, ul_test[i].result);
failed++;
}
}
if(!failed)
printf("All curl_mprintf() unsigned long tests OK!\n");
else
printf("Some curl_mprintf() unsigned long tests Failed!\n");
return failed;
}
static int test_signed_long_formatting(void)
{
int i, j;
int num_slong_tests = 0;
int failed = 0;
#if (SIZEOF_LONG == 2)
i = 1; sl_test[i].num = 0x7FFFL; sl_test[i].expected = "32767";
i++; sl_test[i].num = 0x7FFEL; sl_test[i].expected = "32766";
i++; sl_test[i].num = 0x7FFDL; sl_test[i].expected = "32765";
i++; sl_test[i].num = 0x7F00L; sl_test[i].expected = "32512";
i++; sl_test[i].num = 0x07F0L; sl_test[i].expected = "2032";
i++; sl_test[i].num = 0x007FL; sl_test[i].expected = "127";
i++; sl_test[i].num = 0x7000L; sl_test[i].expected = "28672";
i++; sl_test[i].num = 0x0700L; sl_test[i].expected = "1792";
i++; sl_test[i].num = 0x0070L; sl_test[i].expected = "112";
i++; sl_test[i].num = 0x0007L; sl_test[i].expected = "7";
i++; sl_test[i].num = 0x5000L; sl_test[i].expected = "20480";
i++; sl_test[i].num = 0x0500L; sl_test[i].expected = "1280";
i++; sl_test[i].num = 0x0050L; sl_test[i].expected = "80";
i++; sl_test[i].num = 0x0005L; sl_test[i].expected = "5";
i++; sl_test[i].num = 0x0001L; sl_test[i].expected = "1";
i++; sl_test[i].num = 0x0000L; sl_test[i].expected = "0";
i++; sl_test[i].num = -0x7FFFL -1L; sl_test[i].expected = "-32768";
i++; sl_test[i].num = -0x7FFEL -1L; sl_test[i].expected = "-32767";
i++; sl_test[i].num = -0x7FFDL -1L; sl_test[i].expected = "-32766";
i++; sl_test[i].num = -0x7F00L -1L; sl_test[i].expected = "-32513";
i++; sl_test[i].num = -0x07F0L -1L; sl_test[i].expected = "-2033";
i++; sl_test[i].num = -0x007FL -1L; sl_test[i].expected = "-128";
i++; sl_test[i].num = -0x7000L -1L; sl_test[i].expected = "-28673";
i++; sl_test[i].num = -0x0700L -1L; sl_test[i].expected = "-1793";
i++; sl_test[i].num = -0x0070L -1L; sl_test[i].expected = "-113";
i++; sl_test[i].num = -0x0007L -1L; sl_test[i].expected = "-8";
i++; sl_test[i].num = -0x5000L -1L; sl_test[i].expected = "-20481";
i++; sl_test[i].num = -0x0500L -1L; sl_test[i].expected = "-1281";
i++; sl_test[i].num = -0x0050L -1L; sl_test[i].expected = "-81";
i++; sl_test[i].num = -0x0005L -1L; sl_test[i].expected = "-6";
i++; sl_test[i].num = 0x0000L -1L; sl_test[i].expected = "-1";
num_slong_tests = i;
#elif (SIZEOF_LONG == 4)
i = 1; sl_test[i].num = 0x7FFFFFFFL; sl_test[i].expected = "2147483647";
i++; sl_test[i].num = 0x7FFFFFFEL; sl_test[i].expected = "2147483646";
i++; sl_test[i].num = 0x7FFFFFFDL; sl_test[i].expected = "2147483645";
i++; sl_test[i].num = 0x7FFF0000L; sl_test[i].expected = "2147418112";
i++; sl_test[i].num = 0x00007FFFL; sl_test[i].expected = "32767";
i++; sl_test[i].num = 0x7F000000L; sl_test[i].expected = "2130706432";
i++; sl_test[i].num = 0x007F0000L; sl_test[i].expected = "8323072";
i++; sl_test[i].num = 0x00007F00L; sl_test[i].expected = "32512";
i++; sl_test[i].num = 0x0000007FL; sl_test[i].expected = "127";
i++; sl_test[i].num = 0x70000000L; sl_test[i].expected = "1879048192";
i++; sl_test[i].num = 0x07000000L; sl_test[i].expected = "117440512";
i++; sl_test[i].num = 0x00700000L; sl_test[i].expected = "7340032";
i++; sl_test[i].num = 0x00070000L; sl_test[i].expected = "458752";
i++; sl_test[i].num = 0x00007000L; sl_test[i].expected = "28672";
i++; sl_test[i].num = 0x00000700L; sl_test[i].expected = "1792";
i++; sl_test[i].num = 0x00000070L; sl_test[i].expected = "112";
i++; sl_test[i].num = 0x00000007L; sl_test[i].expected = "7";
i++; sl_test[i].num = 0x50000000L; sl_test[i].expected = "1342177280";
i++; sl_test[i].num = 0x05000000L; sl_test[i].expected = "83886080";
i++; sl_test[i].num = 0x00500000L; sl_test[i].expected = "5242880";
i++; sl_test[i].num = 0x00050000L; sl_test[i].expected = "327680";
i++; sl_test[i].num = 0x00005000L; sl_test[i].expected = "20480";
i++; sl_test[i].num = 0x00000500L; sl_test[i].expected = "1280";
i++; sl_test[i].num = 0x00000050L; sl_test[i].expected = "80";
i++; sl_test[i].num = 0x00000005L; sl_test[i].expected = "5";
i++; sl_test[i].num = 0x00000001L; sl_test[i].expected = "1";
i++; sl_test[i].num = 0x00000000L; sl_test[i].expected = "0";
i++; sl_test[i].num = -0x7FFFFFFFL -1L; sl_test[i].expected = "-2147483648";
i++; sl_test[i].num = -0x7FFFFFFEL -1L; sl_test[i].expected = "-2147483647";
i++; sl_test[i].num = -0x7FFFFFFDL -1L; sl_test[i].expected = "-2147483646";
i++; sl_test[i].num = -0x7FFF0000L -1L; sl_test[i].expected = "-2147418113";
i++; sl_test[i].num = -0x00007FFFL -1L; sl_test[i].expected = "-32768";
i++; sl_test[i].num = -0x7F000000L -1L; sl_test[i].expected = "-2130706433";
i++; sl_test[i].num = -0x007F0000L -1L; sl_test[i].expected = "-8323073";
i++; sl_test[i].num = -0x00007F00L -1L; sl_test[i].expected = "-32513";
i++; sl_test[i].num = -0x0000007FL -1L; sl_test[i].expected = "-128";
i++; sl_test[i].num = -0x70000000L -1L; sl_test[i].expected = "-1879048193";
i++; sl_test[i].num = -0x07000000L -1L; sl_test[i].expected = "-117440513";
i++; sl_test[i].num = -0x00700000L -1L; sl_test[i].expected = "-7340033";
i++; sl_test[i].num = -0x00070000L -1L; sl_test[i].expected = "-458753";
i++; sl_test[i].num = -0x00007000L -1L; sl_test[i].expected = "-28673";
i++; sl_test[i].num = -0x00000700L -1L; sl_test[i].expected = "-1793";
i++; sl_test[i].num = -0x00000070L -1L; sl_test[i].expected = "-113";
i++; sl_test[i].num = -0x00000007L -1L; sl_test[i].expected = "-8";
i++; sl_test[i].num = -0x50000000L -1L; sl_test[i].expected = "-1342177281";
i++; sl_test[i].num = -0x05000000L -1L; sl_test[i].expected = "-83886081";
i++; sl_test[i].num = -0x00500000L -1L; sl_test[i].expected = "-5242881";
i++; sl_test[i].num = -0x00050000L -1L; sl_test[i].expected = "-327681";
i++; sl_test[i].num = -0x00005000L -1L; sl_test[i].expected = "-20481";
i++; sl_test[i].num = -0x00000500L -1L; sl_test[i].expected = "-1281";
i++; sl_test[i].num = -0x00000050L -1L; sl_test[i].expected = "-81";
i++; sl_test[i].num = -0x00000005L -1L; sl_test[i].expected = "-6";
i++; sl_test[i].num = 0x00000000L -1L; sl_test[i].expected = "-1";
num_slong_tests = i;
#elif (SIZEOF_LONG == 8)
i = 1; sl_test[i].num = 0x7FFFFFFFFFFFFFFFL; sl_test[i].expected = "9223372036854775807";
i++; sl_test[i].num = 0x7FFFFFFFFFFFFFFEL; sl_test[i].expected = "9223372036854775806";
i++; sl_test[i].num = 0x7FFFFFFFFFFFFFFDL; sl_test[i].expected = "9223372036854775805";
i++; sl_test[i].num = 0x7FFFFFFF00000000L; sl_test[i].expected = "9223372032559808512";
i++; sl_test[i].num = 0x000000007FFFFFFFL; sl_test[i].expected = "2147483647";
i++; sl_test[i].num = 0x7FFF000000000000L; sl_test[i].expected = "9223090561878065152";
i++; sl_test[i].num = 0x00007FFF00000000L; sl_test[i].expected = "140733193388032";
i++; sl_test[i].num = 0x000000007FFF0000L; sl_test[i].expected = "2147418112";
i++; sl_test[i].num = 0x0000000000007FFFL; sl_test[i].expected = "32767";
i++; sl_test[i].num = 0x7F00000000000000L; sl_test[i].expected = "9151314442816847872";
i++; sl_test[i].num = 0x007F000000000000L; sl_test[i].expected = "35747322042253312";
i++; sl_test[i].num = 0x00007F0000000000L; sl_test[i].expected = "139637976727552";
i++; sl_test[i].num = 0x0000007F00000000L; sl_test[i].expected = "545460846592";
i++; sl_test[i].num = 0x000000007F000000L; sl_test[i].expected = "2130706432";
i++; sl_test[i].num = 0x00000000007F0000L; sl_test[i].expected = "8323072";
i++; sl_test[i].num = 0x0000000000007F00L; sl_test[i].expected = "32512";
i++; sl_test[i].num = 0x000000000000007FL; sl_test[i].expected = "127";
i++; sl_test[i].num = 0x7000000000000000L; sl_test[i].expected = "8070450532247928832";
i++; sl_test[i].num = 0x0700000000000000L; sl_test[i].expected = "504403158265495552";
i++; sl_test[i].num = 0x0070000000000000L; sl_test[i].expected = "31525197391593472";
i++; sl_test[i].num = 0x0007000000000000L; sl_test[i].expected = "1970324836974592";
i++; sl_test[i].num = 0x0000700000000000L; sl_test[i].expected = "123145302310912";
i++; sl_test[i].num = 0x0000070000000000L; sl_test[i].expected = "7696581394432";
i++; sl_test[i].num = 0x0000007000000000L; sl_test[i].expected = "481036337152";
i++; sl_test[i].num = 0x0000000700000000L; sl_test[i].expected = "30064771072";
i++; sl_test[i].num = 0x0000000070000000L; sl_test[i].expected = "1879048192";
i++; sl_test[i].num = 0x0000000007000000L; sl_test[i].expected = "117440512";
i++; sl_test[i].num = 0x0000000000700000L; sl_test[i].expected = "7340032";
i++; sl_test[i].num = 0x0000000000070000L; sl_test[i].expected = "458752";
i++; sl_test[i].num = 0x0000000000007000L; sl_test[i].expected = "28672";
i++; sl_test[i].num = 0x0000000000000700L; sl_test[i].expected = "1792";
i++; sl_test[i].num = 0x0000000000000070L; sl_test[i].expected = "112";
i++; sl_test[i].num = 0x0000000000000007L; sl_test[i].expected = "7";
i++; sl_test[i].num = 0x0000000000000001L; sl_test[i].expected = "1";
i++; sl_test[i].num = 0x0000000000000000L; sl_test[i].expected = "0";
i++; sl_test[i].num = -0x7FFFFFFFFFFFFFFFL -1L; sl_test[i].expected = "-9223372036854775808";
i++; sl_test[i].num = -0x7FFFFFFFFFFFFFFEL -1L; sl_test[i].expected = "-9223372036854775807";
i++; sl_test[i].num = -0x7FFFFFFFFFFFFFFDL -1L; sl_test[i].expected = "-9223372036854775806";
i++; sl_test[i].num = -0x7FFFFFFF00000000L -1L; sl_test[i].expected = "-9223372032559808513";
i++; sl_test[i].num = -0x000000007FFFFFFFL -1L; sl_test[i].expected = "-2147483648";
i++; sl_test[i].num = -0x7FFF000000000000L -1L; sl_test[i].expected = "-9223090561878065153";
i++; sl_test[i].num = -0x00007FFF00000000L -1L; sl_test[i].expected = "-140733193388033";
i++; sl_test[i].num = -0x000000007FFF0000L -1L; sl_test[i].expected = "-2147418113";
i++; sl_test[i].num = -0x0000000000007FFFL -1L; sl_test[i].expected = "-32768";
i++; sl_test[i].num = -0x7F00000000000000L -1L; sl_test[i].expected = "-9151314442816847873";
i++; sl_test[i].num = -0x007F000000000000L -1L; sl_test[i].expected = "-35747322042253313";
i++; sl_test[i].num = -0x00007F0000000000L -1L; sl_test[i].expected = "-139637976727553";
i++; sl_test[i].num = -0x0000007F00000000L -1L; sl_test[i].expected = "-545460846593";
i++; sl_test[i].num = -0x000000007F000000L -1L; sl_test[i].expected = "-2130706433";
i++; sl_test[i].num = -0x00000000007F0000L -1L; sl_test[i].expected = "-8323073";
i++; sl_test[i].num = -0x0000000000007F00L -1L; sl_test[i].expected = "-32513";
i++; sl_test[i].num = -0x000000000000007FL -1L; sl_test[i].expected = "-128";
i++; sl_test[i].num = -0x7000000000000000L -1L; sl_test[i].expected = "-8070450532247928833";
i++; sl_test[i].num = -0x0700000000000000L -1L; sl_test[i].expected = "-504403158265495553";
i++; sl_test[i].num = -0x0070000000000000L -1L; sl_test[i].expected = "-31525197391593473";
i++; sl_test[i].num = -0x0007000000000000L -1L; sl_test[i].expected = "-1970324836974593";
i++; sl_test[i].num = -0x0000700000000000L -1L; sl_test[i].expected = "-123145302310913";
i++; sl_test[i].num = -0x0000070000000000L -1L; sl_test[i].expected = "-7696581394433";
i++; sl_test[i].num = -0x0000007000000000L -1L; sl_test[i].expected = "-481036337153";
i++; sl_test[i].num = -0x0000000700000000L -1L; sl_test[i].expected = "-30064771073";
i++; sl_test[i].num = -0x0000000070000000L -1L; sl_test[i].expected = "-1879048193";
i++; sl_test[i].num = -0x0000000007000000L -1L; sl_test[i].expected = "-117440513";
i++; sl_test[i].num = -0x0000000000700000L -1L; sl_test[i].expected = "-7340033";
i++; sl_test[i].num = -0x0000000000070000L -1L; sl_test[i].expected = "-458753";
i++; sl_test[i].num = -0x0000000000007000L -1L; sl_test[i].expected = "-28673";
i++; sl_test[i].num = -0x0000000000000700L -1L; sl_test[i].expected = "-1793";
i++; sl_test[i].num = -0x0000000000000070L -1L; sl_test[i].expected = "-113";
i++; sl_test[i].num = -0x0000000000000007L -1L; sl_test[i].expected = "-8";
i++; sl_test[i].num = 0x0000000000000000L -1L; sl_test[i].expected = "-1";
num_slong_tests = i;
#endif
for(i = 1; i <= num_slong_tests; i++) {
for(j = 0; j<BUFSZ; j++)
sl_test[i].result[j] = 'X';
sl_test[i].result[BUFSZ-1] = '\0';
(void)curl_msprintf(sl_test[i].result, "%ld", sl_test[i].num);
if(memcmp(sl_test[i].result,
sl_test[i].expected,
strlen(sl_test[i].expected))) {
printf("signed long test #%.2d: Failed (Expected: %s Got: %s)\n",
i, sl_test[i].expected, sl_test[i].result);
failed++;
}
}
if(!failed)
printf("All curl_mprintf() signed long tests OK!\n");
else
printf("Some curl_mprintf() signed long tests Failed!\n");
return failed;
}
static int test_curl_off_t_formatting(void)
{
int i, j;
int num_cofft_tests = 0;
int failed = 0;
#if (SIZEOF_CURL_OFF_T == 2)
i = 1; co_test[i].num = MPRNT_OFF_T_C(0x7FFF); co_test[i].expected = "32767";
i++; co_test[i].num = MPRNT_OFF_T_C(0x7FFE); co_test[i].expected = "32766";
i++; co_test[i].num = MPRNT_OFF_T_C(0x7FFD); co_test[i].expected = "32765";
i++; co_test[i].num = MPRNT_OFF_T_C(0x7F00); co_test[i].expected = "32512";
i++; co_test[i].num = MPRNT_OFF_T_C(0x07F0); co_test[i].expected = "2032";
i++; co_test[i].num = MPRNT_OFF_T_C(0x007F); co_test[i].expected = "127";
i++; co_test[i].num = MPRNT_OFF_T_C(0x7000); co_test[i].expected = "28672";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0700); co_test[i].expected = "1792";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0070); co_test[i].expected = "112";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0007); co_test[i].expected = "7";
i++; co_test[i].num = MPRNT_OFF_T_C(0x5000); co_test[i].expected = "20480";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0500); co_test[i].expected = "1280";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0050); co_test[i].expected = "80";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0005); co_test[i].expected = "5";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0001); co_test[i].expected = "1";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0000); co_test[i].expected = "0";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFF) -MPRNT_OFF_T_C(1); co_test[i].expected = "-32768";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFE) -MPRNT_OFF_T_C(1); co_test[i].expected = "-32767";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFD) -MPRNT_OFF_T_C(1); co_test[i].expected = "-32766";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x7F00) -MPRNT_OFF_T_C(1); co_test[i].expected = "-32513";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x07F0) -MPRNT_OFF_T_C(1); co_test[i].expected = "-2033";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x007F) -MPRNT_OFF_T_C(1); co_test[i].expected = "-128";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x7000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-28673";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x0700) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1793";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x0070) -MPRNT_OFF_T_C(1); co_test[i].expected = "-113";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x0007) -MPRNT_OFF_T_C(1); co_test[i].expected = "-8";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x5000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-20481";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x0500) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1281";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x0050) -MPRNT_OFF_T_C(1); co_test[i].expected = "-81";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x0005) -MPRNT_OFF_T_C(1); co_test[i].expected = "-6";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1";
num_cofft_tests = i;
#elif (SIZEOF_CURL_OFF_T == 4)
i = 1; co_test[i].num = MPRNT_OFF_T_C(0x7FFFFFFF); co_test[i].expected = "2147483647";
i++; co_test[i].num = MPRNT_OFF_T_C(0x7FFFFFFE); co_test[i].expected = "2147483646";
i++; co_test[i].num = MPRNT_OFF_T_C(0x7FFFFFFD); co_test[i].expected = "2147483645";
i++; co_test[i].num = MPRNT_OFF_T_C(0x7FFF0000); co_test[i].expected = "2147418112";
i++; co_test[i].num = MPRNT_OFF_T_C(0x00007FFF); co_test[i].expected = "32767";
i++; co_test[i].num = MPRNT_OFF_T_C(0x7F000000); co_test[i].expected = "2130706432";
i++; co_test[i].num = MPRNT_OFF_T_C(0x007F0000); co_test[i].expected = "8323072";
i++; co_test[i].num = MPRNT_OFF_T_C(0x00007F00); co_test[i].expected = "32512";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0000007F); co_test[i].expected = "127";
i++; co_test[i].num = MPRNT_OFF_T_C(0x70000000); co_test[i].expected = "1879048192";
i++; co_test[i].num = MPRNT_OFF_T_C(0x07000000); co_test[i].expected = "117440512";
i++; co_test[i].num = MPRNT_OFF_T_C(0x00700000); co_test[i].expected = "7340032";
i++; co_test[i].num = MPRNT_OFF_T_C(0x00070000); co_test[i].expected = "458752";
i++; co_test[i].num = MPRNT_OFF_T_C(0x00007000); co_test[i].expected = "28672";
i++; co_test[i].num = MPRNT_OFF_T_C(0x00000700); co_test[i].expected = "1792";
i++; co_test[i].num = MPRNT_OFF_T_C(0x00000070); co_test[i].expected = "112";
i++; co_test[i].num = MPRNT_OFF_T_C(0x00000007); co_test[i].expected = "7";
i++; co_test[i].num = MPRNT_OFF_T_C(0x50000000); co_test[i].expected = "1342177280";
i++; co_test[i].num = MPRNT_OFF_T_C(0x05000000); co_test[i].expected = "83886080";
i++; co_test[i].num = MPRNT_OFF_T_C(0x00500000); co_test[i].expected = "5242880";
i++; co_test[i].num = MPRNT_OFF_T_C(0x00050000); co_test[i].expected = "327680";
i++; co_test[i].num = MPRNT_OFF_T_C(0x00005000); co_test[i].expected = "20480";
i++; co_test[i].num = MPRNT_OFF_T_C(0x00000500); co_test[i].expected = "1280";
i++; co_test[i].num = MPRNT_OFF_T_C(0x00000050); co_test[i].expected = "80";
i++; co_test[i].num = MPRNT_OFF_T_C(0x00000005); co_test[i].expected = "5";
i++; co_test[i].num = MPRNT_OFF_T_C(0x00000001); co_test[i].expected = "1";
i++; co_test[i].num = MPRNT_OFF_T_C(0x00000000); co_test[i].expected = "0";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFFFFFF) -MPRNT_OFF_T_C(1); co_test[i].expected = "-2147483648";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFFFFFE) -MPRNT_OFF_T_C(1); co_test[i].expected = "-2147483647";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFFFFFD) -MPRNT_OFF_T_C(1); co_test[i].expected = "-2147483646";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFF0000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-2147418113";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x00007FFF) -MPRNT_OFF_T_C(1); co_test[i].expected = "-32768";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x7F000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-2130706433";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x007F0000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-8323073";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x00007F00) -MPRNT_OFF_T_C(1); co_test[i].expected = "-32513";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000007F) -MPRNT_OFF_T_C(1); co_test[i].expected = "-128";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x70000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1879048193";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x07000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-117440513";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x00700000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-7340033";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x00070000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-458753";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x00007000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-28673";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x00000700) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1793";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x00000070) -MPRNT_OFF_T_C(1); co_test[i].expected = "-113";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x00000007) -MPRNT_OFF_T_C(1); co_test[i].expected = "-8";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x50000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1342177281";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x05000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-83886081";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x00500000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-5242881";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x00050000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-327681";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x00005000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-20481";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x00000500) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1281";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x00000050) -MPRNT_OFF_T_C(1); co_test[i].expected = "-81";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x00000005) -MPRNT_OFF_T_C(1); co_test[i].expected = "-6";
i++; co_test[i].num = MPRNT_OFF_T_C(0x00000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1";
num_cofft_tests = i;
#elif (SIZEOF_CURL_OFF_T == 8)
i = 1; co_test[i].num = MPRNT_OFF_T_C(0x7FFFFFFFFFFFFFFF); co_test[i].expected = "9223372036854775807";
i++; co_test[i].num = MPRNT_OFF_T_C(0x7FFFFFFFFFFFFFFE); co_test[i].expected = "9223372036854775806";
i++; co_test[i].num = MPRNT_OFF_T_C(0x7FFFFFFFFFFFFFFD); co_test[i].expected = "9223372036854775805";
i++; co_test[i].num = MPRNT_OFF_T_C(0x7FFFFFFF00000000); co_test[i].expected = "9223372032559808512";
i++; co_test[i].num = MPRNT_OFF_T_C(0x000000007FFFFFFF); co_test[i].expected = "2147483647";
i++; co_test[i].num = MPRNT_OFF_T_C(0x7FFF000000000000); co_test[i].expected = "9223090561878065152";
i++; co_test[i].num = MPRNT_OFF_T_C(0x00007FFF00000000); co_test[i].expected = "140733193388032";
i++; co_test[i].num = MPRNT_OFF_T_C(0x000000007FFF0000); co_test[i].expected = "2147418112";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000007FFF); co_test[i].expected = "32767";
i++; co_test[i].num = MPRNT_OFF_T_C(0x7F00000000000000); co_test[i].expected = "9151314442816847872";
i++; co_test[i].num = MPRNT_OFF_T_C(0x007F000000000000); co_test[i].expected = "35747322042253312";
i++; co_test[i].num = MPRNT_OFF_T_C(0x00007F0000000000); co_test[i].expected = "139637976727552";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0000007F00000000); co_test[i].expected = "545460846592";
i++; co_test[i].num = MPRNT_OFF_T_C(0x000000007F000000); co_test[i].expected = "2130706432";
i++; co_test[i].num = MPRNT_OFF_T_C(0x00000000007F0000); co_test[i].expected = "8323072";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000007F00); co_test[i].expected = "32512";
i++; co_test[i].num = MPRNT_OFF_T_C(0x000000000000007F); co_test[i].expected = "127";
i++; co_test[i].num = MPRNT_OFF_T_C(0x7000000000000000); co_test[i].expected = "8070450532247928832";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0700000000000000); co_test[i].expected = "504403158265495552";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0070000000000000); co_test[i].expected = "31525197391593472";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0007000000000000); co_test[i].expected = "1970324836974592";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0000700000000000); co_test[i].expected = "123145302310912";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0000070000000000); co_test[i].expected = "7696581394432";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0000007000000000); co_test[i].expected = "481036337152";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000700000000); co_test[i].expected = "30064771072";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000070000000); co_test[i].expected = "1879048192";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000007000000); co_test[i].expected = "117440512";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000700000); co_test[i].expected = "7340032";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000070000); co_test[i].expected = "458752";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000007000); co_test[i].expected = "28672";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000000700); co_test[i].expected = "1792";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000000070); co_test[i].expected = "112";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000000007); co_test[i].expected = "7";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000000001); co_test[i].expected = "1";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000000000); co_test[i].expected = "0";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFFFFFFFFFFFFFF) -MPRNT_OFF_T_C(1); co_test[i].expected = "-9223372036854775808";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFFFFFFFFFFFFFE) -MPRNT_OFF_T_C(1); co_test[i].expected = "-9223372036854775807";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFFFFFFFFFFFFFD) -MPRNT_OFF_T_C(1); co_test[i].expected = "-9223372036854775806";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFFFFFF00000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-9223372032559808513";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x000000007FFFFFFF) -MPRNT_OFF_T_C(1); co_test[i].expected = "-2147483648";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x7FFF000000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-9223090561878065153";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x00007FFF00000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-140733193388033";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x000000007FFF0000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-2147418113";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000000007FFF) -MPRNT_OFF_T_C(1); co_test[i].expected = "-32768";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x7F00000000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-9151314442816847873";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x007F000000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-35747322042253313";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x00007F0000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-139637976727553";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000007F00000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-545460846593";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x000000007F000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-2130706433";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x00000000007F0000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-8323073";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000000007F00) -MPRNT_OFF_T_C(1); co_test[i].expected = "-32513";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x000000000000007F) -MPRNT_OFF_T_C(1); co_test[i].expected = "-128";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x7000000000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-8070450532247928833";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x0700000000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-504403158265495553";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x0070000000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-31525197391593473";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x0007000000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1970324836974593";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000700000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-123145302310913";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000070000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-7696581394433";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000007000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-481036337153";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000700000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-30064771073";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000070000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1879048193";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000007000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-117440513";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000000700000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-7340033";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000000070000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-458753";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000000007000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-28673";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000000000700) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1793";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000000000070) -MPRNT_OFF_T_C(1); co_test[i].expected = "-113";
i++; co_test[i].num = -MPRNT_OFF_T_C(0x0000000000000007) -MPRNT_OFF_T_C(1); co_test[i].expected = "-8";
i++; co_test[i].num = MPRNT_OFF_T_C(0x0000000000000000) -MPRNT_OFF_T_C(1); co_test[i].expected = "-1";
num_cofft_tests = i;
#endif
for(i = 1; i <= num_cofft_tests; i++) {
for(j = 0; j<BUFSZ; j++)
co_test[i].result[j] = 'X';
co_test[i].result[BUFSZ-1] = '\0';
(void)curl_msprintf(co_test[i].result, "%" CURL_FORMAT_CURL_OFF_T,
co_test[i].num);
if(memcmp(co_test[i].result,
co_test[i].expected,
strlen(co_test[i].expected))) {
printf("curl_off_t test #%.2d: Failed (Expected: %s Got: %s)\n",
i, co_test[i].expected, co_test[i].result);
failed++;
}
}
if(!failed)
printf("All curl_mprintf() curl_off_t tests OK!\n");
else
printf("Some curl_mprintf() curl_off_t tests Failed!\n");
return failed;
}
static int _string_check(int linenumber, char *buf, const char *buf2)
{
if(strcmp(buf, buf2)) {
/* they shouldn't differ */
printf("sprintf line %d failed:\nwe '%s'\nsystem: '%s'\n",
linenumber, buf, buf2);
return 1;
}
return 0;
}
#define string_check(x,y) _string_check(__LINE__, x, y)
static int _strlen_check(int linenumber, char *buf, size_t len)
{
size_t buflen = strlen(buf);
if(len != buflen) {
/* they shouldn't differ */
printf("sprintf strlen:%d failed:\nwe '%zu'\nsystem: '%zu'\n",
linenumber, buflen, len);
return 1;
}
return 0;
}
#define strlen_check(x,y) _strlen_check(__LINE__, x, y)
/*
* The output strings in this test need to have been verified with a system
* sprintf() before used here.
*/
static int test_string_formatting(void)
{
int errors = 0;
char buf[256];
curl_msnprintf(buf, sizeof(buf), "%0*d%s", 2, 9, "foo");
errors += string_check(buf, "09foo");
curl_msnprintf(buf, sizeof(buf), "%*.*s", 5, 2, "foo");
errors += string_check(buf, " fo");
curl_msnprintf(buf, sizeof(buf), "%*.*s", 2, 5, "foo");
errors += string_check(buf, "foo");
curl_msnprintf(buf, sizeof(buf), "%*.*s", 0, 10, "foo");
errors += string_check(buf, "foo");
curl_msnprintf(buf, sizeof(buf), "%-10s", "foo");
errors += string_check(buf, "foo ");
curl_msnprintf(buf, sizeof(buf), "%10s", "foo");
errors += string_check(buf, " foo");
curl_msnprintf(buf, sizeof(buf), "%*.*s", -10, -10, "foo");
errors += string_check(buf, "foo ");
if(!errors)
printf("All curl_mprintf() strings tests OK!\n");
else
printf("Some curl_mprintf() string tests Failed!\n");
return errors;
}
static int test_weird_arguments(void)
{
int errors = 0;
char buf[256];
int rc;
/* MAX_PARAMETERS is 128, try exact 128! */
rc = curl_msnprintf(buf, sizeof(buf),
"%d%d%d%d%d%d%d%d%d%d" /* 10 */
"%d%d%d%d%d%d%d%d%d%d" /* 10 1 */
"%d%d%d%d%d%d%d%d%d%d" /* 10 2 */
"%d%d%d%d%d%d%d%d%d%d" /* 10 3 */
"%d%d%d%d%d%d%d%d%d%d" /* 10 4 */
"%d%d%d%d%d%d%d%d%d%d" /* 10 5 */
"%d%d%d%d%d%d%d%d%d%d" /* 10 6 */
"%d%d%d%d%d%d%d%d%d%d" /* 10 7 */
"%d%d%d%d%d%d%d%d%d%d" /* 10 8 */
"%d%d%d%d%d%d%d%d%d%d" /* 10 9 */
"%d%d%d%d%d%d%d%d%d%d" /* 10 10 */
"%d%d%d%d%d%d%d%d%d%d" /* 10 11 */
"%d%d%d%d%d%d%d%d" /* 8 */
,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 1 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 2 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 3 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 4 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 5 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 6 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 7 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 8 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 9 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 10 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 11 */
0, 1, 2, 3, 4, 5, 6, 7); /* 8 */
if(rc != 128) {
printf("curl_mprintf() returned %d and not 128!\n", rc);
errors++;
}
errors += string_check(buf,
"0123456789" /* 10 */
"0123456789" /* 10 1 */
"0123456789" /* 10 2 */
"0123456789" /* 10 3 */
"0123456789" /* 10 4 */
"0123456789" /* 10 5 */
"0123456789" /* 10 6 */
"0123456789" /* 10 7 */
"0123456789" /* 10 8 */
"0123456789" /* 10 9 */
"0123456789" /* 10 10*/
"0123456789" /* 10 11 */
"01234567" /* 8 */
);
/* MAX_PARAMETERS is 128, try more! */
buf[0] = 0;
rc = curl_msnprintf(buf, sizeof(buf),
"%d%d%d%d%d%d%d%d%d%d" /* 10 */
"%d%d%d%d%d%d%d%d%d%d" /* 10 1 */
"%d%d%d%d%d%d%d%d%d%d" /* 10 2 */
"%d%d%d%d%d%d%d%d%d%d" /* 10 3 */
"%d%d%d%d%d%d%d%d%d%d" /* 10 4 */
"%d%d%d%d%d%d%d%d%d%d" /* 10 5 */
"%d%d%d%d%d%d%d%d%d%d" /* 10 6 */
"%d%d%d%d%d%d%d%d%d%d" /* 10 7 */
"%d%d%d%d%d%d%d%d%d%d" /* 10 8 */
"%d%d%d%d%d%d%d%d%d%d" /* 10 9 */
"%d%d%d%d%d%d%d%d%d%d" /* 10 10 */
"%d%d%d%d%d%d%d%d%d%d" /* 10 11 */
"%d%d%d%d%d%d%d%d%d" /* 9 */
,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 1 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 2 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 3 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 4 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 5 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 6 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 7 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 8 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 9 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 10 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* 10 11 */
0, 1, 2, 3, 4, 5, 6, 7, 8); /* 9 */
if(rc != -1) {
printf("curl_mprintf() returned %d and not -1!\n", rc);
errors++;
}
errors += string_check(buf, "");
/* Do not skip sanity checks with parameters! */
buf[0] = 0;
rc = curl_msnprintf(buf, sizeof(buf), "%d, %.*1$d", 500, 1);
if(rc != sizeof(buf) - 1) {
printf("curl_mprintf() returned %d and not %d!\n", rc,
sizeof(buf) - 1);
errors++;
}
errors += strlen_check(buf, 255);
if(errors)
printf("Some curl_mprintf() weird arguments tests failed!\n");
return errors;
}
/* DBL_MAX value from Linux */
#define MAXIMIZE -1.7976931348623157081452E+308
static int test_float_formatting(void)
{
int errors = 0;
char buf[512]; /* larger than max float size */
curl_msnprintf(buf, sizeof(buf), "%f", 9.0);
errors += string_check(buf, "9.000000");
curl_msnprintf(buf, sizeof(buf), "%.1f", 9.1);
errors += string_check(buf, "9.1");
curl_msnprintf(buf, sizeof(buf), "%.2f", 9.1);
errors += string_check(buf, "9.10");
curl_msnprintf(buf, sizeof(buf), "%.0f", 9.1);
errors += string_check(buf, "9");
curl_msnprintf(buf, sizeof(buf), "%0f", 9.1);
errors += string_check(buf, "9.100000");
curl_msnprintf(buf, sizeof(buf), "%10f", 9.1);
errors += string_check(buf, " 9.100000");
curl_msnprintf(buf, sizeof(buf), "%10.3f", 9.1);
errors += string_check(buf, " 9.100");
curl_msnprintf(buf, sizeof(buf), "%-10.3f", 9.1);
errors += string_check(buf, "9.100 ");
curl_msnprintf(buf, sizeof(buf), "%-10.3f", 9.123456);
errors += string_check(buf, "9.123 ");
curl_msnprintf(buf, sizeof(buf), "%.-2f", 9.1);
errors += string_check(buf, "9.100000");
curl_msnprintf(buf, sizeof(buf), "%*f", 10, 9.1);
errors += string_check(buf, " 9.100000");
curl_msnprintf(buf, sizeof(buf), "%*f", 3, 9.1);
errors += string_check(buf, "9.100000");
curl_msnprintf(buf, sizeof(buf), "%*f", 6, 9.2987654);
errors += string_check(buf, "9.298765");
curl_msnprintf(buf, sizeof(buf), "%*f", 6, 9.298765);
errors += string_check(buf, "9.298765");
curl_msnprintf(buf, sizeof(buf), "%*f", 6, 9.29876);
errors += string_check(buf, "9.298760");
curl_msnprintf(buf, sizeof(buf), "%.*f", 6, 9.2987654);
errors += string_check(buf, "9.298765");
curl_msnprintf(buf, sizeof(buf), "%.*f", 5, 9.2987654);
errors += string_check(buf, "9.29877");
curl_msnprintf(buf, sizeof(buf), "%.*f", 4, 9.2987654);
errors += string_check(buf, "9.2988");
curl_msnprintf(buf, sizeof(buf), "%.*f", 3, 9.2987654);
errors += string_check(buf, "9.299");
curl_msnprintf(buf, sizeof(buf), "%.*f", 2, 9.2987654);
errors += string_check(buf, "9.30");
curl_msnprintf(buf, sizeof(buf), "%.*f", 1, 9.2987654);
errors += string_check(buf, "9.3");
curl_msnprintf(buf, sizeof(buf), "%.*f", 0, 9.2987654);
errors += string_check(buf, "9");
/* very large precisions easily turn into system specific outputs so we only
check the output buffer length here as we know the internal limit */
curl_msnprintf(buf, sizeof(buf), "%.*f", (1<<30), 9.2987654);
errors += strlen_check(buf, 325);
curl_msnprintf(buf, sizeof(buf), "%10000.10000f", 9.2987654);
errors += strlen_check(buf, 325);
curl_msnprintf(buf, sizeof(buf), "%240.10000f",
123456789123456789123456789.2987654);
errors += strlen_check(buf, 325);
/* check negative when used signed */
curl_msnprintf(buf, sizeof(buf), "%*f", INT_MIN, 9.1);
errors += string_check(buf, "9.100000");
/* curl_msnprintf() limits a single float output to 325 bytes maximum
width */
curl_msnprintf(buf, sizeof(buf), "%*f", (1<<30), 9.1);
errors += string_check(buf, " 9.100000");
curl_msnprintf(buf, sizeof(buf), "%100000f", 9.1);
errors += string_check(buf, " 9.100000");
curl_msnprintf(buf, sizeof(buf), "%f", MAXIMIZE);
errors += strlen_check(buf, 317);
curl_msnprintf(buf, 2, "%f", MAXIMIZE);
errors += strlen_check(buf, 1);
curl_msnprintf(buf, 3, "%f", MAXIMIZE);
errors += strlen_check(buf, 2);
curl_msnprintf(buf, 4, "%f", MAXIMIZE);
errors += strlen_check(buf, 3);
curl_msnprintf(buf, 5, "%f", MAXIMIZE);
errors += strlen_check(buf, 4);
curl_msnprintf(buf, 6, "%f", MAXIMIZE);
errors += strlen_check(buf, 5);
if(!errors)
printf("All float strings tests OK!\n");
else
printf("test_float_formatting Failed!\n");
return errors;
}
/* !checksrc! enable LONGLINE */
static int test_return_codes(void)
{
char buf[128];
int rc;
rc = curl_msnprintf(buf, 100, "%d", 9999);
if(rc != 4)
return 1;
rc = curl_msnprintf(buf, 100, "%d", 99999);
if(rc != 5)
return 1;
/* returns the length excluding the nul byte */
rc = curl_msnprintf(buf, 5, "%d", 99999);
if(rc != 4)
return 1;
/* returns the length excluding the nul byte */
rc = curl_msnprintf(buf, 5, "%s", "helloooooooo");
if(rc != 4)
return 1;
/* returns the length excluding the nul byte */
rc = curl_msnprintf(buf, 6, "%s", "helloooooooo");
if(rc != 5)
return 1;
return 0;
}
int test(char *URL)
{
int errors = 0;
(void)URL; /* not used */
#ifdef HAVE_SETLOCALE
/*
* The test makes assumptions about the numeric locale (specifically,
* RADIXCHAR) so set it to a known working (and portable) one.
*/
setlocale(LC_NUMERIC, "C");
#endif
errors += test_weird_arguments();
errors += test_unsigned_short_formatting();
errors += test_signed_short_formatting();
errors += test_unsigned_int_formatting();
errors += test_signed_int_formatting();
errors += test_unsigned_long_formatting();
errors += test_signed_long_formatting();
errors += test_curl_off_t_formatting();
errors += test_string_formatting();
errors += test_float_formatting();
errors += test_return_codes();
if(errors)
return TEST_ERR_MAJOR_BAD;
else
return 0;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/testtrace.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "test.h"
#include "testutil.h"
#include "testtrace.h"
#include "memdebug.h"
struct libtest_trace_cfg libtest_debug_config;
static time_t epoch_offset; /* for test time tracing */
static int known_offset; /* for test time tracing */
static
void libtest_debug_dump(const char *timebuf, const char *text, FILE *stream,
const unsigned char *ptr, size_t size, int nohex)
{
size_t i;
size_t c;
unsigned int width = 0x10;
if(nohex)
/* without the hex output, we can fit more on screen */
width = 0x40;
fprintf(stream, "%s%s, %zu bytes (0x%zx)\n", timebuf, text,
size, size);
for(i = 0; i < size; i += width) {
fprintf(stream, "%04zx: ", i);
if(!nohex) {
/* hex not disabled, show it */
for(c = 0; c < width; c++)
if(i + c < size)
fprintf(stream, "%02x ", ptr[i + c]);
else
fputs(" ", stream);
}
for(c = 0; (c < width) && (i + c < size); c++) {
/* check for 0D0A; if found, skip past and start a new line of output */
if(nohex &&
(i + c + 1 < size) && (ptr[i + c] == 0x0D) &&
(ptr[i + c + 1] == 0x0A)) {
i += (c + 2 - width);
break;
}
fprintf(stream, "%c", ((ptr[i + c] >= 0x20) && (ptr[i + c] < 0x80)) ?
ptr[i + c] : '.');
/* check again for 0D0A, to avoid an extra \n if it's at width */
if(nohex &&
(i + c + 2 < size) && (ptr[i + c + 1] == 0x0D) &&
(ptr[i + c + 2] == 0x0A)) {
i += (c + 3 - width);
break;
}
}
fputc('\n', stream); /* newline */
}
fflush(stream);
}
int libtest_debug_cb(CURL *handle, curl_infotype type,
unsigned char *data, size_t size,
void *userp)
{
struct libtest_trace_cfg *trace_cfg = userp;
const char *text;
struct timeval tv;
char timebuf[20];
char *timestr;
time_t secs;
(void)handle;
timebuf[0] = '\0';
timestr = &timebuf[0];
if(trace_cfg->tracetime) {
struct tm *now;
tv = tutil_tvnow();
if(!known_offset) {
epoch_offset = time(NULL) - tv.tv_sec;
known_offset = 1;
}
secs = epoch_offset + tv.tv_sec;
now = localtime(&secs); /* not thread safe but we don't care */
msnprintf(timebuf, sizeof(timebuf), "%02d:%02d:%02d.%06ld ",
now->tm_hour, now->tm_min, now->tm_sec, (long)tv.tv_usec);
}
switch(type) {
case CURLINFO_TEXT:
fprintf(stderr, "%s== Info: %s", timestr, (char *)data);
/* FALLTHROUGH */
default: /* in case a new one is introduced to shock us */
return 0;
case CURLINFO_HEADER_OUT:
text = "=> Send header";
break;
case CURLINFO_DATA_OUT:
text = "=> Send data";
break;
case CURLINFO_SSL_DATA_OUT:
text = "=> Send SSL data";
break;
case CURLINFO_HEADER_IN:
text = "<= Recv header";
break;
case CURLINFO_DATA_IN:
text = "<= Recv data";
break;
case CURLINFO_SSL_DATA_IN:
text = "<= Recv SSL data";
break;
}
libtest_debug_dump(timebuf, text, stderr, data, size, trace_cfg->nohex);
return 0;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/lib1568.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "test.h"
#include "testtrace.h"
#include "memdebug.h"
int test(char *URL)
{
CURLcode ret;
CURL *hnd;
curl_global_init(CURL_GLOBAL_ALL);
hnd = curl_easy_init();
curl_easy_setopt(hnd, CURLOPT_URL, URL);
curl_easy_setopt(hnd, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(hnd, CURLOPT_HEADER, 1L);
curl_easy_setopt(hnd, CURLOPT_USERPWD, "testuser:testpass");
curl_easy_setopt(hnd, CURLOPT_USERAGENT, "lib1568");
curl_easy_setopt(hnd, CURLOPT_HTTPAUTH, (long)CURLAUTH_DIGEST);
curl_easy_setopt(hnd, CURLOPT_MAXREDIRS, 50L);
curl_easy_setopt(hnd, CURLOPT_PORT, (long)atoi(libtest_arg2));
ret = curl_easy_perform(hnd);
curl_easy_cleanup(hnd);
hnd = NULL;
curl_global_cleanup();
return (int)ret;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/lib1905.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 2019 - 2021, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "test.h"
#include "testutil.h"
#include "warnless.h"
#include "memdebug.h"
int test(char *URL)
{
CURLSH *sh = NULL;
CURL *ch = NULL;
int unfinished;
CURLM *cm;
curl_global_init(CURL_GLOBAL_ALL);
cm = curl_multi_init();
if(!cm) {
curl_global_cleanup();
return 1;
}
sh = curl_share_init();
if(!sh)
goto cleanup;
curl_share_setopt(sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);
curl_share_setopt(sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);
ch = curl_easy_init();
if(!ch)
goto cleanup;
curl_easy_setopt(ch, CURLOPT_SHARE, sh);
curl_easy_setopt(ch, CURLOPT_URL, URL);
curl_easy_setopt(ch, CURLOPT_COOKIEFILE, "log/cookies1905");
curl_easy_setopt(ch, CURLOPT_COOKIEJAR, "log/cookies1905");
curl_multi_add_handle(cm, ch);
unfinished = 1;
while(unfinished) {
int MAX = 0;
long max_tout;
fd_set R, W, E;
struct timeval timeout;
FD_ZERO(&R);
FD_ZERO(&W);
FD_ZERO(&E);
curl_multi_perform(cm, &unfinished);
curl_multi_fdset(cm, &R, &W, &E, &MAX);
curl_multi_timeout(cm, &max_tout);
if(max_tout > 0) {
timeout.tv_sec = max_tout / 1000;
timeout.tv_usec = (max_tout % 1000) * 1000;
}
else {
timeout.tv_sec = 0;
timeout.tv_usec = 1000;
}
select(MAX + 1, &R, &W, &E, &timeout);
}
curl_easy_setopt(ch, CURLOPT_COOKIELIST, "FLUSH");
curl_easy_setopt(ch, CURLOPT_SHARE, NULL);
curl_multi_remove_handle(cm, ch);
cleanup:
curl_easy_cleanup(ch);
curl_share_cleanup(sh);
curl_multi_cleanup(cm);
curl_global_cleanup();
return 0;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/lib1528.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "test.h"
#include "memdebug.h"
int test(char *URL)
{
CURL *curl = NULL;
CURLcode res = CURLE_FAILED_INIT;
/* http header list*/
struct curl_slist *hhl = NULL;
struct curl_slist *phl = NULL;
if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) {
fprintf(stderr, "curl_global_init() failed\n");
return TEST_ERR_MAJOR_BAD;
}
curl = curl_easy_init();
if(!curl) {
fprintf(stderr, "curl_easy_init() failed\n");
curl_global_cleanup();
return TEST_ERR_MAJOR_BAD;
}
hhl = curl_slist_append(hhl, "User-Agent: Http Agent");
phl = curl_slist_append(phl, "Proxy-User-Agent: Http Agent2");
if(!hhl) {
goto test_cleanup;
}
test_setopt(curl, CURLOPT_URL, URL);
test_setopt(curl, CURLOPT_PROXY, libtest_arg2);
test_setopt(curl, CURLOPT_HTTPHEADER, hhl);
test_setopt(curl, CURLOPT_PROXYHEADER, phl);
test_setopt(curl, CURLOPT_HEADEROPT, CURLHEADER_SEPARATE);
test_setopt(curl, CURLOPT_VERBOSE, 1L);
test_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
test_setopt(curl, CURLOPT_HEADER, 1L);
res = curl_easy_perform(curl);
test_cleanup:
curl_easy_cleanup(curl);
curl_slist_free_all(hhl);
curl_slist_free_all(phl);
curl_global_cleanup();
return (int)res;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/lib1907.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 2019 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "test.h"
#include "testutil.h"
#include "warnless.h"
#include "memdebug.h"
int test(char *URL)
{
char *url_after;
CURL *curl;
CURLcode curl_code;
char error_buffer[CURL_ERROR_SIZE] = "";
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, URL);
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, error_buffer);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_code = curl_easy_perform(curl);
if(!curl_code)
fprintf(stderr, "failure expected, "
"curl_easy_perform returned %ld: <%s>, <%s>\n",
(long) curl_code, curl_easy_strerror(curl_code), error_buffer);
/* print the used url */
if(!curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url_after))
printf("Effective URL: %s\n", url_after);
curl_easy_cleanup(curl);
curl_global_cleanup();
return 0;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/lib1551.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "test.h"
#include "memdebug.h"
#include <curl/multi.h>
int test(char *URL)
{
CURL *curl;
CURLcode res = CURLE_OK;
global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, URL);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
res = curl_easy_perform(curl);
fprintf(stderr, "****************************** Do it again\n");
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
curl_global_cleanup();
return (int)res;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/lib509.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "test.h"
#include <string.h>
/*
* This test uses these funny custom memory callbacks for the only purpose
* of verifying that curl_global_init_mem() functionality is present in
* libcurl and that it works unconditionally no matter how libcurl is built,
* nothing more.
*
* Do not include memdebug.h in this source file, and do not use directly
* memory related functions in this file except those used inside custom
* memory callbacks which should be calling 'the real thing'.
*/
static int seen;
static void *custom_calloc(size_t nmemb, size_t size)
{
seen++;
return (calloc)(nmemb, size);
}
static void *custom_malloc(size_t size)
{
seen++;
return (malloc)(size);
}
static char *custom_strdup(const char *ptr)
{
seen++;
return (strdup)(ptr);
}
static void *custom_realloc(void *ptr, size_t size)
{
seen++;
return (realloc)(ptr, size);
}
static void custom_free(void *ptr)
{
seen++;
(free)(ptr);
}
int test(char *URL)
{
unsigned char a[] = {0x2f, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
0x91, 0xa2, 0xb3, 0xc4, 0xd5, 0xe6, 0xf7};
CURLcode res;
CURL *curl;
int asize;
char *str = NULL;
(void)URL;
res = curl_global_init_mem(CURL_GLOBAL_ALL,
custom_malloc,
custom_free,
custom_realloc,
custom_strdup,
custom_calloc);
if(res != CURLE_OK) {
fprintf(stderr, "curl_global_init_mem() failed\n");
return TEST_ERR_MAJOR_BAD;
}
curl = curl_easy_init();
if(!curl) {
fprintf(stderr, "curl_easy_init() failed\n");
curl_global_cleanup();
return TEST_ERR_MAJOR_BAD;
}
test_setopt(curl, CURLOPT_USERAGENT, "test509"); /* uses strdup() */
asize = (int)sizeof(a);
str = curl_easy_escape(curl, (char *)a, asize); /* uses realloc() */
if(seen)
printf("Callbacks were invoked!\n");
test_cleanup:
if(str)
curl_free(str);
curl_easy_cleanup(curl);
curl_global_cleanup();
return (int)res;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/lib1500.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "test.h"
#include "testutil.h"
#include "warnless.h"
#include "memdebug.h"
#define TEST_HANG_TIMEOUT 60 * 1000
int test(char *URL)
{
CURL *curls = NULL;
CURLM *multi = NULL;
int still_running;
int i = TEST_ERR_FAILURE;
int res = 0;
CURLMsg *msg;
start_test_timing();
global_init(CURL_GLOBAL_ALL);
multi_init(multi);
easy_init(curls);
easy_setopt(curls, CURLOPT_URL, URL);
easy_setopt(curls, CURLOPT_HEADER, 1L);
multi_add_handle(multi, curls);
multi_perform(multi, &still_running);
abort_on_test_timeout();
while(still_running) {
int num;
res = curl_multi_wait(multi, NULL, 0, TEST_HANG_TIMEOUT, &num);
if(res != CURLM_OK) {
printf("curl_multi_wait() returned %d\n", res);
res = TEST_ERR_MAJOR_BAD;
goto test_cleanup;
}
abort_on_test_timeout();
multi_perform(multi, &still_running);
abort_on_test_timeout();
}
msg = curl_multi_info_read(multi, &still_running);
if(msg)
/* this should now contain a result code from the easy handle,
get it */
i = msg->data.result;
test_cleanup:
/* undocumented cleanup sequence - type UA */
curl_multi_cleanup(multi);
curl_easy_cleanup(curls);
curl_global_cleanup();
if(res)
i = res;
return i; /* return the final return code */
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/curl/tests | repos/gpt4all.zig/src/zig-libcurl/curl/tests/libtest/lib575.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2020, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "test.h"
#include <fcntl.h>
#include "testutil.h"
#include "warnless.h"
#include "memdebug.h"
#define TEST_HANG_TIMEOUT 60 * 1000
/* 3x download!
* 1. normal
* 2. dup handle
* 3. with multi interface
*/
int test(char *URL)
{
CURL *handle = NULL;
CURL *duphandle = NULL;
CURLM *mhandle = NULL;
int res = 0;
int still_running = 0;
start_test_timing();
global_init(CURL_GLOBAL_ALL);
easy_init(handle);
easy_setopt(handle, CURLOPT_URL, URL);
easy_setopt(handle, CURLOPT_WILDCARDMATCH, 1L);
easy_setopt(handle, CURLOPT_VERBOSE, 1L);
res = curl_easy_perform(handle);
if(res)
goto test_cleanup;
res = curl_easy_perform(handle);
if(res)
goto test_cleanup;
duphandle = curl_easy_duphandle(handle);
if(!duphandle)
goto test_cleanup;
curl_easy_cleanup(handle);
handle = duphandle;
multi_init(mhandle);
multi_add_handle(mhandle, handle);
multi_perform(mhandle, &still_running);
abort_on_test_timeout();
while(still_running) {
struct timeval timeout;
fd_set fdread;
fd_set fdwrite;
fd_set fdexcep;
int maxfd = -99;
timeout.tv_sec = 0;
timeout.tv_usec = 100000L; /* 100 ms */
FD_ZERO(&fdread);
FD_ZERO(&fdwrite);
FD_ZERO(&fdexcep);
multi_fdset(mhandle, &fdread, &fdwrite, &fdexcep, &maxfd);
/* At this point, maxfd is guaranteed to be greater or equal than -1. */
select_test(maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout);
abort_on_test_timeout();
multi_perform(mhandle, &still_running);
abort_on_test_timeout();
}
test_cleanup:
/* undocumented cleanup sequence - type UA */
curl_multi_cleanup(mhandle);
curl_easy_cleanup(handle);
curl_global_cleanup();
return res;
}
|
Subsets and Splits