Running Programs in MathGL - mathgl

I'm trying to run one of the examples using FLTK in Mathgl. While basic programs will compile without error, I seem to be getting a linker error when compiling FLTK_MathGL examples.
This is the error portion I get from my build log.
C:\mathgl-2.3\src\libmgl.dll.a C:\mathgl-2.3\widgets\libmgl-fltk.a -mwindows
obj\Release\main.o:main.cpp:(.text$_ZN7mglFLTK3RunEv[__ZN7mglFLTK3RunEv]+0x1): undefined reference to "_imp__mgl_fltk_run'
obj\Release\main.o:main.cpp:(.text$_ZN7mglFLTKC1EPFiP8mglGraphEPKc[__ZN7mglFLTKC1EPFiP8mglGraphEPKc]+0x39): undefined reference to "_imp___ZTV7mglFLTK'
c:/codeblocks/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: obj\Release\main.o: bad reloc address 0x39 in section ".text$_ZN7mglFLTKC1EPFiP8mglGraphEPKc[__ZN7mglFLTKC1EPFiP8mglGraphEPKc]'
c:/codeblocks/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: final link failed: Invalid operation
collect2.exe: error: ld returned 1 exit status
Process terminated with status 1 (0 minute(s), 3 second(s))
2 error(s), 0 warning(s) (0 minute(s), 3 second(s))
I'm not sure what else I can do. I have pasted the program below.
#define MGL_HAVE_FLTK
#include "mgl2/fltk.h"
//-----------------------------------------------------------------------------
#if defined(WIN32) || defined(_MSC_VER) || defined(__BORLANDC__)
#include <windows.h>
#else
#include <unistd.h>
#endif
void long_calculations() // just delay which correspond to simulate calculations
{
#if defined(WIN32) || defined(_MSC_VER) || defined(__BORLANDC__)
Sleep(1000);
#else
sleep(1); // which can be very long
#endif
}
//-----------------------------------------------------------------------------
#if defined(PTHREAD_SAMPLE1) // first variant of multi-threading usage of mglFLTK window
mglFLTK *gr=NULL;
void *calc(void *)
{
mglPoint pnt;
for(int i=0;i<10;i++) // do calculation
{
long_calculations(); // which can be very long
pnt = mglPoint(2*mgl_rnd()-1,2*mgl_rnd()-1);
if(gr)
{
gr->Clf(); // make new drawing
gr->Line(mglPoint(),pnt,"Ar2");
char str[10] = "i=0"; str[2] = '0'+i;
gr->Puts(mglPoint(),str);
gr->Update(); // update window
}
}
exit(0);
}
int main(int argc,char **argv)
{
static pthread_t thr;
pthread_create(&thr,0,calc,0);
pthread_detach(thr);
gr = new mglFLTK;
gr->Run(); return 0;
}
#elif defined(PTHREAD_SAMPLE2) // another variant of multi-threading usage of mglFLTK window. Work only if pthread was enabled for MathGL
mglPoint pnt; // some global variable for changeable data
int main(int argc,char **argv)
{
mglFLTK gr("test");
gr.RunThr(); // <-- need MathGL version which use pthread
for(int i=0;i<10;i++) // do calculation
{
long_calculations();// which can be very long
pnt = mglPoint(2*mgl_rnd()-1,2*mgl_rnd()-1);
gr.Clf(); // make new drawing
gr.Line(mglPoint(),pnt,"Ar2");
char str[10] = "i=0"; str[3] = '0'+i;
gr.Update(); // update window
}
return 0; // finish calculations and close the window
}
#else // just default samples
int test_wnd(mglGraph *gr);
int sample(mglGraph *gr);
int sample_1(mglGraph *gr);
int sample_2(mglGraph *gr);
int sample_3(mglGraph *gr);
int sample_d(mglGraph *gr);
//-----------------------------------------------------------------------------
int main(int argc,char **argv)
{
mglFLTK *gr;
char key = 0;
if(argc>1) key = argv[1][0]!='-' ? argv[1][0]:argv[1][1];
else printf("You may specify argument '1', '2', '3' or 'd' for viewing examples of 1d, 2d, 3d or dual plotting\n");
switch(key)
{
case '0': gr = new mglFLTK((mglDraw *)NULL,"1D plots"); break;
case '1': gr = new mglFLTK(sample_1,"1D plots"); break;
case '2': gr = new mglFLTK(sample_2,"2D plots"); break;
case '3': gr = new mglFLTK(sample_3,"3D plots"); break;
case 'd': gr = new mglFLTK(sample_d,"Dual plots");break;
case 't': gr = new mglFLTK(test_wnd,"Testing"); break;
default: gr = new mglFLTK(sample,"Drop and waves"); break;
}
if(key=='0')
{ gr->Rotate(40,60); gr->Box(); gr->Light(true); gr->FSurf("sin(4*pi*x*y)"); gr->Update(); }
gr->Run(); return 0;
}
#endif
//-----------------------------------------------------------------------------

Related

Pthreads based program crashing on MacOS doesn't crash on Linux

I have a pthreads based program with 3 threads that crashes on MacOS (Darwin Kernel Version 19.6.0) within a few seconds. I was expecting the same behavior on Linux. But the program doesn't crash on Linux. I am left speculating if Linux has a different thread scheduling policy or if it is something else. Any pointers appreciated.
This is the program. If I don't use pthread mutex lock in the printer thread, it is supposed to crash because the linked list is left in an inconsistent state.
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
#include "list.h"
#define RANGE_MIN 1
#define RANGE_MAX 10
pthread_t tid[3];
list_t list;
pthread_mutex_t queue_lock;
/* Return a uniformly random number in the range [low,high]. */
int random_range (unsigned const low, unsigned const high)
{
unsigned const range = high - low + 1;
return low + (int) (((double) range) * rand() / (RAND_MAX + 1.0));
}
/*
* consumer thread function
*/
void* consumer(void *arg)
{
static int val = 0;
while (1) {
//sleep(1);
pthread_mutex_lock(&queue_lock);
while (list.total_elem > 0)
consume_and_delete(&list);
pthread_mutex_unlock(&queue_lock);
}
}
void *producer(void *arg)
{
while (1) {
//sleep(1);
pthread_mutex_lock(&queue_lock);
while (list.total_elem < 10)
add_to_list(&list, random_range(RANGE_MIN, RANGE_MAX));
pthread_mutex_unlock(&queue_lock);
}
}
/*
* printer thread function
*/
void* printer(void *arg)
{
while (1) {
//pthread_mutex_lock(&queue_lock); //lines deliberately commented out to show the crash
print_list(&list);
//pthread_mutex_unlock(&queue_lock);
}
}
int main(void)
{
int ret;
if (pthread_mutex_init(&queue_lock, NULL) != 0) {
printf("\n mutex init failed\n");
return 1;
}
ret = pthread_create(&(tid[1]), NULL, &consumer, NULL);
if (ret != 0) {
printf("\ncan't create thread :[%s]", strerror(ret));
}
ret = pthread_create(&(tid[0]), NULL, &producer, NULL);
if (ret != 0) {
printf("\ncan't create thread :[%s]", strerror(ret));
}
ret = pthread_create(&(tid[2]), NULL, &printer, NULL);
if (ret != 0) {
printf("\ncan't create thread :[%s]", strerror(ret));
}
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
pthread_join(tid[2], NULL);
pthread_mutex_destroy(&queue_lock);
return 0;
}
For the sake of completeness, here is the code for list.h and list.c
ifndef __LIST_H__
#define __LIST_H__
typedef struct node_ {
int num;
struct node_ *next;
} node_t;
typedef struct list_ {
int total_elem;
node_t *head;
} list_t;
#define TRUE 1
#define FALSE 0
void add_to_list(list_t *list, int num);
node_t *allocate_new(int num);
void consume_and_delete(list_t *list);
void print_list(list_t *list);
#endif
list.c:
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
void add_to_list(list_t *list, int val)
{
node_t *tmp;
node_t *new;
new = allocate_new(val);
if (!new) {
printf("%s: allocation failure \n", __FUNCTION__);
}
printf("%s: Enqueueing %d\n", __FUNCTION__, new->num);
if (!list) {
return;
}
if (!list->head) {
list->total_elem++;
list->head = new;
return;
}
tmp = list->head;
while (tmp->next) {
tmp = tmp->next;
}
tmp->next = new;
list->total_elem++;
}
node_t *allocate_new(int num)
{
node_t *tmp;
tmp = malloc(sizeof(node_t));
if (!tmp) {
printf("%s: failed in malloc\n", __FUNCTION__);
return NULL;
}
tmp->num = num;
tmp->next = NULL;
return tmp;
}
/* reads from the front of the queue and deletes the element
*/
void consume_and_delete(list_t *list)
{
node_t *tmp, *next;
if (!list->head) {
return;
}
tmp = list->head;
next = tmp->next;
printf("%s: Dequeueing %d\n", __FUNCTION__,tmp->num);
list->head = next;
list->total_elem--;
free(tmp);
}
void print_list(list_t *list)
{
node_t *tmp;
if (!list->head) {
printf("%s: queue empty \n", __FUNCTION__);
}
tmp = list->head;
while (tmp) {
printf("%d ", tmp->num);
tmp = tmp->next;
}
printf("\n");
}
Makefile:
all: prodcon
prodcon: list.o prod_consume.o
gcc -g -o prodcon list.o prod_consume.o -lpthread
list.o: list.c list.h
gcc -g -c -o list.o list.c
prod_consume.o: prod_consume.c list.h
gcc -g -c -o prod_consume.o prod_consume.c
clean:
rm -f *.o ./prodcon
Note that if I un-comment pthread_mutex_lock and unlock calls in printer fn, the program runs without a crash on MacOS, as expected. But on Linux, even without un-commenting those lines in printer thread, it runs fine.
So my question. Is thread scheduling different in Linux. Or is is there some other reason?
Any reason the program runs fine on Linux, while it crahes on MacOS?
//lines deliberately commented out to show the crash
The print_list accesses the list without the lock; of course the code will intermittently crash, what did you expect?
on Linux, even without un-commenting those lines in printer thread, it runs fine.
It doesn't "run fine" -- it exercises undefined behavior, and will crash if you run enough times and the stars align to expose the data race.

trouble with pmi handle on windows 7

I am trying to set up performance monitorint interrupt on counter overflow to collect some information. For this I created driver. I skip some part of code that are irrelevant.
driver.c
extern VOID EnableReadPmc();
extern VOID PmiHandle();
extern VOID GetIdt(IDT_INFO *idt);
extern ULONG64 GetCs();
#pragma pack(2)
typedef struct {
USHORT Limit;
ULONG64 Base;
}IDT_INFO;
#pragma pack()
typedef struct _entry {
ULONG64 Low;
ULONG64 High;
} entry;
PHYSICAL_ADDRESS lvt_perf_count_reg = {0xfee00340, 0x00000000};
PVOID map_lvt_perf_count_reg = NULL;
PHYSICAL_ADDRESS eoi_register = {0xfee000b0, 0x00000000};
PVOID map_eoi_register = NULL;
NTSTATUS IoCtlDispatch(IN PDEVICE_OBJECT pDeviceObject, IN PIRP pIrp) {
ULONG32 set_lvt_perf_count_reg = 0x000000ee;
//idt
IDT_INFO idtr;
entry *idt = NULL;
entry tmp_gate;
ULONG64 func;
ULONG64 seg;
ULONG64 int_setting;
//ovf status value
ULONG64 ovf_status;
pIrpStack = IoGetCurrentIrpStackLocation(pIrp);
switch (pIrpStack->Parameters.DeviceIoControl.IoControlCode) {
case IOCTL_INTERRUPT_SETTING_UP:
//disable pmc and clear ovf
WriteMsr(IA32_PERF_GLOBAL_CTRL, 0x00);
WriteMsr(IA32_FIXED_CTR_CTRL, 0x00);
ovf_status = ReadMsr(IA32_PERF_GLOBAL_STATUS);
WriteMsr(IA32_PERF_GLOBAL_OVF_CTRL, ovf_status);
//setting up lvt entry
map_lvt_perf_count_reg = MmMapIoSpace(lvt_perf_count_reg, 4, MmNonCached);
*(PULONG32)map_lvt_perf_count_reg = set_lvt_perf_count_reg;
map_eoi_register = MmMapIoSpace(eoi_register, 4, MmNonCached);
//setting up idt handler
idtr.Limit = 0;
idtr.Base = 0;
GetIdt(&idtr);
idt = idtr.Base;
tmp_gate.Low = 0;
tmp_gate.High = 0;
func = 0;
seg = 0;
int_setting = 0x8e00;
//p = 1 dpl = 0 type(interrupt gate) = 1110 ist = 0
seg = GetCs();
func = (ULONG64)PmiHandle;
tmp_gate.Low = func & 0x0ffff;
tmp_gate.Low = seg << 16 | tmp_gate.Low;
tmp_gate.Low = int_setting << 32 | tmp_gate.Low;
tmp_gate.Low = ((func & 0x0ffff0000) << 32) | tmp_gate.Low;
tmp_gate.High = (func & 0xffffffff00000000) >> 32;
idt[238] = tmp_gate;
MmUnmapIoSpace(map_lvt_perf_count_reg, 4);
map_lvt_perf_count_reg = NULL;
pIrp->IoStatus.Information = 0;
break;
default:
DbgPrint("Error in switch");
break;
}
status = pIrp->IoStatus.Status;
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
return status;
}
pmihandle.asm
public PmiHandle
extern Handle : proc
.code
PmiHandle:
call Handle
add rsp, 8
iretq
end
handle.c
#define IA32_PERF_GLOBAL_CTRL 0x38f
#define IA32_PERF_GLOBAL_STATUS 0x38e
#define IA32_PERF_GLOBAL_OVF_CTRL 0x390
extern ULONG64 ovf_status_handle;
extern PVOID map_eoi_register;
VOID Handle() {
WriteMsr(IA32_PERF_GLOBAL_CTRL, 0x00);
ovf_status_handle = ReadMsr(IA32_PERF_GLOBAL_STATUS);
WriteMsr(IA32_PERF_GLOBAL_OVF_CTRL, ovf_status_handle);
DbgPrint("INTERRUPT_INTERRUPT_INTERRUPT");
if (map_eoi_register != NULL)
*(PULONG32)map_eoi_register = 0x0;
else
DbgPrint("EOI failed");
}
main.c application with which I turn on counters
#include <stdio.h>
#include "include/msr_sampling.h"
#define FILE_DEVICE_MSR 0x8000
#define IOCTL_INTERRUPT_SETTING_UP CTL_CODE(FILE_DEVICE_MSR, 0x805, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_FILE_TEST CTL_CODE(FILE_DEVICE_MSR, 0x806, METHOD_BUFFERED, FILE_ANY_ACCESS)
int main() {
SetProcForMsrCtr(); //set affinity mask for first proc
DriverOpen();
EnableReadPmc(); //enable __readpmc instruction
DWORD numberData = -1;
DeviceIoControl(hFile, IOCTL_INTERRUPT_SETTING_UP, NULL, 0, NULL, 0, &numberData, NULL);
ULONG64 value;
value = 0x000000000000000b;
WriteMsr(IA32_FIXED_CTR_CTRL, value);
value = 0xfffffffff000; //old value ffffffffc000
printf("%llu\n", __readpmc((1 << 30)));
WriteMsr(0x309, value);
printf("%llx\n", __readpmc((1 << 30)));
printf("=================================================\n");
ReadMsr(IA32_PERF_GLOBAL_CTRL, &value);
printf("%llX\n", value);
value = 0x0000000100000000;
WriteMsr(IA32_PERF_GLOBAL_CTRL, value);
printf("counter value: %llX\n", __readpmc((1 << 30)));
DriverClose();
system("pause");
return 0;
}
When I launch application my computer froze(does not respond to mouse movement and press key).
But if I generate interrupt with using assembly instuction INT it is OK.
I checked IDT and LVT entry via WinDbg they are correct.
What could be the problem?
Some informantion:
My processor is Intel Core i5-3210M. OS windows 7 x64. I do this on laptop.

Access violation error on stereolabs

I'm writing a program to convert an image sensed with a StereoLabs ZED stereocamera to an OpenCV image, to do some processing, here is the code (including the setup part een if I don't know if the problem can be there):
#include "stdafx.h"
#include "sl/camera.hpp"
#include "opencv2/opencv.hpp"
using namespace std;
using namespace cv;
using namespace sl;
cv::Mat zed_to_ocv(sl::Mat zed_mat) {
int cv_type = -1;
switch (zed_mat.getDataType()) {
case MAT_TYPE_32F_C1: cv_type = CV_32FC1; break;
case MAT_TYPE_32F_C2: cv_type = CV_32FC2; break;
case MAT_TYPE_32F_C3: cv_type = CV_32FC3; break;
case MAT_TYPE_32F_C4: cv_type = CV_32FC4; break;
case MAT_TYPE_8U_C1: cv_type = CV_8UC1; break;
case MAT_TYPE_8U_C2: cv_type = CV_8UC2; break;
case MAT_TYPE_8U_C3: cv_type = CV_8UC3; break;
case MAT_TYPE_8U_C4: cv_type = CV_8UC4; break;
default: break;
}
return cv::Mat(zed_mat.getHeight(), zed_mat.getWidth(), cv_type, zed_mat.getPtr<sl::uchar1>(MEM_CPU));
}
int main(int argc, char **argv) {
InitParameters parameters;
parameters.depth_mode = DEPTH_MODE_PERFORMANCE;
parameters.coordinate_units = UNIT_METER;
parameters.camera_fps = 30;
if (argc > 1) {
parameters.svo_input_filename = argv[1];
}
sl::Camera zed;
ERROR_CODE err = zed.open(parameters);
if (err != SUCCESS) {
zed.close();
cout << "Error while opening ZED camera";
return -1;
}
RuntimeParameters runtime_parameters;
runtime_parameters.sensing_mode = SENSING_MODE_STANDARD;
Resolution image_size = zed.getResolution();
int new_width = image_size.width;
int new_height = image_size.height;
sl::Mat image_zed(new_width, new_height, MAT_TYPE_8U_C4);
cv::Mat image_ocv = zed_to_ocv(image_zed);
cv::Mat image(new_width, new_height, CV_8UC1);
while (true) {
if (zed.grab(runtime_parameters) == SUCCESS) {
zed.retrieveImage(image_zed, VIEW_LEFT, MEM_CPU, new_width, new_height);
cv::cvtColor(image_ocv, image, CV_BGRA2GRAY);
imshow("camera", image);
waitKey(30);
}
}
zed.close();
return 0;
}
This code works just fine, but if I wanted to use 32F matrices instead (changing the type of both image_zed and image) I get a
Exception in correspondence of 0x00007FF97D175400 (opencv_imgproc340d.dll) in projectCV.exe: 0xC0000005: access violation error reading 0x000002C52DC13040.
error. I tried changing to
getPtr<sl::float1>
inside zed_to_ocv, but the error is still there.
EDIT: Debugging I found out the crash happens at line
cv::cvtColor(image_ocv, image, CV_BGRA2GRAY);
but I still can't figure out why.
What is the problem here? Thanks.

openCV:capture images from webcam but only greysreen

Can anyone tell me what's wrong with my code? I can use my webcam by other code, so there is nothing do with the supported problem. In my code below, I must set the camera index into a loop so that i can motivate my camera(the led inductor is on, simply set "CvCapture* camera=cvCaptureFromCAM(0)" can not run! that's wierd!).However, I just can obtain a greysreen,why?
#include "highgui.h"
#include "cv.h"
int main(int grac, char** grav)
{
CvCapture* camera;
int index;
for (index = -1; index <1; index++)
{
camera = cvCaptureFromCAM(index);
if (camera)
{
printf("%d\n", index);
IplImage* f;
cvNamedWindow("camera", CV_WINDOW_AUTOSIZE);
while (1)
{
f = cvQueryFrame(camera);
cvShowImage("camera", f);
char c = cvWaitKey(33);
if (c == 27)break;
}
}
}
cvReleaseCapture(&camera);
cvDestroyAllWindows;
}

Using fgets and strtok to read in data and create linked list

Need some help with reading in lines of data from a text file using the fgets and string tokenization commands, which will then be used to create a linked list. I've followed some examples I've found on Stack Overflow and other tutorial websites, but still cannot get the read function below to work properly in my program, it just causes it to crash. The data file has lines like this:
Zucchini, Squash, pound, 2.19, 45
Yellow, Squash, pound, 1.79, 15
Based on everything I've read, I believe I have the necessary code, but obviously I'm missing something. Also, I commented out one of the fields (the one for float price) as I'm not sure what to use to copy the float value from the data, as I cannot treat it as a string (the integer value right below it seems to let me get away with it in my compiler).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Struct for linked list node
struct produceItem
{
char produce[20];
char type[20];
char soldBy[20];
float price;
int quantityInStock;
struct produceItem *next;
};
// Function to read in data from file to
void read(struct produceItem **head)
{
struct produceItem *temp = NULL;
struct produceItem *right = NULL;
//char ch[3];
char line[50];
char *value;
FILE *data = fopen("RecitationFiveInput.txt", "r");
printf("Trying to open file RecitationFiveInput.txt\n");
if (data == NULL)
{
printf("Could not open file RecitationFiveInput.txt\n");
}
else
{
while(fgets(line, sizeof(line), data))
{
value = strtok(line, ", ");
strcpy(temp->produce, strdup(value));
value = strtok(NULL, ", ");
strcpy(temp->type, strdup(value));
value = strtok(NULL, ", ");
strcpy(temp->soldBy, strdup(value));
//value = strtok(NULL, ", ");
//strcpy(temp->price, strdup(value));
value = strtok(NULL, " \n");
strcpy(temp->quantityInStock, strdup(value));
temp->next = NULL;
if (*head == NULL)
{
*head = temp;
}
else
{
right = *head;
while(right->next != NULL)
{
right = right->next;
}
right->next = temp;
}
}
printf("Successfully opened file RecitationFiveInput.txt\n");
}
fclose(data);
return;
}
// Function to display the nodes of the linked list that contains the data from the data file
void display(struct produceItem *head)
{
int value = 1;
struct produceItem *temp = NULL;
temp = head;
printf("=============================================================================\n");
printf(" Item # Produce Type Sold By Price In Stock\n");
printf("=============================================================================\n");
if(temp == NULL)
{
return;
}
else
{
while(temp != NULL)
{
printf(" %d %s %s %s %lf %d\n", value, temp->produce, temp->type, temp->soldBy, temp->price, temp->quantityInStock);
value++;
temp = temp->next;
if(temp == NULL)
{
break;
}
}
}
return;
}
//Main function
int main()
{
int input = 0;
struct produceItem *head = NULL;
while(1)
{
printf("\nList Operations\n");
printf("=================\n");
printf("1. Stock Produce Department\n");
printf("2. Display Produce Inventory\n");
printf("3. Reverse Order of Produce Inventory\n");
printf("4. Export Produce Inventory\n");
printf("5. Exit Program\n");
printf("Enter your choice: ");
if(scanf("%d", &input) <= 0)
{
printf("Enter only an integer.\n");
exit(0);
}
else
{
switch(input)
{
case 1:
read(&head);
break;
case 2:
display(head);
break;
case 3:
//function
break;
case 4:
//function
break;
case 5:
printf("You have exited the program, Goodbye!\n");
return 0;
break;
default:
printf("Invalid option.\n");
}
}
}
return 0;
}
Never mind everyone, found the issue. The crashes were due to me not allocating memory for the temp pointer in the read me function.

Resources