-
Notifications
You must be signed in to change notification settings - Fork 1
/
DDetector.c
132 lines (113 loc) · 2.49 KB
/
DDetector.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <dlfcn.h>
#include <execinfo.h>
struct Node{
int count;
pthread_mutex_t *mutex;
struct Node *next;
}Node;
struct Node* head;
//print value in linked list
void
printer(){
struct Node* current = head;
while(current !=NULL){
// printf(" %d->", current->count);
current = current->next;
}
printf("\n");
return;
}
void
detect(){//detect deadlock
printer();
struct Node* current = head;
while(current !=NULL){
if(current->count >=0){
return;
}
current = current->next;
}
char buf[50];
snprintf(buf,50,"deadlock\n");
fputs(buf,stderr);
return;
}
void/*push item in linked list*/
push(struct Node** head_ref,pthread_mutex_t *mutex)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
/* put in the key */
new_node->mutex = mutex;
new_node->count = 0;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
int
lock_find_mutex(pthread_mutex_t *mutex){
struct Node* current = head;
int find =0;
while (current != NULL)
{
if (current->mutex == mutex){
current->count = current->count-1;
return 1;
}
current = current->next;
}
push(&head,mutex);
return 0;
}
int
ulock_find_mutex(pthread_mutex_t *mutex){
struct Node* current = head;
int find =0;
while (current != NULL)
{
if (current->mutex == mutex){
if(current->count <=0){
current->count = current->count + 1;
return 1;
}
else return 1;
}
current = current->next;
}
return 0;
}
int
pthread_mutex_lock (pthread_mutex_t *mutex)
{
int (*lockp)(pthread_mutex_t *mutex) ;
char * error ;
lockp = dlsym(RTLD_NEXT, "pthread_mutex_lock") ;
if ((error = dlerror()) != 0x0)
exit(1) ;
/*find mutex in linked list and update status or push new node*/
lock_find_mutex(mutex);
/*detect deadlock*/
detect();
lockp(mutex);
return 0;
}
int pthread_mutex_unlock(pthread_mutex_t *mutex)
{
int (*ulockp)(pthread_mutex_t *mutex) ;
char * error ;
ulockp = dlsym(RTLD_NEXT, "pthread_mutex_unlock") ;
if ((error = dlerror()) != 0x0)
exit(1) ;
ulock_find_mutex(mutex);
char buf[50] ;
snprintf(buf, 50, "out\n") ;
fputs(buf, stderr) ;
ulockp(mutex);
return 77 ;
}