summary refs log blame commit diff stats
path: root/test/tc_ext.py
blob: b80942336313257679735e58411fb2c6c44fadba (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15














                                                                       


































































                                                                           









                                                               
                                                     
                                               

                                                  
 





                                                                                    





                                                                               

























                                                                                         






                                                                                     
 

                          
# Copyright (C) 2009, 2010  Roman Zimbelmann <romanz@lavabit.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

if __name__ == '__main__': from __init__ import init; init()
import unittest
from collections import deque

from ranger.ext.iter_tools import *

class TestCases(unittest.TestCase):
	def test_flatten(self):
		def f(x):
			return list(flatten(x))

		self.assertEqual(
			[1,2,3,4,5],
			f([1,2,3,4,5]))
		self.assertEqual(
			[1,2,3,4,5],
			f([1,[2,3],4,5]))
		self.assertEqual(
			[1,2,3,4,5],
			f([[1,[2,3]],4,5]))
		self.assertEqual(
			[],
			f([[[[]]]]))
		self.assertEqual(
			['a', 'b', 'fskldfjl'],
			f(['a', ('b', 'fskldfjl')]))
		self.assertEqual(
			['a', 'b', 'fskldfjl'],
			f(['a', deque(['b', 'fskldfjl'])]))
		self.assertEqual(
			set([3.5, 4.3, 5.2, 6.0]),
			set(f([6.0, set((3.5, 4.3)), (5.2, )])))

	def test_unique(self):
		def u(x):
			return list(unique(x))

		self.assertEqual(
			[1,2,3],
			u([1,2,3]))
		self.assertEqual(
			[1,2,3],
			u([1,2,3,2,1]))
		self.assertEqual(
			[1,2,3],
			u([1,2,3,1,2,3,2,2,3,1,2,3,1,2,3,2,3,2,1]))
		self.assertEqual(
			[1,[2,3]],
			u([1,[2,3],1,[2,3],[2,3],1,[2,3],1,[2,3],[2,3],1]))

	def test_unique_keeps_type(self):
		def u(x):
			return unique(x)

		self.assertEqual(
			[1,2,3],
			u([1,2,3,1]))
		self.assertEqual(
			(1,2,3),
			u((1,2,3,1)))
		self.assertEqual(
			set((1,2,3)),
			u(set((1,2,3,1))))
		self.assertEqual(
			deque((1,2,3)),
			u(deque((1,2,3,1))))

	def test_mount_path(self):
		# assuming ismount() is used

		def my_ismount(path):
			depth = path.count('/')
			if path.startswith('/media'):
				return depth == 0 or depth == 2
			return depth <= 1

		from ranger.ext import mount_path
		original_ismount = mount_path.ismount
		mount_path.ismount = my_ismount
		try:
			mp = mount_path.mount_path

			self.assertEqual('/home', mp('/home/hut/porn/bondage'))
			self.assertEqual('/', mp('/'))
			self.assertEqual('/media/sdb1', mp('/media/sdb1/foo/bar'))
			self.assertEqual('/media/sdc2', mp('/media/sdc2/a/b/c/d/e'))
		finally:
			mount_path.ismount = original_ismount

		# TODO: links are not tested but I don't see how its possible
		# without messing around with mounts.
		# self.assertEqual('/media/foo',
		#     mount_path('/media/bar/some_link_to_a_foo_subdirectory'))

	def test_openstruct(self):
		from ranger.ext.openstruct import OpenStruct
		from random import randint, choice
		from string import ascii_letters

		os = OpenStruct(a='a')
		self.assertEqual(os.a, 'a')
		self.assertRaises(AttributeError, getattr, os, 'b')

		dictionary = {'foo': 'bar', 'zoo': 'zar'}
		os = OpenStruct(dictionary)
		self.assertEqual(os.foo, 'bar')
		self.assertEqual(os.zoo, 'zar')
		self.assertRaises(AttributeError, getattr, os, 'sdklfj')

		for i in range(100):
			attr_name = ''.join(choice(ascii_letters) \
				for x in range(randint(3,9)))
			value = randint(100,999)
			if not attr_name in os:
				self.assertRaises(AttributeError, getattr, os, attr_name)
			setattr(os, attr_name, value)
			value2 = randint(100,999)
			setattr(os, attr_name, value2)
			self.assertEqual(value2, getattr(os, attr_name))

	def test_shell_escape(self):
		from ranger.ext.shell_escape import shell_escape, shell_quote
		self.assertEqual(r"'luigi'\''s pizza'", shell_quote("luigi's pizza"))
		self.assertEqual(r"luigi\'s\ pizza", shell_escape("luigi's pizza"))
		self.assertEqual(r"\$lol/foo\\xyz\|\>\<\]\[",
				shell_escape(r"$lol/foo\xyz|><]["))


if __name__ == '__main__':
	unittest.main()
blame/kernel.soso/process.c?h=main&id=5183a8425f22cdd43f7d3cdef21a9523f0aceb8c'>^
46bb1d31 ^


67de9b02 ^
46bb1d31 ^




67de9b02 ^
46bb1d31 ^



67de9b02 ^

46bb1d31 ^









67de9b02 ^
46bb1d31 ^



852d31cf ^
46bb1d31 ^
67de9b02 ^
852d31cf ^
67de9b02 ^
46bb1d31 ^











67de9b02 ^
46bb1d31 ^



67de9b02 ^

46bb1d31 ^










67de9b02 ^
46bb1d31 ^

67de9b02 ^

46bb1d31 ^







67de9b02 ^
46bb1d31 ^

67de9b02 ^

46bb1d31 ^







67de9b02 ^
46bb1d31 ^


67de9b02 ^
46bb1d31 ^


67de9b02 ^
46bb1d31 ^

67de9b02 ^

46bb1d31 ^







67de9b02 ^
46bb1d31 ^

67de9b02 ^

46bb1d31 ^







f470eca4 ^
46bb1d31 ^
67de9b02 ^
46bb1d31 ^

67de9b02 ^
46bb1d31 ^



67de9b02 ^
46bb1d31 ^











67de9b02 ^
46bb1d31 ^

67de9b02 ^

46bb1d31 ^


















67de9b02 ^
46bb1d31 ^



67de9b02 ^
46bb1d31 ^









67de9b02 ^


46bb1d31 ^


67de9b02 ^
46bb1d31 ^



67de9b02 ^
46bb1d31 ^


67de9b02 ^
46bb1d31 ^




67de9b02 ^
46bb1d31 ^




67de9b02 ^
46bb1d31 ^



67de9b02 ^
46bb1d31 ^







67de9b02 ^
852d31cf ^
46bb1d31 ^



f470eca4 ^
46bb1d31 ^

f470eca4 ^
46bb1d31 ^










f470eca4 ^


46bb1d31 ^


67de9b02 ^
f470eca4 ^
46bb1d31 ^



























f470eca4 ^
46bb1d31 ^

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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713




























                                     
                            


                                 
                           


                                
                                      


                                     
                          











































                                                                                                                           

                                                         




                             
                       





                       
                                                     



                                                               
                                         













                                        
                                              



                       
                       








                                                                                   
                                                                          


                                                   
                                                        



                                                  
                                                                            


                                                                                               
                                                        
 
                                         










                                                    
                                         











                                                    
                                                                                                                                                       


                                                                                                                      
                                                                                                                                                                                                 
                                                                          
                         


                                        
                        




























                                                                                                           
                 






                                                             
              









































                                                                
                             




                     
                  


                                                       
                                















                                                                           
                                    



                                                       
                                 









                                                                 
                                       


                                  
          





                                                                                    
                                       

                                  


                                       










                                                                                                             
                                               












                                          

                                                



                                     
                          
                              


                                                    













                                                          

                                                                               




                     
                          


               
                    






















                                           
                        
                                            

                       
                  





                                                                
                          


                                     
                                       




                        
                                    



                           

                                                









                         
                                                      



                           
                                                          
 
                                                
                                                                              
                                     











                                  
                                                           



                           

                                                










                                  
                                        

                             

                                      







                     
                                           

                             

                                







                     
                               


                        
                            


                          
                                    

                             

                          







                        
                                       

                             

                                  







                        
                                          
 
                                           

                                        
                                       



                                     
                           











                                                                                                    
                                              

                                     

                                                               


















                                                          
                                       



                                                                   
              









                                                    


                                             


                                     
                                          



                                            
                                             


                                                                   
                                       




                                                      
                                           




                                    
                              



                                                     
          







                                                                                           
                                        
                                                                                                                 



                           
                          

 
                                           










                                                         


                           


                                    
          
                             



























                                  
                           

          
#include "process.h"
#include "common.h"
#include "alloc.h"
#include "vmm.h"
#include "descriptortables.h"
#include "elf.h"
#include "screen.h"
#include "debugprint.h"
#include "isr.h"
#include "timer.h"
#include "message.h"

#define MESSAGE_QUEUE_SIZE 64

Process* gKernelProcess = NULL;

Thread* gFirstThread = NULL;
Thread* gCurrentThread = NULL;

Thread* gDestroyedThread = NULL;

uint32 gProcessIdGenerator = 0;
uint32 gThreadIdGenerator = 0;

uint32 gSystemContextSwitchCount = 0;
uint32 gLastUptimeSeconds = 0;

extern Tss gTss;

uint32 generateProcessId() {
    return gProcessIdGenerator++;
}

uint32 generateThreadId() {
    return gThreadIdGenerator++;
}

uint32 getSystemContextSwitchCount() {
    return gSystemContextSwitchCount;
}

void initializeTasking() {
    Process* process = (Process*)kmalloc(sizeof(Process));
    memset((uint8*)process, 0, sizeof(Process));
    strcpy(process->name, "[kernel]");
    process->pid = generateProcessId();
    process->pd = (uint32*) KERN_PAGE_DIRECTORY;
    process->workingDirectory = getFileSystemRootNode();

    gKernelProcess = process;


    Thread* thread = (Thread*)kmalloc(sizeof(Thread));
    memset((uint8*)thread, 0, sizeof(Thread));

    thread->owner = gKernelProcess;

    thread->threadId = generateThreadId();

    thread->userMode = 0;
    thread->state = TS_RUN;
    thread->messageQueue = FifoBuffer_create(sizeof(SosoMessage) * MESSAGE_QUEUE_SIZE);
    Spinlock_Init(&(thread->messageQueueLock));
    thread->regs.cr3 = (uint32) process->pd;

    uint32 selector = 0x10;

    thread->regs.ss = selector;
    thread->regs.eflags = 0x0;
    thread->regs.cs = 0x08;
    thread->regs.eip = NULL;
    thread->regs.ds = selector;
    thread->regs.es = selector;
    thread->regs.fs = selector;
    thread->regs.gs = selector;

    thread->regs.esp = 0; //no need because this is already main kernel thread. ESP will written to this in first schedule.

    thread->kstack.ss0 = 0x10;
    thread->kstack.esp0 = 0;//For kernel threads, this is not required


    gFirstThread = thread;
    gCurrentThread = thread;
}

static int getStringArrayItemCount(char *const array[]) {
    if (NULL == array) {
        return 0;
    }

    int i = 0;
    const char* a = array[0];
    while (NULL != a) {
        a = array[++i];
    }

    return i;
}

static char** cloneStringArray(char *const array[]) {
    int itemCount = getStringArrayItemCount(array);

    char** newArray = kmalloc(sizeof(char*) * (itemCount + 1));

    for (int i = 0; i < itemCount; ++i) {
        const char* str = array[i];
        int len = strlen(str);

        char* newStr = kmalloc(len + 1);
        strcpy(newStr, str);

        newArray[i] = newStr;
    }

    newArray[itemCount] = NULL;

    return newArray;
}

static void destroyStringArray(char** array) {
    char* a = array[0];

    int i = 0;

    while (NULL != a) {
        kfree(a);

        a = array[++i];
    }

    kfree(array);
}

//This function must be called within the correct page directory for target process
static void copyArgvEnvToProcess(char *const argv[], char *const envp[]) {
    char** destination = (char**)USER_ARGV_ENV_LOC;
    int destinationIndex = 0;

    //printkf("ARGVENV: destination:%x\n", destination);

    int argvCount = getStringArrayItemCount(argv);
    int envpCount = getStringArrayItemCount(envp);

    //printkf("ARGVENV: argvCount:%d envpCount:%d\n", argvCount, envpCount);

    char* stringTable = (char*)USER_ARGV_ENV_LOC + sizeof(char*) * (argvCount + envpCount + 2);

    //printkf("ARGVENV: stringTable:%x\n", stringTable);

    for (int i = 0; i < argvCount; ++i) {
        strcpy(stringTable, argv[i]);

        destination[destinationIndex] = stringTable;

        stringTable += strlen(argv[i]) + 2;

        destinationIndex++;
    }

    destination[destinationIndex++] = NULL;

    for (int i = 0; i < envpCount; ++i) {
        strcpy(stringTable, envp[i]);

        destination[destinationIndex] = stringTable;

        stringTable += strlen(envp[i]) + 2;

        destinationIndex++;
    }

    destination[destinationIndex++] = NULL;
}

Process* createUserProcessFromElfData(const char* name, uint8* elfData, char *const argv[], char *const envp[], Process* parent, FileSystemNode* tty) {
    return createUserProcessEx(name, generateProcessId(), generateThreadId(), NULL, elfData, argv, envp, parent, tty);
}

Process* createUserProcessEx(const char* name, uint32 processId, uint32 threadId, Function0 func, uint8* elfData, char *const argv[], char *const envp[], Process* parent, FileSystemNode* tty) {
    printkf("createUserProcessEx: %s %d %d\n", name, processId, threadId);
    if (0 == processId) {
        processId = generateProcessId();
    }

    if (0 == threadId) {
        threadId = generateThreadId();
    }

    Process* process = (Process*)kmalloc(sizeof(Process));
    memset((uint8*)process, 0, sizeof(Process));
    strcpy(process->name, name);
    process->pid = processId;
    process->pd = createPd();//our page directories are identity mapped so this is also a physical address.
    process->workingDirectory = getFileSystemRootNode();

    Thread* thread = (Thread*)kmalloc(sizeof(Thread));
    memset((uint8*)thread, 0, sizeof(Thread));

    thread->owner = process;

    thread->threadId = threadId;

    thread->userMode = 1;

    thread->state = TS_RUN;

    thread->messageQueue = FifoBuffer_create(sizeof(SosoMessage) * MESSAGE_QUEUE_SIZE);
    Spinlock_Init(&(thread->messageQueueLock));

    thread->regs.cr3 = (uint32) process->pd;

    //Since stack grows backwards, we must allocate previous page. So lets substract a small amount.
    uint32 stackp = USER_STACK-4;

    if (parent) {
        process->parent = parent;

        process->workingDirectory = parent->workingDirectory;

        process->tty = parent->tty;
    }

    if (tty) {
        process->tty = tty;
    }

    char** newArgv = cloneStringArray(argv);
    char** newEnvp = cloneStringArray(envp);

    //Change memory view (page directory)
    asm("mov %0, %%eax; mov %%eax, %%cr3"::"m"(process->pd));

    initializeProcessHeap(process);

    initializeProcessMmap(process);

    copyArgvEnvToProcess(newArgv, newEnvp);

    destroyStringArray(newArgv);
    destroyStringArray(newEnvp);

    uint32 selector = 0x23;

    thread->regs.ss = selector;
    thread->regs.eflags = 0x0;
    thread->regs.cs = 0x1B;
    thread->regs.eip = (uint32)func;
    thread->regs.ds = selector;
    thread->regs.es = selector;
    thread->regs.fs = selector;
    thread->regs.gs = selector;

    thread->regs.esp = stackp;

    char* p_addr = getPageFrame4M();
    char* v_addr = (char *) (USER_STACK - PAGESIZE_4M);
    addPageToPd(process->pd, v_addr, p_addr, PG_USER);

    thread->kstack.ss0 = 0x10;
    uint8* stack = (uint8*)kmalloc(KERN_STACK_SIZE);
    thread->kstack.esp0 = (uint32)(stack + KERN_STACK_SIZE - 4);
    thread->kstack.stackStart = (uint32)stack;

    Thread* p = gCurrentThread;

    while (p->next != NULL) {
        p = p->next;
    }

    p->next = thread;

    if (elfData) {
        printkf("about to load ELF data\n");
        uint32 startLocation = loadElf((char*)elfData);

        if (startLocation > 0) {
            thread->regs.eip = startLocation;
        }
    }

    //Restore memory view (page directory)
    asm("mov %0, %%eax ;mov %%eax, %%cr3":: "m"(gCurrentThread->regs.cr3));

    open_fs_forProcess(thread, process->tty, 0);//0: standard input
    open_fs_forProcess(thread, process->tty, 0);//1: standard output
    open_fs_forProcess(thread, process->tty, 0);//2: standard error

    printkf("running process %d\n", process->pid);
    return process;
}

//This function should be called in interrupts disabled state
void destroyThread(Thread* thread) {
    Spinlock_Lock(&(thread->messageQueueLock));

    //TODO: signal the process somehow
    Thread* previousThread = getPreviousThread(thread);
    if (NULL != previousThread) {
        previousThread->next = thread->next;

        kfree((void*)thread->kstack.stackStart);

        FifoBuffer_destroy(thread->messageQueue);

        Debug_PrintF("destroying thread %d\n", thread->threadId);

        kfree(thread);

        if (thread == gCurrentThread) {
            gCurrentThread = NULL;
        }
    }
    else {
        printkf("Could not find previous thread for thread %d\n", thread->threadId);
        PANIC("This should not be happened!\n");
    }
}

//This function should be called in interrupts disabled state
void destroyProcess(Process* process) {
    Thread* thread = gFirstThread;
    Thread* previous = NULL;
    while (thread) {
        if (process == thread->owner) {
            if (NULL != previous) {
                previous->next = thread->next;

                kfree((void*)thread->kstack.stackStart);

                Spinlock_Lock(&(thread->messageQueueLock));
                FifoBuffer_destroy(thread->messageQueue);

                Debug_PrintF("destroying thread id:%d (owner process %d)\n", thread->threadId, process->pid);

                kfree(thread);

                if (thread == gCurrentThread) {
                    gCurrentThread = NULL;
                }

                thread = previous->next;
                continue;
            }
        }

        previous = thread;
        thread = thread->next;
    }

    //Cleanup opened files
    for (int i = 0; i < MAX_OPENED_FILES; ++i) {
        if (process->fd[i] != NULL) {
            close_fs(process->fd[i]);
        }
    }

    if (process->parent) {
        thread = gFirstThread;
        while (thread) {
            if (process->parent == thread->owner) {
                if (thread->state == TS_WAITCHILD) {
                    thread->state = TS_RUN;
                }
            }

            thread = thread->next;
        }
    }

    Debug_PrintF("destroying process %d\n", process->pid);

    destroyPd(process->pd);
    kfree(process);
}

void threadStateToString(ThreadState state, uint8* buffer, uint32 bufferSize) {
    if (bufferSize < 1) {
        return;
    }

    buffer[0] = '\0';

    if (bufferSize < 10) {
        return;
    }

    switch (state) {
    case TS_RUN:
        strcpy((char*)buffer, "run");
        break;
    case TS_SLEEP:
        strcpy((char*)buffer, "sleep");
        break;
    case TS_SUSPEND:
        strcpy((char*)buffer, "suspend");
        break;
    case TS_WAITCHILD:
        strcpy((char*)buffer, "waitchild");
        break;
    case TS_WAITIO:
        strcpy((char*)buffer, "waitio");
        break;
    case TS_YIELD:
        strcpy((char*)buffer, "yield");
        break;
    default:
        break;
    }
}

void waitForSchedule() {
    //printkf("Waiting for a schedule()\n");

    enableInterrupts();
    while (TRUE) {
        halt();
    }
    disableInterrupts();
    PANIC("waitForSchedule(): Should not be reached here!!!\n");
}

void yield(uint32 count) {
    gCurrentThread->yield = count;
    gCurrentThread->state = TS_YIELD;
    enableInterrupts();
    while (gCurrentThread->yield > 0) {
        halt();
    }
    disableInterrupts();
}

int32 getEmptyFd(Process* process) {
    int32 result = -1;

    beginCriticalSection();

    for (int i = 0; i < MAX_OPENED_FILES; ++i) {
        if (process->fd[i] == NULL) {
            result = i;
            break;
        }
    }

    endCriticalSection();

    return result;
}

int32 addFileToProcess(Process* process, File* file) {
    int32 result = -1;

    beginCriticalSection();

    //printkf("addFileToProcess: pid:%d\n", process->pid);

    for (int i = 0; i < MAX_OPENED_FILES; ++i) {
        //printkf("addFileToProcess: i:%d fd[%d]:%x\n", i, i, process->fd[i]);
        if (process->fd[i] == NULL) {
            result = i;
            file->fd = i;
            process->fd[i] = file;
            break;
        }
    }

    endCriticalSection();

    return result;
}

int32 removeFileFromProcess(Process* process, File* file) {
    int32 result = -1;

    beginCriticalSection();

    for (int i = 0; i < MAX_OPENED_FILES; ++i) {
        if (process->fd[i] == file) {
            result = i;
            process->fd[i] = NULL;
            break;
        }
    }

    endCriticalSection();

    return result;
}

Thread* getThreadById(uint32 threadId) {
    Thread* p = gFirstThread;

    while (p != NULL) {
        if (p->threadId == threadId) {
            return p;
        }
        p = p->next;
    }

    return NULL;
}

Thread* getPreviousThread(Thread* thread) {
    Thread* t = gFirstThread;

    while (t->next != NULL) {
        if (t->next == thread) {
            return t;
        }
        t = t->next;
    }

    return NULL;
}

Thread* getMainKernelThread() {
    return gFirstThread;
}

Thread* getCurrentThread() {
    return gCurrentThread;
}

BOOL isThreadValid(Thread* thread) {
    Thread* p = gFirstThread;

    while (p != NULL) {
        if (p == thread) {
            return TRUE;
        }
        p = p->next;
    }

    return FALSE;
}

BOOL isProcessValid(Process* process) {
    Thread* p = gFirstThread;

    while (p != NULL) {
        if (p->owner == process) {
            return TRUE;
        }
        p = p->next;
    }

    return FALSE;
}

static void switchToTask(Thread* current);

static void updateMetrics(Thread* thread) {
    uint32 seconds = getUptimeSeconds();

    if (seconds > gLastUptimeSeconds) {
        gLastUptimeSeconds = seconds;

        Thread* t = gFirstThread;

        while (t != NULL) {
            t->contextSwitchCount = t->totalContextSwitchCount - t->totalContextSwitchCountPrevious;
            t->totalContextSwitchCountPrevious = t->totalContextSwitchCount;

            t = t->next;
        }
    }

    ++gSystemContextSwitchCount;

    ++thread->totalContextSwitchCount;
}

void schedule(TimerInt_Registers* registers) {
    Thread* current = gCurrentThread;

    if (NULL != current) {
        if (current->next == NULL && current == gFirstThread) {
            //We are the only process, no need to schedule
            return;
        }

        current->regs.eflags = registers->eflags;
        current->regs.cs = registers->cs;
        current->regs.eip = registers->eip;
        current->regs.eax = registers->eax;
        current->regs.ecx = registers->ecx;
        current->regs.edx = registers->edx;
        current->regs.ebx = registers->ebx;
        current->regs.ebp = registers->ebp;
        current->regs.esi = registers->esi;
        current->regs.edi = registers->edi;
        current->regs.ds = registers->ds;
        current->regs.es = registers->es;
        current->regs.fs = registers->fs;
        current->regs.gs = registers->gs;

        if (current->regs.cs != 0x08) {
            //Debug_PrintF("schedule() - 2.1\n");
            current->regs.esp = registers->esp_if_privilege_change;
            current->regs.ss = registers->ss_if_privilege_change;
        }
        else {
            //Debug_PrintF("schedule() - 2.2\n");
            current->regs.esp = registers->esp + 12;
            current->regs.ss = gTss.ss0;
        }

        //Save the TSS from the old process
        current->kstack.ss0 = gTss.ss0;
        current->kstack.esp0 = gTss.esp0;

        current = current->next;
        while (NULL != current) {
            if (current->state == TS_YIELD) {
                if (current->yield > 0) {
                    --current->yield;
                }

                if (current->yield == 0) {
                    current->state = TS_RUN;
                }
            }

            if (current->state == TS_SLEEP) {
                uint32 uptime = getUptimeMilliseconds();
                uint32 target = (uint32)current->state_privateData;

                if (uptime >= target) {
                    current->state = TS_RUN;
                    current->state_privateData = NULL;
                }
            }

            if (current->state == TS_RUN) {
                break;
            }
            current = current->next;
        }

        if (current == NULL) {
            //reached last process returning to first
            current = gFirstThread;
        }
    }
    else {
        //current is NULL. This means thread is destroyed, so start from the begining

        current = gFirstThread;
    }

    gCurrentThread = current;//Now gCurrentThread is the thread we are about to schedule to

    /*
    if (gCurrentThread->threadId == 5) {
        printkf("I am scheduling to %d and its EIP is %x\n", gCurrentThread->threadId, gCurrentThread->regs.eip);
    }
    */

    updateMetrics(current);
    switchToTask(current);
}

static void switchToTask(Thread* current) {
    uint32 kesp, eflags;
    uint16 kss, ss, cs;

    //Set TSS values
    gTss.ss0 = current->kstack.ss0;
    gTss.esp0 = current->kstack.esp0;

    ss = current->regs.ss;
    cs = current->regs.cs;
    eflags = (current->regs.eflags | 0x200) & 0xFFFFBFFF;

    int oldMode;
    if (cs != 0x08) {
        oldMode = USERMODE;
        kss = current->kstack.ss0;
        kesp = current->kstack.esp0;
    }
    else {
        oldMode = KERNELMODE;
        kss = current->regs.ss;
        kesp = current->regs.esp;
    }

    //switchTask is in task.asm

    asm("	mov %0, %%ss; \
        mov %1, %%esp; \
        cmpl %[KMODE], %[mode]; \
        je nextt; \
        push %2; \
        push %3; \
        nextt: \
        push %4; \
        push %5; \
        push %6; \
        push %7; \
        ljmp $0x08, $switchTask"
        :: \
        "m"(kss), \
        "m"(kesp), \
        "m"(ss), \
        "m"(current->regs.esp), \
        "m"(eflags), \
        "m"(cs), \
        "m"(current->regs.eip), \
        "m"(current), \
        [KMODE] "i"(KERNELMODE), \
        [mode] "g"(oldMode)
        );
}