Debian Codegraph @

src/core/chuck_vm.cpp

raw symbols SCIP
1 /*----------------------------------------------------------------------------
2 ChucK Strongly-timed Audio Programming Language
3 Compiler, Virtual Machine, and Synthesis Engine
4
5 Copyright (c) 2003 Ge Wang and Perry R. Cook. All rights reserved.
6 http://chuck.stanford.edu/
7 http://chuck.cs.princeton.edu/
8
9 This program is free software; you can redistribute it and/or modify
10 it under the dual-license terms of EITHER the MIT License OR the GNU
11 General Public License (the latter as published by the Free Software
12 Foundation; either version 2 of the License or, at your option, any
13 later version).
14
15 This program is distributed in the hope that it will be useful and/or
16 interesting, but WITHOUT ANY WARRANTY; without even the implied warranty
17 of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 MIT Licence and/or the GNU General Public License for details.
19
20 You should have received a copy of the MIT License and the GNU General
21 Public License (GPL) along with this program; a copy of the GPL can also
22 be obtained by writing to the Free Software Foundation, Inc., 59 Temple
23 Place, Suite 330, Boston, MA 02111-1307 U.S.A.
24 -----------------------------------------------------------------------------*/
25
26 //-----------------------------------------------------------------------------
27 // file: chuck_vm.cpp
28 // desc: chuck virtual machine
29 //
30 // author: Ge Wang (https://ccrma.stanford.edu/~ge/)
31 // date: Autumn 2002
32 //-----------------------------------------------------------------------------
33 #include "chuck_vm.h"
34 #include "chuck_instr.h"
35 #include "chuck_lang.h"
36 #include "chuck_type.h"
37 #include "chuck_dl.h"
38 #include "chuck_globals.h" // added 1.4.1.0 (jack)
39 #include "chuck_errmsg.h"
40 #include "chuck.h"
41 #include "ugen_xxx.h"
42 #include "util_buffers.h"
43 #include "util_platforms.h"
44 #include "util_string.h"
45
46 #ifndef __DISABLE_SERIAL__
47 #include "chuck_io.h"
48 #endif
49
50 #ifndef __DISABLE_HID__
51 #include "hidio_sdl.h" // 1.4.0.0
52 #endif
53
54 #ifndef __DISABLE_MIDI__
55 #include "midiio_rtmidi.h" // 1.4.1.0
56 #endif
57
58 #include <limits.h> // 1.5.1.5 | for ULONG_MAX
59 #include <iomanip>
60 #include <string>
61 #include <algorithm>
62 using namespace std;
63
64
65
66
67 //-----------------------------------------------------------------------------
68 // uncomment AND set to 1 to compile VM stack observe messages
69 //-----------------------------------------------------------------------------
70 #define CK_VM_STACK_OBSERVE_ENABLE 0
71 // vm statck observe macros
72 #if CK_VM_STACK_OBSERVE_ENABLE
73 #define CK_VM_STACK_OBSERVE(x) x
74 #else
75 #define CK_VM_STACK_OBSERVE(x)
76 #endif
77
78 //-----------------------------------------------------------------------------
79 // uncomment AND set to 1 to compile VM stack debug messages
80 //-----------------------------------------------------------------------------
81 #define CK_VM_STACK_DEBUG_ENABLE 0
82 // vm statck debug macros
83 #if CK_VM_STACK_DEBUG_ENABLE
84 #include <typeinfo>
85 #define CK_VM_STACK_DEBUG(x) x
86 #else
87 #define CK_VM_STACK_DEBUG(x)
88 #endif
89
90
91
92
93
94 //-----------------------------------------------------------------------------
95 // name: struct SortByID_LT()
96 // desc: for sorting less than
97 //-----------------------------------------------------------------------------
98 struct SortByID_LT
99 {
100 bool operator()( const Chuck_VM_Shred * lhs, const Chuck_VM_Shred * rhs )
101 { return lhs->xid < rhs->xid; }
102 };
103
104
105
106
107 //-----------------------------------------------------------------------------
108 // name: struct SortByID_GT()
109 // desc: for sorting greater than
110 //-----------------------------------------------------------------------------
111 struct SortByID_GT
112 {
113 bool operator()( const Chuck_VM_Shred * lhs, const Chuck_VM_Shred * rhs )
114 { return lhs->xid > rhs->xid; }
115 };
116
117
118
119
120 //-----------------------------------------------------------------------------
121 // name: struct Chuck_VM_Frame
122 // desc: func frame
123 //-----------------------------------------------------------------------------
124 struct Chuck_VM_Frame
125 {
126 public:
127 t_CKUINT size;
128
129 public:
130 Chuck_VM_Frame() { size = 0; }
131 ~Chuck_VM_Frame() { }
132 };
133
134
135
136
137 //-----------------------------------------------------------------------------
138 // name: struct Chuck_VM_Func
139 // desc: vm function
140 //-----------------------------------------------------------------------------
141 struct Chuck_VM_Func
142 {
143 public:
144 Chuck_VM_Code * code;
145 Chuck_VM_Frame * frame;
146 t_CKUINT index;
147
148 public:
149 Chuck_VM_Func() { code = NULL; frame = NULL; index = 0; }
150 ~Chuck_VM_Func() { }
151 };
152
153
154
155
156 //-----------------------------------------------------------------------------
157 // name: struct Chuck_VM_FTable
158 // desc: function table
159 //-----------------------------------------------------------------------------
160 struct Chuck_VM_FTable
161 {
162 public:
163 Chuck_VM_FTable();
164 ~Chuck_VM_FTable();
165
166 public:
167 Chuck_VM_Func * get_func( t_CKUINT index );
168 t_CKUINT append( Chuck_VM_Func * f );
169 t_CKBOOL remove( t_CKUINT index );
170
171 public:
172 vector<Chuck_VM_Func *> func_table;
173 };
174
175
176
177
178 //-----------------------------------------------------------------------------
179 // name: Chuck_VM()
180 // desc: constructor
181 //-----------------------------------------------------------------------------
182 Chuck_VM::Chuck_VM()
183 {
184 // REFACTOR-2017: refs
185 m_carrier = NULL;
186
187 // machine state
188 m_init = FALSE;
189 m_halt = TRUE;
190 m_is_running = FALSE;
191
192 // shred management
193 m_num_shreds = 0;
194 m_shreduler = NULL;
195 m_num_dumped_shreds = 0;
196 m_globals_manager = NULL; // 1.4.1.0 (jack)
197 m_msg_buffer = NULL;
198 m_reply_buffer = NULL;
199 m_event_buffer = NULL;
200 m_shred_id = 0;
201 m_shred_check4dupes = FALSE; // 1.5.1.5 (ge)
202 m_asap_remove_all_shreds = FALSE; // 1.5.4.4 (ge) added
203
204 // audio hookups
205 m_dac = NULL;
206 m_adc = NULL;
207 m_bunghole = NULL;
208 m_srate = 0;
209 m_num_dac_channels = 0;
210 m_num_adc_channels = 0;
211 m_input_ref = NULL;
212 m_output_ref = NULL;
213 m_current_buffer_frames = 0;
214 }
215
216
217
218
219 //-----------------------------------------------------------------------------
220 // name: ~Chuck_VM()
221 // desc: ...
222 //-----------------------------------------------------------------------------
223 Chuck_VM::~Chuck_VM()
224 {
225 // check if init
226 if( m_init )
227 {
228 // cleanup
229 shutdown();
230 }
231 }
232
233
234
235
236 //-----------------------------------------------------------------------------
237 // name: initialize()
238 // desc: ...
239 //-----------------------------------------------------------------------------
240 t_CKBOOL Chuck_VM::initialize( t_CKUINT srate, t_CKUINT dac_chan,
241 t_CKUINT adc_chan, t_CKUINT adaptive, t_CKBOOL halt )
242 {
243 if( m_init )
244 {
245 m_last_error = "VM already initialized!";
246 return FALSE;
247 }
248
249 // log
250 EM_log( CK_LOG_SYSTEM, "initializing virtual machine..." );
251 EM_pushlog(); // push stack
252
253 m_halt = halt;
254 m_num_adc_channels = adc_chan;
255 m_num_dac_channels = dac_chan;
256 m_srate = srate;
257
258 // lockdown
259 Chuck_VM_Object::lock_all();
260
261 // log
262 EM_log( CK_LOG_SYSTEM, "allocating shreduler..." );
263 // allocate shreduler
264 m_shreduler = new Chuck_VM_Shreduler;
265 m_shreduler->vm_ref = this;
266 m_shreduler->set_adaptive( adaptive > 0 ? adaptive : 0 );
267
268 // log
269 EM_log( CK_LOG_SYSTEM, "allocating messaging buffers..." );
270 // allocate msg buffer
271 m_msg_buffer = new CBufferSimple;
272 m_msg_buffer->initialize( 1024, sizeof(Chuck_Msg *) );
273 //m_msg_buffer->join(); // this should return 0
274 m_reply_buffer = new CBufferSimple;
275 m_reply_buffer->initialize( 1024, sizeof(Chuck_Msg *) );
276 //m_reply_buffer->join(); // this should return 0 too
277 m_event_buffer = new CBufferSimple;
278 m_event_buffer->initialize( 1024, sizeof(Chuck_Event *) );
279 //m_event_buffer->join(); // this should also return 0
280
281 // 1.4.1.0 (jack): added globals manager
282 EM_log( CK_LOG_SYSTEM, "allocating globals manager..." );
283 m_globals_manager = new Chuck_Globals_Manager( this );
284
285 // pop log
286 EM_poplog();
287
288 // TODO: clean up all the dynamic objects here on failure
289 // and in the shutdown function!
290
291 return m_init = TRUE;
292 }
293
294
295
296
297 //-----------------------------------------------------------------------------
298 // name: initialize_synthesis()
299 // desc: requires type system
300 //-----------------------------------------------------------------------------
301 t_CKBOOL Chuck_VM::initialize_synthesis()
302 {
303 if( !m_init )
304 {
305 m_last_error = "VM initialize_synthesis() called on raw VM";
306 return FALSE;
307 }
308
309 if( !env()->ckt_dac || !env()->ckt_adc )
310 {
311 m_last_error = "VM initialize_synthesis() called before type system initialized";
312 return FALSE;
313 }
314
315 if( m_dac != NULL )
316 {
317 m_last_error = "VM synthesis already initialized";
318 return FALSE;
319 }
320
321 // log
322 EM_log( CK_LOG_HERALD, "initializing 'dac'..." );
323 // allocate dac and adc (REFACTOR-2017: g_t_dac changed to env()->ckt_dac)
324 env()->ckt_dac->ugen_info->num_outs = env()->ckt_dac->ugen_info->num_ins = m_num_dac_channels;
325 m_dac = (Chuck_UGen *)instantiate_and_initialize_object( env()->ckt_dac, this );
326 // special case: DAC is a UGen_Multi, but due to the underlying system /
327 // command-line flags, it's possible to only have one channel | 1.5.2.0
328 if( m_num_dac_channels == 1 ) {
329 m_dac->m_multi_chan = new Chuck_UGen *[1];
330 // assign first channel to dac itself
331 m_dac->m_multi_chan[0] = m_dac;
332 // no ref count will deal with this explicitly on clean up in Chuck_VM::shutdown()
333 }
334 // Chuck_DL_Api::instance() added 1.3.0.0
335 object_ctor( m_dac, NULL, this, NULL, Chuck_DL_Api::instance() ); // TODO: this can't be the place to do this
336 multi_ctor( m_dac, NULL, this, NULL, Chuck_DL_Api::instance() ); // TODO: remove and let type system do this
337 stereo_ctor( m_dac, NULL, this, NULL, Chuck_DL_Api::instance() ); // TODO: is the NULL shred a problem?
338 m_dac->add_ref();
339 // lock it
340 m_dac->lock();
341
342 // log
343 EM_log( CK_LOG_HERALD, "initializing 'adc'..." );
344 // (REFACTOR-2017: g_t_adc changed to env()->ckt_adc)
345 env()->ckt_adc->ugen_info->num_ins = env()->ckt_adc->ugen_info->num_outs = m_num_adc_channels;
346 m_adc = (Chuck_UGen *)instantiate_and_initialize_object( env()->ckt_adc, this );
347 // special case: ADC is a UGen_Multi, but due to the underlying system /
348 // command-line flags, it's possible to only have one channel | 1.5.2.0
349 if( m_num_adc_channels == 1 ) {
350 m_adc->m_multi_chan = new Chuck_UGen *[1];
351 // assign first channel to adc itself
352 m_adc->m_multi_chan[0] = m_adc;
353 // no ref count will deal with this explicitly on clean up in Chuck_VM::shutdown()
354 }
355 // Chuck_DL_Api::instance() added 1.3.0.0
356 object_ctor( m_adc, NULL, this, NULL, Chuck_DL_Api::instance() ); // TODO: this can't be the place to do this
357 multi_ctor( m_adc, NULL, this, NULL, Chuck_DL_Api::instance() ); // TODO: remove and let type system do this
358 stereo_ctor( m_adc, NULL, this, NULL, Chuck_DL_Api::instance() );
359 m_adc->add_ref();
360 // lock it
361 m_adc->lock();
362
363 // log
364 EM_log( CK_LOG_HERALD, "initializing 'blackhole'..." );
365 m_bunghole = new Chuck_UGen;
366 m_bunghole->add_ref();
367 m_bunghole->lock();
368 initialize_object( m_bunghole, env()->ckt_ugen, NULL, this );
369 m_bunghole->tick = NULL;
370 m_bunghole->alloc_v( m_shreduler->m_max_block_size );
371 m_shreduler->m_dac = m_dac;
372 m_shreduler->m_adc = m_adc;
373 m_shreduler->m_bunghole = m_bunghole;
374 m_shreduler->m_num_dac_channels = m_num_dac_channels;
375 m_shreduler->m_num_adc_channels = m_num_adc_channels;
376
377 return TRUE;
378 }
379
380
381
382
383 //-----------------------------------------------------------------------------
384 // name: update_srate() | 1.5.4.2 (ge) added
385 // update sample rate (this will also trigger notifications for srate update)
386 //-----------------------------------------------------------------------------
387 t_CKBOOL Chuck_VM::update_srate( t_CKUINT srate )
388 {
389 // log
390 EM_log( CK_LOG_SYSTEM, "updating sample rate: '%d'...", srate );
391 // set it
392 m_srate = srate;
393 // notify registered callbacks of the srate update
394 notify_callbacks_on_srate_update( srate );
395 // done
396 return TRUE;
397 }
398
399
400
401
402 //-----------------------------------------------------------------------------
403 // name: shutdown()
404 // desc: shut it down, VM-wise
405 //-----------------------------------------------------------------------------
406 t_CKBOOL Chuck_VM::shutdown()
407 {
408 // make sure we are in the initialized state
409 if( !m_init ) return FALSE;
410
411 // log
412 EM_log( CK_LOG_SYSTEM, "shutting down virtual machine..." );
413 // push indent
414 EM_pushlog();
415
416 // unlockdown
417 // REFACTOR-2017: TODO: don't unlock all objects for all VMs? see relockdown below
418 Chuck_VM_Object::unlock_all();
419
420 // REFACTOR-2017: clean up after my global variables
421 m_globals_manager->cleanup_global_variables();
422 CK_SAFE_DELETE( m_globals_manager );
423
424 // log
425 EM_log( CK_LOG_HERALD, "removing shreds..." );
426 // removal all | 1.5.0.8 (ge) updated from previously non-functioning code
427 this->removeAll();
428
429 #ifndef __DISABLE_HID__
430 // log
431 EM_log( CK_LOG_SYSTEM, "unregistering VM from HID manager..." );
432 // clean up this vm
433 HidInManager::cleanup_buffer( this );
434 #endif
435
436 #ifndef __DISABLE_MIDI__
437 EM_log( CK_LOG_SYSTEM, "unregistering VM from MIDI manager..." );
438 MidiInManager::cleanup_buffer( this );
439 #endif
440
441 // log
442 EM_log( CK_LOG_SYSTEM, "freeing msg/reply/event buffers..." );
443 // free the msg buffer
444 CK_SAFE_DELETE( m_msg_buffer );
445 // free the reply buffer
446 CK_SAFE_DELETE( m_reply_buffer );
447 // free the event buffer
448 CK_SAFE_DELETE( m_event_buffer );
449
450 // log
451 EM_pushlog();
452 EM_log( CK_LOG_HERALD, "freeing dumped shreds..." );
453 // do it
454 this->release_dump();
455 EM_poplog();
456
457 // log
458 EM_log( CK_LOG_SYSTEM, "freeing shreduler..." );
459 // free the shreduler; do this later as dumped shreds may refer to shreduler
460 CK_SAFE_DELETE( m_shreduler );
461
462 // log
463 EM_log( CK_LOG_SYSTEM, "freeing special ugens..." );
464 // explcitly calling a destructor, accounting for internal ref counts | 1.5.2.0
465 if( m_dac ) stereo_dtor( m_dac, this, NULL, Chuck_DL_Api::instance() );
466 if( m_adc ) stereo_dtor( m_adc, this, NULL, Chuck_DL_Api::instance() );
467 // special case: if mono, must zero out multi-chan[0] (see Chuck_VM::initialize_synthesis())
468 if( m_num_dac_channels == 1 ) // 1.5.2.0 (ge) added
469 {
470 // verify
471 assert( m_dac->m_multi_chan_size == 0 );
472 // zero out, no ref count -- this flies under the ref counting system...
473 m_dac->m_multi_chan[0] = NULL;
474 // reclaim
475 CK_SAFE_DELETE_ARRAY( m_dac->m_multi_chan );
476 }
477 // special case: if mono, must zero out multi-chan[0] (see Chuck_VM::initialize_synthesis())
478 if( m_num_adc_channels == 1 ) // 1.5.2.0 (ge) added
479 {
480 // verify
481 assert( m_adc->m_multi_chan_size == 0 );
482 // zero out, no ref count -- this flies under the ref counting system...
483 m_adc->m_multi_chan[0] = NULL;
484 // reclaim
485 CK_SAFE_DELETE_ARRAY( m_adc->m_multi_chan );
486 }
487 // release
488 CK_SAFE_RELEASE( m_dac );
489 CK_SAFE_RELEASE( m_adc );
490 CK_SAFE_RELEASE( m_bunghole );
491
492 // set state
493 m_init = FALSE;
494
495 // notify registered callbacks we are shutting down | 1.5.2.5 (ge) added
496 notify_callbacks_on_shutdown();
497
498 // relockdown (added 1.3.6.0)
499 // REFACTOR-2017: TODO -- remove once made per-VM
500 Chuck_VM_Object::lock_all();
501
502 // log
503 EM_log( CK_LOG_SYSTEM, "virtual machine shutdown complete." );
504
505 // pop indent
506 EM_poplog();
507
508 return TRUE;
509 }
510
511
512
513
514 //-----------------------------------------------------------------------------
515 // name: start()
516 // desc: run start (can be called before or after init)
517 //-----------------------------------------------------------------------------
518 t_CKBOOL Chuck_VM::start()
519 {
520 // already running?
521 if( m_is_running ) return FALSE;
522 // set state
523 m_is_running = TRUE;
524 // done
525 return TRUE;
526 }
527
528
529
530
531 //-----------------------------------------------------------------------------
532 // name: running()
533 // desc: get run state
534 //-----------------------------------------------------------------------------
535 t_CKBOOL Chuck_VM::running() const
536 {
537 return m_is_running;
538 }
539
540
541
542
543 //-----------------------------------------------------------------------------
544 // name: stop()
545 // desc: run stop
546 //-----------------------------------------------------------------------------
547 t_CKBOOL Chuck_VM::stop()
548 {
549 // running?
550 if( !m_is_running ) return FALSE;
551 // set state
552 m_is_running = FALSE;
553 // done
554 return TRUE;
555 }
556
557
558
559
560 //-----------------------------------------------------------------------------
561 // name: compute()
562 // desc: compute all shreds at one instance in ChucK time
563 //-----------------------------------------------------------------------------
564 t_CKBOOL Chuck_VM::compute()
565 {
566 Chuck_VM_Shred *& shred = m_shreduler->m_current_shred;
567 Chuck_Msg * msg = NULL;
568 Chuck_Event * event = NULL;
569 t_CKBOOL iterate = TRUE;
570
571 // check if request to remove all shreds | 1.5.4.4
572 if( m_asap_remove_all_shreds )
573 {
574 // call remove all
575 this->removeAll();
576 // reset the flag
577 m_asap_remove_all_shreds = FALSE;
578 }
579
580 // REFACTOR-2017: spork queued shreds, handle global messages
581 // this is called once per chuck time / sample / "tick"
582 // global manager added 1.4.1.0 (jack)
583 m_globals_manager->handle_global_queue_messages();
584
585 // iterate until no more shreds/events/messages
586 while( iterate )
587 {
588 // get the shreds queued for 'now'
589 shred = m_shreduler->get();
590 // run all shreds waiting to run 'now'
591 while( shred != NULL )
592 {
593 // set the current time of the shred
594 shred->now = shred->wake_time;
595 // track shred activation
596 CK_TRACK( Chuck_Stats::instance()->activate_shred( shred ) );
597
598 // run the shred
599 // 1.5.0.0 (ge) add check for shred->is_done, which flags a shred to exit
600 if( shred->is_done || !shred->run( this ) )
601 {
602 // track shred deactivation
603 CK_TRACK( Chuck_Stats::instance()->deactivate_shred( shred ) );
604
605 this->free_shred( shred, TRUE );
606 shred = NULL;
607 if( !m_num_shreds && m_halt ) return FALSE;
608 }
609
610 // track shred deactivation
611 CK_TRACK( if( shred ) Chuck_Stats::instance()->deactivate_shred( shred ) );
612 // get next shred queued for 'now'
613 shred = m_shreduler->get();
614 }
615
616 // set to false for now
617 iterate = FALSE;
618
619 // broadcast queued events
620 while( m_event_buffer->get( &event, 1 ) )
621 {
622 event->broadcast_local();
623 event->broadcast_global();
624 iterate = TRUE;
625 }
626
627 // loop over thread-specific queued event buffers (added 1.3.0.0)
628 for( list<CBufferSimple *>::const_iterator i = m_event_buffers.begin();
629 i != m_event_buffers.end(); i++ )
630 {
631 while( (*i)->get( &event, 1 ) )
632 {
633 event->broadcast_local();
634 event->broadcast_global();
635 iterate = TRUE;
636 }
637 }
638
639 // process messages
640 while( m_msg_buffer->get( &msg, 1 ) )
641 { process_msg( msg ); iterate = TRUE; }
642
643 // clear dumped shreds
644 if( m_num_dumped_shreds > 0 )
645 release_dump();
646 }
647
648 // continue executing if have shreds left or if don't-halt
649 // or if have shreds to add or globals to process
650 // (TODO: restrict this to just shred-messages to pass, as it once was?)
651 return ( m_num_shreds || !m_halt || m_globals_manager->more_requests() );
652 }
653
654
655
656
657 //-----------------------------------------------------------------------------
658 // name: run()
659 // desc: run VM and compute the next N frames of audio
660 // `N` : the number of audio frames to run
661 // `input`: the incoming input array of audio samples
662 // `output`: the outgoing output array of audio samples
663 //-----------------------------------------------------------------------------
664 t_CKBOOL Chuck_VM::run( t_CKINT N, const SAMPLE * input, SAMPLE * output )
665 {
666 // copy
667 m_input_ref = input; m_output_ref = output; m_current_buffer_frames = N;
668 // frame count
669 t_CKINT frame = 0;
670
671 // zero output buffer
672 memset( output, 0, N*m_num_dac_channels*sizeof(SAMPLE) );
673
674 // for now, check for global variables once per sample (below)
675 // TODO: once per buffer instead? (place here then)
676
677 // loop it
678 while( N )
679 {
680 // compute shreds
681 if( !compute() ) goto vm_stop;
682
683 // advance the shreduler
684 if( !m_shreduler->m_adaptive )
685 {
686 m_shreduler->advance( frame++ );
687 if( N > 0 ) N--;
688 }
689 else m_shreduler->advance_v( N, frame );
690 }
691
692 // clear
693 m_input_ref = NULL; m_output_ref = NULL;
694
695 return FALSE;
696
697 // vm stop here
698 vm_stop:
699
700 // log, check so we only log once, in case run() still gets called
701 // after the initial stoppage; calling stop after resets m_is_running
702 if( m_is_running ) EM_log( CK_LOG_SYSTEM, "stopping virtual machine..." );
703
704 // stop | 1.3.5.3
705 this->stop();
706
707 // clear | 1.5.0.8
708 m_input_ref = NULL; m_output_ref = NULL;
709
710 return TRUE;
711 }
712
713
714
715 //-----------------------------------------------------------------------------
716 // name: gc() | 1.5.2.0 (ge) added
717 // desc: manually trigger a VM-level garbage collection pass
718 //-----------------------------------------------------------------------------
719 void Chuck_VM::gc( )
720 {
721 // vector of shreds
722 vector<Chuck_VM_Shred *> shreds;
723 // retrieve all shreds currently in the shreduler; this includes the
724 // ready list, the blocked list, and the currently executing shred
725 m_shreduler->get_all_shreds( shreds );
726 // iterate through all shreds in VM
727 for( t_CKUINT i = 0; i < shreds.size(); i++ )
728 {
729 // manually trigger GC pass in each shred
730 shreds[i]->gc();
731 }
732 }
733
734
735
736
737 //-----------------------------------------------------------------------------
738 // name: queue_msg()
739 // desc: ...
740 //-----------------------------------------------------------------------------
741 t_CKBOOL Chuck_VM::queue_msg( Chuck_Msg * msg, t_CKINT count )
742 {
743 assert( count == 1 );
744 m_msg_buffer->put( &msg, count );
745 return TRUE;
746 }
747
748
749
750
751 //-----------------------------------------------------------------------------
752 // name: queue_event()
753 // desc: since 1.3.0.0 a buffer is passed in associated with each thread
754 //-----------------------------------------------------------------------------
755 t_CKBOOL Chuck_VM::queue_event( Chuck_Event * event, t_CKINT count,
756 CBufferSimple * buffer )
757 {
758 // sanity
759 assert( count == 1 );
760 // if null
761 if( buffer == NULL )
762 {
763 // use non thread-safe buffer
764 buffer = m_event_buffer;
765 }
766 // put into the buffer
767 buffer->put( &event, count );
768
769 // done
770 return TRUE;
771 }
772
773
774
775
776 //-----------------------------------------------------------------------------
777 // name: create_event_buffer()
778 // desc: added 1.3.0.0 to fix uber-crash
779 //-----------------------------------------------------------------------------
780 CBufferSimple * Chuck_VM::create_event_buffer()
781 {
782 CBufferSimple * buffer = new CBufferSimple;
783 buffer->initialize( 1024, sizeof(Chuck_Event *) );
784 m_event_buffers.push_back(buffer);
785
786 return buffer;
787 }
788
789
790
791
792 //-----------------------------------------------------------------------------
793 // name: destroy_event_buffer()
794 // desc: added 1.3.0.0 to fix uber-crash
795 // updated 1.5.13 and broken into two parts
796 //-----------------------------------------------------------------------------
797 void Chuck_VM::destroy_event_buffer( CBufferSimple * buffer )
798 {
799 // always detach, even if buffer already detached by external calls
800 this->detach_event_buffer_without_delete( buffer );
801 // reclaim
802 CK_SAFE_DELETE( buffer );
803 }
804
805
806
807
808 //-----------------------------------------------------------------------------
809 // name: detach_event_buffer_without_delete() | 1.5.1.3
810 // desc: detach event buffer from VM, without deleting buffer
811 //-----------------------------------------------------------------------------
812 void Chuck_VM::detach_event_buffer_without_delete( CBufferSimple * buffer )
813 {
814 // detach
815 m_event_buffers.remove( buffer );
816 }
817
818
819
820
821 //-----------------------------------------------------------------------------
822 // name: get_reply()
823 // desc: get reply from reply buffer
824 // TODO: make thread safe for multiple consumers
825 //-----------------------------------------------------------------------------
826 Chuck_Msg * Chuck_VM::get_reply()
827 {
828 Chuck_Msg * msg = NULL;
829 m_reply_buffer->get( &msg, 1 );
830 return msg;
831 }
832
833
834
835
836 //-----------------------------------------------------------------------------
837 // name: process_msg()
838 // desc: process a VM message; NOTE: assumes msg is dynamically allocated...
839 // and msg will be cleaned up by the VM
840 // TODO: make thread safe for multiple consumers
841 //-----------------------------------------------------------------------------
842 t_CKUINT Chuck_VM::process_msg( Chuck_Msg * & msg )
843 {
844 t_CKUINT retval = 0xfffffff0;
845
846 // check message type
847 if( msg->type == CK_MSG_REPLACE )
848 {
849 Chuck_VM_Shred * out = m_shreduler->lookup( msg->param );
850 if( !out && !msg->alwaysAdd )
851 {
852 EM_print2orange( "(VM) replacing shred: no shred with id %lu...", msg->param );
853 retval = 0;
854 goto done;
855 }
856
857 // get a shred one way or another
858 Chuck_VM_Shred * shred = msg->shred;
859 // if shred wasn't created on the outside
860 if( !shred )
861 {
862 shred = new Chuck_VM_Shred;
863 shred->vm_ref = this;
864 shred->initialize( msg->code );
865 shred->name = msg->code->name;
866 shred->base_ref = shred->mem;
867 // NOTE no add_ref() since we spork() later
868 }
869 // set the id (even if out is NULL)
870 shred->xid = msg->param;
871 // set args
872 if( msg->args ) shred->args = *(msg->args);
873
874 // check for different scenarios of replace
875 // replace-target absent | 1.5.1.5 (nshaheed) added
876 if( !out )
877 {
878 // spork it
879 this->spork( shred );
880
881 // print
882 const char * s = (msg->shred ? msg->shred->name.c_str() : msg->code->name.c_str());
883 EM_print2orange( "(VM) (optional) replacing shred: %lu not found...", msg->param );
884 EM_print2green( "(VM) sporking incoming shred: %lu (%s)...", shred->xid, mini(s) );
885
886 // return value
887 retval = shred->xid;
888 // done
889 goto done;
890 }
891 // replace-target present
892 // modified shredule(shred) -> spork(shred) | 1.5.1.5 (ge)
893 else if( m_shreduler->remove( out ) && this->spork( shred ) )
894 {
895 EM_print2blue( "(VM) replacing shred %lu (%s) with %lu (%s)...",
896 out->xid, mini(out->name.c_str()), shred->xid, mini(shred->name.c_str()) );
897 // free shred; dec==TRUE since spork above always increments shred count
898 this->free_shred( out, TRUE, TRUE );
899 // set return value to shred ID
900 retval = shred->xid;
901 // tracking new shred
902 CK_TRACK( Chuck_Stats::instance()->add_shred( shred ) );
903 goto done;
904 }
905 else
906 {
907 // shouldn't get here!
908 EM_print2blue( "(VM) (internal error) replacing shred %lu...", out->xid );
909 shred->release();
910 retval = 0;
911 goto done;
912 }
913 }
914 else if( msg->type == CK_MSG_REMOVE )
915 {
916 if( msg->param == CK_NO_VALUE )
917 {
918 if( !this->m_num_shreds)
919 {
920 EM_print2orange( "(VM) no shreds to remove..." );
921 retval = 0;
922 goto done;
923 }
924
925 t_CKUINT xid = m_shred_id;
926 Chuck_VM_Shred * shred = NULL;
927 while( xid > 0 && m_shreduler->remove( shred = m_shreduler->lookup( xid ) ) == 0 )
928 xid--;
929 if( xid > 0 )
930 {
931 EM_print2orange( "(VM) removing recent shred: %lu (%s)...",
932 xid, mini(shred->name.c_str()) );
933 this->free_shred( shred, TRUE );
934 retval = xid;
935 }
936 else
937 {
938 EM_print2orange( "(VM) no shreds removed..." );
939 retval = 0;
940 goto done;
941 }
942 }
943 else
944 {
945 Chuck_VM_Shred * shred = m_shreduler->lookup( msg->param );
946 if( !shred )
947 {
948 EM_print2orange( "(VM) cannot remove: no shred with id %lu...", msg->param );
949 retval = 0;
950 goto done;
951 }
952 if( shred != m_shreduler->m_current_shred && !m_shreduler->remove( shred ) ) // was lookup
953 {
954 EM_print2orange( "(VM) shreduler: cannot remove shred %lu...", msg->param );
955 retval = 0;
956 goto done;
957 }
958 EM_print2orange( "(VM) removing shred: %lu (%s)...", msg->param, mini(shred->name.c_str()) );
959 this->free_shred( shred, TRUE );
960 retval = msg->param;
961 }
962 }
963 else if( msg->type == CK_MSG_REMOVEALL )
964 {
965 // print
966 EM_print2magenta( "(VM) removing all (%lu) shreds...", m_num_shreds );
967 // remove all shreds
968 this->removeAll();
969 }
970 else if( msg->type == CK_MSG_CLEARVM ) // added 1.3.2.0
971 {
972 // print
973 EM_print2magenta( "(VM) removing all shreds and resetting type system" );
974 // first, remove all shreds
975 this->removeAll();
976 // next, clear user type system
977 if( env() )
978 {
979 // clear user namespace
980 env()->clear_user_namespace();
981 // reset operload overloading to default | 1.5.1.5
982 // not needed; this is implicit in clear_user_namespace() which calls reset()
983 // env()->op_registry.reset();
984 }
985 // 1.4.1.0 (jack): also clear any global variables
986 m_globals_manager->cleanup_global_variables();
987 }
988 else if( msg->type == CK_MSG_CLEARGLOBALS ) // added chunity
989 {
990 // clean up global variables without clearing the whole VM
991 m_globals_manager->cleanup_global_variables();
992 }
993 else if( msg->type == CK_MSG_ADD )
994 {
995 t_CKUINT xid = 0;
996 Chuck_VM_Shred * shred = NULL;
997 if( msg->shred ) shred = this->spork( msg->shred );
998 else shred = this->spork( msg->code, NULL, TRUE );
999 xid = shred->xid;
1000 if( msg->args ) shred->args = *(msg->args);
1001
1002 const char * s = ( msg->shred ? msg->shred->name.c_str() : msg->code->name.c_str() );
1003 EM_print2green( "(VM) sporking incoming shred: %lu (%s)...", xid, mini(s) );
1004 retval = xid;
1005 goto done;
1006 }
1007 else if( msg->type == CK_MSG_EXIT )
1008 {
1009 EM_print2magenta( "(VM) EXIT received...." );
1010 // close file handles and clean up
1011 // REFACTOR-2017: TODO all_detach function
1012 // all_detach();
1013 // TODO: free more memory?
1014
1015 // log
1016 EM_log( CK_LOG_INFO, "(VM): exiting..." );
1017 // come again
1018 exit( 1 );
1019 }
1020 else if( msg->type == CK_MSG_STATUS )
1021 {
1022 // fill in structure
1023 if( msg->status )
1024 {
1025 // get it
1026 m_shreduler->status( msg->status );
1027 }
1028 else
1029 {
1030 m_shreduler->status();
1031 }
1032 }
1033 else if( msg->type == CK_MSG_TIME )
1034 {
1035 // string stream
1036 ostringstream sout;
1037 // generate string; fixed notation
1038 sout << "chuck time: " << std::fixed << m_shreduler->now_system << "::samp (now)";
1039 // get string
1040 string ckt_str = sout.str();
1041 // find occurence of ::
1042 size_t where = ckt_str.find( "::" );
1043 // just in case
1044 if( where == string::npos ) where = 22;
1045 // sample rate
1046 t_CKFLOAT srate = m_srate;
1047
1048 // earth time
1049 EM_print2magenta( "local time: %s", timestamp_formatted().c_str() );
1050 // chuck time
1051 EM_print2magenta( ckt_str.c_str() );
1052
1053 // clear and generate
1054 sout.str(std::string()); sout << "%" << where << ".6f::second since VM start";
1055 EM_print2vanilla( sout.str().c_str(), m_shreduler->now_system / srate );
1056
1057 sout.str(std::string()); sout << "%" << where << ".6f::minute";
1058 EM_print2vanilla( sout.str().c_str(), m_shreduler->now_system / srate / 60.0f );
1059
1060 sout.str(std::string()); sout << "%" << where << ".6f::hour";
1061 EM_print2vanilla( sout.str().c_str(), m_shreduler->now_system / srate / 60.0f / 60.0f );
1062
1063 sout.str(std::string()); sout << "%" << where << ".6f::day";
1064 EM_print2vanilla( sout.str().c_str(), m_shreduler->now_system / srate / 60.0f / 60.0f / 24.0f );
1065
1066 sout.str(std::string()); sout << "%" << where << ".6f::week";
1067 EM_print2vanilla( sout.str().c_str(), m_shreduler->now_system / srate / 60.0f / 60.0f / 24.0f / 7.0f );
1068 }
1069 else if( msg->type == CK_MSG_RESET_ID )
1070 {
1071 // reset ID to current highest shred ID + 1
1072 // could be helpful to keep shred ID #'s low, especially after a lot of sporks
1073 EM_print2magenta( "(VM) resetting shred id to %lu...", this->reset_id() );
1074 }
1075
1076 done:
1077 // set return value
1078 msg->replyA = retval;
1079
1080 // check reponse method
1081 if( msg->reply_cb ) // 1.5.0.8 (ge) added
1082 {
1083 // call the callback
1084 msg->reply_cb( msg );
1085 }
1086 else if( msg->reply_queue )
1087 {
1088 // put on reply queue
1089 m_reply_buffer->put( &msg, 1 );
1090 }
1091 else
1092 {
1093 // nothing further to be done; delete msg
1094 // FYI since msg pointer is passed into this function by reference,
1095 // this will also set the external msg pointer to NULL
1096 CK_SAFE_DELETE( msg );
1097 }
1098
1099 return retval;
1100 }
1101
1102
1103
1104
1105 //-----------------------------------------------------------------------------
1106 // name: next_id()
1107 // desc: first increments the shred id, then returns it
1108 //-----------------------------------------------------------------------------
1109 t_CKUINT Chuck_VM::next_id( const Chuck_VM_Shred * shred )
1110 {
1111 // max id
1112 const t_CKUINT MAX_ID = ULONG_MAX;
1113
1114 // see if shred passed in and already has an ID to use (e.g., from REPLACE)
1115 if( shred && shred->xid != 0 )
1116 {
1117 // check if we need to raise m_shred_id as highest shred ID...
1118 // NOTE if check4dupes is enabled, m_shred_id may no longer be the
1119 // highest ID but instead is a counter for possible next shred IDs,
1120 // which will repeatedly increment+check for duplicates until an
1121 // available ID is found | 1.5.1.5 (ge and nshaheed) added
1122 if( !m_shred_check4dupes && shred->xid > m_shred_id )
1123 {
1124 // update as highest ID so far
1125 m_shred_id = shred->xid;
1126 }
1127 // return the shred's ID back
1128 return shred->xid;
1129 }
1130
1131 // test for bound
1132 if( m_shred_id == MAX_ID )
1133 {
1134 // print congratulatory message
1135 EM_print2orange( "(VM) you have surpassed max shred ID: %lu", m_shred_id );
1136 EM_print2orange( "(VM) congratulations! resetting IDs back to 1 and up..." );
1137 // reset ID back to 0
1138 m_shred_id = 0;
1139 // set to check for duplicates, since there now could be collisions
1140 m_shred_check4dupes = TRUE;
1141 }
1142
1143 // check for dupes (after shred id wraps from MAX_ID) | 1.5.1.5
1144 if( !m_shred_check4dupes ) return ++m_shred_id;
1145
1146 // find next unused shred ID | 1.5.1.5
1147 while( m_shreduler->lookup( ++m_shred_id ) );
1148
1149 // return it
1150 return m_shred_id;
1151 }
1152
1153
1154
1155
1156 //-----------------------------------------------------------------------------
1157 // name: last_id()
1158 // desc: returns the last used shred id
1159 //-----------------------------------------------------------------------------
1160 t_CKUINT Chuck_VM::last_id( ) const
1161 {
1162 return m_shred_id;
1163 }
1164
1165
1166
1167
1168 //-----------------------------------------------------------------------------
1169 // name: reset_id() | 1.5.0.8 (ge) re-factored from code in process_msg
1170 // desc: reset ID to lowest current ID + 1; returns what next ID would be
1171 //-----------------------------------------------------------------------------
1172 t_CKUINT Chuck_VM::reset_id()
1173 {
1174 // set shred_id to the current highest; will be incremented on next_id()
1175 m_shred_id = m_shreduler->highest();
1176
1177 return m_shred_id + 1;
1178 }
1179
1180
1181
1182
1183 //-----------------------------------------------------------------------------
1184 // name: shreduler()
1185 // desc: get the VM's shreduler
1186 //-----------------------------------------------------------------------------
1187 Chuck_VM_Shreduler * Chuck_VM::shreduler() const
1188 {
1189 return m_shreduler;
1190 }
1191
1192
1193
1194
1195 //-----------------------------------------------------------------------------
1196 // name: srate()
1197 // desc: get VM sample rate
1198 //-----------------------------------------------------------------------------
1199 t_CKUINT Chuck_VM::srate() const
1200 {
1201 return m_srate; // 1.3.5.3; was: (t_CKUINT)Digitalio::sampling_rate();
1202 }
1203
1204
1205
1206
1207 //-----------------------------------------------------------------------------
1208 // name: now() | 1.5.0.8 (ge) added
1209 // desc: get the current chuck time
1210 //-----------------------------------------------------------------------------
1211 t_CKTIME Chuck_VM::now() const
1212 {
1213 return m_shreduler ? m_shreduler->now_system : 0;
1214 }
1215
1216
1217
1218
1219 //-----------------------------------------------------------------------------
1220 // name: spork()
1221 // desc: spork shred from compiled VM code
1222 //-----------------------------------------------------------------------------
1223 Chuck_VM_Shred * Chuck_VM::spork( Chuck_VM_Code * code, Chuck_VM_Shred * parent,
1224 t_CKBOOL immediate )
1225 {
1226 // allocate a new shred
1227 Chuck_VM_Shred * shred = new Chuck_VM_Shred;
1228 // set the vm
1229 shred->vm_ref = this;
1230 // get stack size hints | 1.5.1.5
1231 t_CKINT mems = parent ? parent->childGetMemSize() : 0;
1232 t_CKINT regs = parent ? parent->childGetRegSize() : 0;
1233 // initialize the shred (default stack size)
1234 shred->initialize( code, mems, regs );
1235 // set the name
1236 shred->name = code->name;
1237 // set the parent
1238 shred->parent = parent;
1239 // set the base ref for global
1240 if( parent ) shred->base_ref = shred->parent->base_ref;
1241 else shred->base_ref = shred->mem;
1242
1243 // get shred ID | 1.5.0.8 (ge) moved here so all shreds have IDs earlier
1244 // previously: only immediate-mode shreds were assigned IDs in this method
1245 // (via the other spork() function) and non-immediate shreds were returned
1246 // with ID 0 (their ID assignment would have been deferred)
1247 // presently: the shred created and returned by this function will be
1248 // assigned an ID regardless of the immediate flag
1249 shred->xid = next_id();
1250
1251 // check whether to start running immediately at current time step
1252 // (this is more timely, but should be only used if called on same
1253 // thread as VM compute() / the audio thread)
1254 if( immediate )
1255 {
1256 // spork it
1257 this->spork( shred );
1258 }
1259 else // or be sporked later (by compute() on the next time step)
1260 {
1261 // spork it later
1262 Chuck_Global_Request spork_request;
1263 spork_request.type = spork_shred_request;
1264 spork_request.shred = shred;
1265 // added 1.4.1.0 (jack)
1266 m_globals_manager->add_request( spork_request );
1267 }
1268
1269 // track new shred
1270 CK_TRACK( Chuck_Stats::instance()->add_shred( shred ) );
1271
1272 return shred;
1273 }
1274
1275
1276
1277
1278 //-----------------------------------------------------------------------------
1279 // name: spork()
1280 // desc: spork a shred, shreduling it to run in the VM
1281 //-----------------------------------------------------------------------------
1282 Chuck_VM_Shred * Chuck_VM::spork( Chuck_VM_Shred * shred )
1283 {
1284 // set the current time
1285 shred->start = m_shreduler->now_system;
1286 // set the now
1287 shred->now = shred->wake_time = m_shreduler->now_system;
1288 // set the id, if one hasn't been assigned yet | 1.5.0.8 (ge) add check
1289 // pass in the shred into next_id() instead of checking here | 1.5.1.5
1290 shred->xid = next_id( shred );
1291 // add ref
1292 CK_SAFE_ADD_REF( shred );
1293 // add it to the parent
1294 if( shred->parent )
1295 shred->parent->children[shred->xid] = shred;
1296 // shredule it
1297 m_shreduler->shredule( shred );
1298 // count
1299 m_num_shreds++;
1300
1301 // notify watcher | 1.5.1.5
1302 notify_watchers( ckvm_shreds_watch_SPORK, shred, m_shreds_watchers_spork );
1303
1304 return shred;
1305 }
1306
1307
1308
1309
1310 //-----------------------------------------------------------------------------
1311 // name: removeAll()
1312 // desc: remove all shreds from VM
1313 //-----------------------------------------------------------------------------
1314 void Chuck_VM::removeAll()
1315 {
1316 // get list of active shreds
1317 std::vector<Chuck_VM_Shred *> shreds;
1318
1319 // get list from shreduler
1320 m_shreduler->get_all_shreds( shreds );
1321
1322 // before 1.5.0.8, was:
1323 // m_shreduler->get_ready_shreds( shreds );
1324
1325 // sort in descending ID order
1326 SortByID_GT byid;
1327 std::sort( shreds.begin(), shreds.end(), byid );
1328
1329 // itereate over sorted list
1330 for( vector<Chuck_VM_Shred *>::iterator s = shreds.begin(); s != shreds.end(); s++ )
1331 {
1332 // remove from shreduler
1333 if( m_shreduler->remove( *s ) )
1334 {
1335 // free the shred
1336 this->free_shred( *s, TRUE );
1337 }
1338 }
1339
1340 // reset
1341 m_shred_id = 0;
1342 m_num_shreds = 0;
1343
1344 // can safely reset this as well | 1.5.1.5
1345 m_shred_check4dupes = FALSE;
1346 }
1347
1348
1349
1350
1351 //-----------------------------------------------------------------------------
1352 // name: free_shred()
1353 // desc: deallocate a shred
1354 //-----------------------------------------------------------------------------
1355 t_CKBOOL Chuck_VM::free_shred( Chuck_VM_Shred * shred, t_CKBOOL cascade, t_CKBOOL dec )
1356 {
1357 assert( cascade );
1358
1359 // log
1360 EM_log( CK_LOG_FINER, "freeing shred (id==%lu | ptr==%p)", shred->xid,
1361 (t_CKUINT)shred );
1362
1363 // abort on the double free
1364 // TODO: can a shred be dumped, then resporked? from code?
1365 if( shred->is_dumped ) return FALSE;
1366
1367 // mark this done
1368 shred->is_done = TRUE;
1369
1370 // free the children
1371 t_CKINT size = shred->children.size();
1372 if( size )
1373 {
1374 vector<Chuck_VM_Shred *> list; list.resize( size );
1375 map<t_CKUINT, Chuck_VM_Shred *>::iterator iter; t_CKINT i = 0;
1376 for( iter = shred->children.begin(); iter != shred->children.end(); iter++ )
1377 list[i++] = (*iter).second;
1378 for( i = 0; i < size; i++ )
1379 this->free_shred( list[i], cascade );
1380 }
1381
1382 // make sure it's done
1383 assert( shred->children.size() == 0 );
1384
1385 // tell parent
1386 if( shred->parent )
1387 shred->parent->children.erase( shred->xid );
1388
1389 // track remove shred
1390 CK_TRACK( Chuck_Stats::instance()->remove_shred( shred ) );
1391
1392 // free!
1393 m_shreduler->remove( shred );
1394 // TODO: remove shred from event, with synchronization (still necessary with dump?)
1395 // if( shred->event ) shred->event->remove( shred );
1396 // OLD: shred->release();
1397 this->dump_shred( shred );
1398 shred = NULL;
1399
1400 // decrement?
1401 if( dec )
1402 {
1403 // make sure shred counter isn't already zero
1404 if( m_num_shreds == 0 )
1405 {
1406 EM_print2magenta( "(VM) internal inconsistency detected: shreds counter already zero." );
1407 return FALSE;
1408 }
1409 // decrement
1410 m_num_shreds--;
1411 }
1412
1413 // reset ID if no more shreds currently
1414 if( !m_num_shreds ) m_shred_id = 0;
1415
1416 return TRUE;
1417 }
1418
1419
1420
1421
1422 //-----------------------------------------------------------------------------
1423 // name: abort_current_shred()
1424 // desc: abort the current shred
1425 //-----------------------------------------------------------------------------
1426 t_CKBOOL Chuck_VM::abort_current_shred()
1427 {
1428 // for threading
1429 Chuck_VM_Shred * shred = m_shreduler->m_current_shred;
1430
1431 // if there
1432 if( shred )
1433 {
1434 // log
1435 EM_log( CK_LOG_HERALD, "trying to abort current shred (id: %lu)", shred->xid );
1436 // flag it
1437 shred->is_abort = TRUE;
1438 }
1439 else
1440 {
1441 // log
1442 EM_log( CK_LOG_HERALD, "cannot abort shred: nothing currently running!" );
1443 }
1444
1445 return shred != NULL;
1446 }
1447
1448
1449
1450
1451 //-----------------------------------------------------------------------------
1452 // name: get_current_shred()
1453 // desc: get currently executing shred
1454 // NOTE this can only be non-NULL during a Chuck_VM::compute() cycle
1455 //-----------------------------------------------------------------------------
1456 Chuck_VM_Shred * Chuck_VM::get_current_shred() const
1457 {
1458 // no shreduler
1459 if( !m_shreduler ) return NULL;
1460 // return shreduler's current shred
1461 return m_shreduler->get_current_shred();
1462 }
1463
1464
1465
1466
1467 //-----------------------------------------------------------------------------
1468 // name: remove_all_shreds() | 1.5.4.4 (ge) added
1469 // desc: remove all shreds asap (thread-safe) will enact atop next compute()
1470 //-----------------------------------------------------------------------------
1471 void Chuck_VM::remove_all_shreds()
1472 {
1473 // set the flag
1474 m_asap_remove_all_shreds = TRUE;
1475 }
1476
1477
1478
1479
1480 //-----------------------------------------------------------------------------
1481 // name: register_callback_on_shutdown()
1482 // cesc: register a callback to be called on VM shutdown | 1.5.2.5 (ge) added
1483 //-----------------------------------------------------------------------------
1484 void Chuck_VM::register_callback_on_shutdown( f_callback_on_shutdown cb, void * bindle )
1485 {
1486 // check
1487 if( !cb ) return;
1488
1489 // ensure no duplicates
1490 list<Chuck_VM_Callback_On_Shutdown>::iterator it = std::find( m_callbacks_on_shutdown.begin(),
1491 m_callbacks_on_shutdown.end(), cb );
1492 // add if not already preset
1493 if( it == m_callbacks_on_shutdown.end() )
1494 {
1495 // append
1496 m_callbacks_on_shutdown.push_back( Chuck_VM_Callback_On_Shutdown(cb, bindle) );
1497 }
1498 }
1499
1500
1501
1502
1503 //-----------------------------------------------------------------------------
1504 // name: register_callback_on_srate_update() | 1.5.4.2 (ge) added
1505 // cesc: register a callback to be called on system sample rate update
1506 //-----------------------------------------------------------------------------
1507 void Chuck_VM::register_callback_on_srate_update( f_callback_on_srate_update cb, void * bindle )
1508 {
1509 // check
1510 if( !cb ) return;
1511
1512 // ensure no duplicates
1513 list<Chuck_VM_Callback_On_SampleRate_Update>::iterator it = std::find( m_callbacks_on_srate_update.begin(),
1514 m_callbacks_on_srate_update.end(), cb );
1515 // add if not already preset
1516 if( it == m_callbacks_on_srate_update.end() )
1517 {
1518 // append
1519 m_callbacks_on_srate_update.push_back( Chuck_VM_Callback_On_SampleRate_Update(cb, bindle) );
1520 }
1521 }
1522
1523
1524
1525
1526 //-----------------------------------------------------------------------------
1527 // name: notify_callbacks_on_shutdown()
1528 // desc: notify callbacks on VM shutdown | 1.5.2.5 (ge) added
1529 //-----------------------------------------------------------------------------
1530 void Chuck_VM::notify_callbacks_on_shutdown()
1531 {
1532 // the function to call eventually
1533 f_callback_on_shutdown f = NULL;
1534 // iterator
1535 list<Chuck_VM_Callback_On_Shutdown>::iterator it;
1536 // iterate
1537 for( it = m_callbacks_on_shutdown.begin(); it != m_callbacks_on_shutdown.end(); it++ )
1538 {
1539 // the function
1540 f = (*it).cb;
1541 // call it with user data
1542 f( (*it).userdata );
1543 }
1544 }
1545
1546
1547
1548
1549 //-----------------------------------------------------------------------------
1550 // name: notify_callbacks_on_srate_update()
1551 // desc: notify callbacks on sample rate update | 1.5.4.2 (ge) added
1552 //-----------------------------------------------------------------------------
1553 void Chuck_VM::notify_callbacks_on_srate_update( t_CKUINT srate )
1554 {
1555 // the function to call eventually
1556 f_callback_on_srate_update f = NULL;
1557 // iterator
1558 list<Chuck_VM_Callback_On_SampleRate_Update>::iterator it;
1559 // iterate
1560 for( it = m_callbacks_on_srate_update.begin();
1561 it != m_callbacks_on_srate_update.end(); it++ )
1562 {
1563 // the function
1564 f = (*it).cb;
1565 // call it with the srate and user data
1566 f( srate, (*it).userdata );
1567 }
1568 }
1569
1570
1571
1572
1573 //-----------------------------------------------------------------------------
1574 // name: notify_watchers()
1575 // desc: notify watchers for a particular subscription | 1.5.1.5
1576 //-----------------------------------------------------------------------------
1577 void Chuck_VM::notify_watchers( ckvm_ShredsWatcherFlag which,
1578 Chuck_VM_Shred * shred,
1579 list<Chuck_VM_Shreds_Watcher> & v )
1580 {
1581 // the function to call eventually
1582 f_shreds_watcher f = NULL;
1583 // iterator
1584 list<Chuck_VM_Shreds_Watcher>::iterator it;
1585 // iterate
1586 for( it = v.begin(); it != v.end(); it++ )
1587 {
1588 // the function
1589 f = (*it).cb;
1590 // call it with user data
1591 f( shred, which, 0, this, (*it).userdata );
1592 }
1593 }
1594
1595
1596
1597
1598 //-----------------------------------------------------------------------------
1599 // name: dump_shred()
1600 // desc: place a shred into the "dump" to be later released
1601 //-----------------------------------------------------------------------------
1602 void Chuck_VM::dump_shred( Chuck_VM_Shred * shred )
1603 {
1604 // log
1605 EM_log( CK_LOG_FINER, "dumping shred (id==%lu | ptr==%p)", shred->xid,
1606 (t_CKUINT)shred );
1607 // add
1608 m_shred_dump.push_back( shred );
1609 // stop
1610 shred->is_running = FALSE;
1611 shred->is_done = TRUE;
1612 shred->is_dumped = TRUE;
1613
1614 // before we reset the shred ID, notify watchers
1615 notify_watchers( ckvm_shreds_watch_REMOVE, shred, m_shreds_watchers_remove );
1616
1617 // TODO: cool?
1618 shred->xid = 0;
1619 // inc
1620 m_num_dumped_shreds++;
1621 }
1622
1623
1624
1625
1626 //-----------------------------------------------------------------------------
1627 // name: release_dump()
1628 // desc: release the contents of the dump
1629 //-----------------------------------------------------------------------------
1630 void Chuck_VM::release_dump( )
1631 {
1632 // log
1633 EM_log( CK_LOG_FINER, "releasing dumped shreds..." );
1634
1635 // iterate through dump
1636 for( t_CKUINT i = 0; i < m_shred_dump.size(); i++ )
1637 {
1638 // detach ugens | 1.5.1.5 (moved here from inside shred destructor)
1639 // (ensure we always do this, even if release below doesn't
1640 // actually delete the shred due to reference count)
1641 m_shred_dump[i]->detach_ugens();
1642 // release
1643 CK_SAFE_RELEASE( m_shred_dump[i] );
1644 }
1645
1646 // clear the dump
1647 m_shred_dump.clear();
1648 // reset
1649 m_num_dumped_shreds = 0;
1650 }
1651
1652
1653
1654
1655 //-----------------------------------------------------------------------------
1656 // helper function
1657 //-----------------------------------------------------------------------------
1658 static void ckvm_process_watcher( t_CKBOOL add, list<Chuck_VM_Shreds_Watcher> & v,
1659 Chuck_VM_Shreds_Watcher & watcher )
1660 {
1661 // ensure no duplicates
1662 list<Chuck_VM_Shreds_Watcher>::iterator it = std::find( v.begin(), v.end(), watcher );
1663
1664 // add or remove
1665 if( add )
1666 {
1667 // if not found, add
1668 if( it == v.end() ) v.push_back( watcher );
1669 }
1670 else if( it != v.end() )
1671 {
1672 // erase it
1673 v.erase( it );
1674 }
1675 }
1676
1677
1678
1679
1680 //-----------------------------------------------------------------------------
1681 // name: subscribe_watcher() | 1.5.1.5
1682 // desc: subscribe shreds watcher callback
1683 //-----------------------------------------------------------------------------
1684 void Chuck_VM::subscribe_watcher( f_shreds_watcher cb, t_CKUINT options, void * userdata )
1685 {
1686 // check
1687 if( !cb ) return;
1688 // watcher bundle
1689 Chuck_VM_Shreds_Watcher w( cb, userdata );
1690 // check options and subscribe the watcher
1691 ckvm_process_watcher( options & ckvm_shreds_watch_SPORK, m_shreds_watchers_spork, w );
1692 ckvm_process_watcher( options & ckvm_shreds_watch_REMOVE, m_shreds_watchers_remove, w );
1693 ckvm_process_watcher( options & ckvm_shreds_watch_SUSPEND, m_shreds_watchers_suspend, w );
1694 ckvm_process_watcher( options & ckvm_shreds_watch_ACTIVATE, m_shreds_watchers_activate, w );
1695 }
1696
1697
1698
1699
1700 //-----------------------------------------------------------------------------
1701 // name: remove_watcher() | 1.5.1.5
1702 // desc: remove shreds watcher callback
1703 //-----------------------------------------------------------------------------
1704 void Chuck_VM::remove_watcher( f_shreds_watcher cb )
1705 {
1706 subscribe_watcher( cb, ckvm_shreds_watch_NONE );
1707 }
1708
1709
1710
1711
1712 //-----------------------------------------------------------------------------
1713 // name: Chuck_VM_Stack()
1714 // desc: constructor
1715 //-----------------------------------------------------------------------------
1716 Chuck_VM_Stack::Chuck_VM_Stack()
1717 {
1718 stack = sp = sp_max = NULL;
1719 prev = next = NULL;
1720 m_is_init = FALSE;
1721 m_size = 0;
1722 }
1723
1724
1725
1726
1727 //-----------------------------------------------------------------------------
1728 // name: ~Chuck_VM_Stack()
1729 // desc: desctructor
1730 //-----------------------------------------------------------------------------
1731 Chuck_VM_Stack::~Chuck_VM_Stack()
1732 {
1733 this->shutdown();
1734 }
1735
1736
1737
1738
1739 //-----------------------------------------------------------------------------
1740 // name: Chuck_VM_Code()
1741 // desc: constructor
1742 //-----------------------------------------------------------------------------
1743 Chuck_VM_Code::Chuck_VM_Code()
1744 {
1745 instr = NULL;
1746 num_instr = 0;
1747 stack_depth = 0;
1748 need_this = FALSE;
1749 is_static = FALSE;
1750 native_func = 0;
1751 native_func_kind = ae_fp_unknown;
1752 }
1753
1754
1755
1756
1757 //-----------------------------------------------------------------------------
1758 // name: ~Chuck_VM_Code()
1759 // desc: destructor
1760 //-----------------------------------------------------------------------------
1761 Chuck_VM_Code::~Chuck_VM_Code()
1762 {
1763 // free instructions
1764 if( instr )
1765 {
1766 // loop over array
1767 for( t_CKUINT i = 0; i < num_instr; i++ )
1768 delete instr[i];
1769
1770 // free the array
1771 CK_SAFE_DELETE_ARRAY( instr );
1772 }
1773
1774 num_instr = 0;
1775 }
1776
1777
1778
1779
1780 // minimum stack size | 1.5.1.5 (ge) added
1781 #define VM_STACK_MINIMUM_SIZE 2048
1782 // offset in bytes at the beginning of a stack for initializing data
1783 #define VM_STACK_OFFSET 16
1784 // overflow padding in bytes, to allow some overflow before detection
1785 #define VM_STACK_OVERFLOW_PADDING 512
1786 //-----------------------------------------------------------------------------
1787 // name: initialize()
1788 // desc: initialize VM stack, with at least 'size' bytes
1789 //-----------------------------------------------------------------------------
1790 t_CKBOOL Chuck_VM_Stack::initialize( t_CKUINT size )
1791 {
1792 // check if already initialized
1793 if( m_is_init ) return FALSE;
1794
1795 // ensure stack size >= minimum size | 1.5.1.5
1796 if( size < VM_STACK_MINIMUM_SIZE ) size = VM_STACK_MINIMUM_SIZE;
1797 // actual size in bytes to allocate; stack header + size + overflow pad
1798 t_CKUINT alloc_size = VM_STACK_OFFSET + size + VM_STACK_OVERFLOW_PADDING;
1799
1800 // allocate stack
1801 stack = new t_CKBYTE[alloc_size];
1802 if( !stack ) goto out_of_memory;
1803 // zero the memory
1804 memset( stack, 0, alloc_size );
1805
1806 // advance stack after the header
1807 stack += VM_STACK_OFFSET;
1808 // set the sp
1809 sp = stack;
1810 // upper limit (beyond which is the overflow padding)
1811 sp_max = stack + size;
1812 // remember size
1813 m_size = size;
1814
1815 // log
1816 EM_log( CK_LOG_FINER, "allocated VM stack (size:%lu alloc:%lu)", size, alloc_size );
1817
1818 // set flag and return
1819 return m_is_init = TRUE;
1820
1821 out_of_memory:
1822
1823 // we have a problem
1824 EM_exception( "OutOfMemory: VM stack [size=%lu alloc=%lu]", size, alloc_size );
1825
1826 // return FALSE
1827 return FALSE;
1828 }
1829
1830
1831
1832
1833 //-----------------------------------------------------------------------------
1834 // name: shutdown()
1835 // desc: shutdown and cleanup VM stack
1836 //-----------------------------------------------------------------------------
1837 t_CKBOOL Chuck_VM_Stack::shutdown()
1838 {
1839 if( !m_is_init )
1840 return FALSE;
1841
1842 // return stack to the allocation point
1843 stack -= VM_STACK_OFFSET;
1844 // free the stack
1845 CK_SAFE_DELETE_ARRAY( stack );
1846 // zero out the stack pointer
1847 sp = sp_max = NULL;
1848
1849 // set the flag to false
1850 m_is_init = FALSE;
1851 // set size to 0 | 1.5.1.5
1852 m_size = 0;
1853
1854 return TRUE;
1855 }
1856
1857
1858
1859
1860 //-----------------------------------------------------------------------------
1861 // name: Chuck_VM_Shred()
1862 // desc: constructor
1863 //-----------------------------------------------------------------------------
1864 Chuck_VM_Shred::Chuck_VM_Shred()
1865 {
1866 mem = NULL;
1867 reg = NULL;
1868 code = code_orig = NULL;
1869 next = prev = NULL;
1870 instr = NULL;
1871 parent = NULL;
1872 base_ref = NULL;
1873 vm_ref = NULL;
1874 event = NULL;
1875 xid = 0;
1876
1877 // initialize
1878 is_abort = FALSE;
1879 is_done = FALSE;
1880 is_dumped = FALSE;
1881 is_running = FALSE;
1882 pc = next_pc = 0;
1883 now = 0;
1884 start = 0;
1885 wake_time = 0;
1886
1887 // set children stack size hints to default | 1.5.1.5
1888 childSetMemSize( 0 );
1889 childSetRegSize( 0 );
1890
1891 // immediate mode | 1.5.1.5
1892 is_immediate_mode = FALSE;
1893 is_immediate_mode_violation = FALSE;
1894
1895 // garbage collection related | 1.5.2.0
1896 m_gc_inc = 0;
1897 m_gc_threshold = 4192; // default samps until next per-shred GC event
1898
1899 #ifndef __DISABLE_SERIAL__
1900 m_serials = NULL;
1901 #endif
1902
1903 // set
1904 CK_TRACK( stat = NULL );
1905 }
1906
1907
1908
1909
1910 //-----------------------------------------------------------------------------
1911 // name: ~Chuck_VM_Shred()
1912 // desc: destructor
1913 //-----------------------------------------------------------------------------
1914 Chuck_VM_Shred::~Chuck_VM_Shred()
1915 {
1916 this->shutdown();
1917 }
1918
1919
1920
1921
1922 //-----------------------------------------------------------------------------
1923 // name: initialize()
1924 // desc: initialize a shred from VM code
1925 //-----------------------------------------------------------------------------
1926 t_CKBOOL Chuck_VM_Shred::initialize( Chuck_VM_Code * c,
1927 t_CKUINT mem_stack_size,
1928 t_CKUINT reg_stack_size )
1929 {
1930 // ensure we don't multi-initialize the shred | 1.5.1.5
1931 // FYI explicitly call shutdown() before re-initializing shred
1932 if( mem ) return FALSE;
1933
1934 // verify
1935 assert( vm_ref != NULL );
1936
1937 // allocate new stacks
1938 mem = new Chuck_VM_Stack;
1939 reg = new Chuck_VM_Stack;
1940
1941 // check for default | 1.5.1.5
1942 if( mem_stack_size == 0 ) mem_stack_size = CKVM_MEM_STACK_SIZE;
1943 if( reg_stack_size == 0 ) reg_stack_size = CKVM_REG_STACK_SIZE;
1944
1945 // initialize mem and reg
1946 if( !mem->initialize( mem_stack_size ) ) goto error;
1947 if( !reg->initialize( reg_stack_size ) ) goto error;
1948
1949 // program counter
1950 pc = 0;
1951 next_pc = 1;
1952 // copy vm code for this shred
1953 CK_SAFE_REF_ASSIGN( code_orig, c );
1954 // initialize code to shred origin code
1955 code = code_orig;
1956 // set the instr | possible shred origin code == NULL (e.g., `Shred s;`)
1957 instr = code ? code->instr : NULL;
1958 // shred in dump (all done)
1959 is_dumped = FALSE;
1960 // shred done
1961 is_done = FALSE;
1962 // shred running
1963 is_running = FALSE;
1964 // shred abort
1965 is_abort = FALSE;
1966 // zero out the id
1967 xid = 0;
1968
1969 // initialize
1970 if( !initialize_object( this, vm_ref->env()->ckt_shred, this, vm_ref ) ) goto error;
1971
1972 // inherit size hints for shreds sporked from this shred | 1.5.1.5
1973 childSetMemSize( mem_stack_size );
1974 childSetRegSize( reg_stack_size );
1975
1976 return TRUE;
1977
1978 error:
1979 // clean up what has been allocated so far
1980 shutdown();
1981
1982 return FALSE;
1983 }
1984
1985
1986
1987
1988 //-----------------------------------------------------------------------------
1989 // name: detach_ugens()
1990 // desc: detach all associate ugens created on a shred
1991 //-----------------------------------------------------------------------------
1992 void Chuck_VM_Shred::detach_ugens()
1993 {
1994 // get iterator to our map
1995 map<Chuck_UGen *, Chuck_UGen *>::iterator iter = m_ugen_map.begin();
1996 // iterate over ugen attached to this shred
1997 while( iter != m_ugen_map.end() )
1998 {
1999 // get the ugen
2000 Chuck_UGen * ugen = iter->first;
2001 // make sure if ugen has an origin shred, it is this one | 1.5.1.5
2002 assert( !ugen->originShred() || ugen->originShred() == this );
2003 // also clear reference to this shred | 1.5.1.5
2004 ugen->setOriginShred( NULL );
2005 // disconnect
2006 ugen->disconnect( TRUE );
2007 // advance the iterator
2008 iter++;
2009 }
2010
2011 // prune UGens still associated with the shred by refcount...
2012 // ---
2013 // as of 1.5.4.2 this is no longer necessary in the general and non-OTF
2014 // case; but for OTF replace and remove, this will conservatively release
2015 // ugens (e.g., with refcount==1); see prune_ugens() for more info
2016 // ---
2017 // BUT WAIT... we can't reliably do this, because a UGen can be created
2018 // on a shred, copy its reference to a variable that originates from a
2019 // different shred and let the original reference go out of scope; this
2020 // could result in the UGen refcount==1 but should NOT be released yet.
2021 // COMMENTING OUT (again) NOTE: this affects OTF operations such as
2022 // remove and replace and (in theory) nothing beyond those, as there
2023 // are mechanisms for properly cleaning up UGens otherwise
2024 // ---
2025 // prune_ugens();
2026
2027 // clear map
2028 m_ugen_map.clear();
2029 }
2030
2031
2032
2033
2034 //-----------------------------------------------------------------------------
2035 // name: prune_ugens() | 1.5.2.0 (ge) added
2036 // desc: manually trigger a pruning of UGens that can be safely released,
2037 // associated with this shred, instead of waiting for the shred to finish
2038 // NOTE this can be useful if a shred dynamically creates a lot of
2039 // UGens without exiting
2040 // 1.5.4.2 (ge) NOTE this is no longer necessary as the new UGen/shred
2041 // semantics have been updated for these types of checks to happen on
2042 // a per-UGen level
2043 // 1.5.4.2 (ge) okay maybe we still do need this for OTF operations,
2044 // e.g., remove / replace, since currently those do not properly unwind
2045 // the execution contexts (see TODO below)
2046 // NOTE: this does not cover cases where a UGen has multiple variables
2047 // referencing it on this shred; currently there is no mechanism to know
2048 // if references are within a shred's context or outside of it
2049 //-----------------------------------------------------------------------------
2050 // TODO: the right way to handle this would be to carefully unwind the
2051 // shred's execution context: function call stacks and stmt-level releases
2052 // possibly letting the current stmt finish if there is memory to be released
2053 // AND then unwinding the call stack and releasing things along the way
2054 //-----------------------------------------------------------------------------
2055 void Chuck_VM_Shred::prune_ugens()
2056 {
2057 // check if we have anything in ugen map for this shred
2058 if( !m_ugen_map.size() )
2059 return;
2060
2061 // ugens to release
2062 std::vector<Chuck_UGen *> release_v;
2063
2064 // get iterator to our map
2065 map<Chuck_UGen *, Chuck_UGen *>::iterator iter = m_ugen_map.begin();
2066 while( iter != m_ugen_map.end() )
2067 {
2068 // get the ugen
2069 Chuck_UGen * ugen = iter->first;
2070
2071 // verify
2072 assert( ugen->refcount() > 0 );
2073 // check for ugens with only one reference (to this shred)
2074 if( ugen->refcount() == 1 ) release_v.push_back( ugen );
2075
2076 // advance the iterator
2077 iter++;
2078 }
2079
2080 // check if anything to prune
2081 if( release_v.size() )
2082 {
2083 // log
2084 EM_log( CK_LOG_FINE, "pruning '%ld' ugen(s) from shred: %x...", release_v.size(), this );
2085
2086 // loop over vector
2087 for( vector<Chuck_UGen *>::iterator rvi = release_v.begin();
2088 rvi != release_v.end(); rvi++ )
2089 {
2090 // remove from map
2091 m_ugen_map.erase( *rvi );
2092 // release the ugen
2093 CK_SAFE_RELEASE( *rvi );
2094 }
2095 // clear the release vector
2096 release_v.clear();
2097 }
2098 }
2099
2100
2101
2102
2103 //-----------------------------------------------------------------------------
2104 // name: gc_inc() | 1.5.2.0 (ge) added
2105 // desc: acrue towards a GC pass
2106 //-----------------------------------------------------------------------------
2107 void Chuck_VM_Shred::gc_inc( t_CKDUR inc )
2108 {
2109 // log
2110 // EM_log( CK_LOG_FINE, "accruing '%f' towards GC on shred: %x", inc, this );
2111
2112 // accumulate
2113 m_gc_inc += inc;
2114 // check threshold
2115 if( m_gc_inc > m_gc_threshold )
2116 {
2117 // invoke gc
2118 gc();
2119 // reset inc
2120 m_gc_inc = 0;
2121 }
2122 }
2123
2124
2125
2126
2127 //-----------------------------------------------------------------------------
2128 // name: gc() | 1.5.2.0 (ge) added
2129 // desc: manually trigger a pre-shred garbage collection pass
2130 //-----------------------------------------------------------------------------
2131 void Chuck_VM_Shred::gc()
2132 {
2133 // 1.5.4.2 (ge) this type of pruning is no longer necessary; FYI in any
2134 // case, this function was never activated in a release due to instabilty
2135 // this->prune_ugens();
2136 }
2137
2138
2139
2140
2141 //-----------------------------------------------------------------------------
2142 // name: shutdown()
2143 // desc: shutdown a shred
2144 //-----------------------------------------------------------------------------
2145 t_CKBOOL Chuck_VM_Shred::shutdown()
2146 {
2147 // detach ugens
2148 detach_ugens();
2149
2150 // check if we have parent object references to clean up
2151 if( m_parent_objects.size() )
2152 {
2153 // loop over parent object references (added 1.3.1.2)
2154 for( vector<Chuck_Object *>::iterator it = m_parent_objects.begin();
2155 it != m_parent_objects.end(); it++ )
2156 {
2157 // release it
2158 CK_SAFE_RELEASE( *it );
2159 }
2160 // clear the vectors (added 1.3.1.2)
2161 m_parent_objects.clear();
2162 }
2163
2164 // reclaim the stacks
2165 CK_SAFE_DELETE( mem );
2166 CK_SAFE_DELETE( reg );
2167 base_ref = NULL;
2168
2169 // release vm code
2170 CK_SAFE_RELEASE( code_orig );
2171 // clear it
2172 code_orig = code = NULL;
2173
2174 // set children stack size hints to default | 1.5.1.5
2175 childSetMemSize( 0 );
2176 childSetRegSize( 0 );
2177
2178 #ifndef __DISABLE_SERIAL__
2179 // HACK (added 1.3.2.0): close serial devices
2180 if( m_serials != NULL )
2181 {
2182 for( list<Chuck_IO_Serial *>::iterator i = m_serials->begin(); i != m_serials->end(); i++ )
2183 {
2184 // close first
2185 (*i)->close();
2186 // release
2187 CK_SAFE_RELEASE( *i );
2188 }
2189 // clear list
2190 m_serials->clear();
2191 // clean up list
2192 CK_SAFE_DELETE( m_serials );
2193 }
2194 #endif
2195
2196 // 1.3.5.3 pop all loop counters
2197 while( this->popLoopCounter() );
2198
2199 // NOTE what to do with next and prev? for now, nothing...
2200 // next/prev should be handled externally, e.g., by shreduler
2201
2202 return TRUE;
2203 }
2204
2205
2206
2207
2208 //-----------------------------------------------------------------------------
2209 // name: add()
2210 // desc: add a ugen to this shred's ugen map
2211 //-----------------------------------------------------------------------------
2212 t_CKBOOL Chuck_VM_Shred::add( Chuck_UGen * ugen )
2213 {
2214 if( !ugen || m_ugen_map[ugen] )
2215 return FALSE;
2216
2217 // increment reference count (added 1.3.0.0)
2218 // remove ref-count from VM-side | 1.5.4.2 (ge) part of #ugen-refs
2219 // CK_SAFE_ADD_REF( ugen );
2220
2221 m_ugen_map[ugen] = ugen;
2222 return TRUE;
2223 }
2224
2225
2226
2227
2228 //-----------------------------------------------------------------------------
2229 // name: remove()
2230 // desc: remove a ugen from this shred's ugen map
2231 //-----------------------------------------------------------------------------
2232 t_CKBOOL Chuck_VM_Shred::remove( Chuck_UGen * ugen )
2233 {
2234 if( !ugen || !m_ugen_map[ugen] )
2235 return FALSE;
2236
2237 // remove it
2238 m_ugen_map.erase( ugen );
2239
2240 // decrement reference count (added 1.3.0.0)
2241 // remove ref-count from VM-side | 1.5.4.2 (ge) part of #ugen-refs
2242 // ugen->release();
2243
2244 return TRUE;
2245 }
2246
2247
2248
2249
2250 //-----------------------------------------------------------------------------
2251 // name: add_parent_ref()
2252 // desc: add parent object reference (added 1.3.1.2)
2253 //-----------------------------------------------------------------------------
2254 t_CKVOID Chuck_VM_Shred::add_parent_ref( Chuck_Object * obj )
2255 {
2256 // sanity check
2257 if( !obj )
2258 return;
2259
2260 // reference count
2261 obj->add_ref();
2262
2263 // add it to vector
2264 m_parent_objects.push_back( obj );
2265 }
2266
2267
2268
2269
2270 //-----------------------------------------------------------------------------
2271 // name: childSetMemSize() | 1.5.1.3
2272 // desc: set hint; affects children shreds sporked from this one
2273 //-----------------------------------------------------------------------------
2274 t_CKINT Chuck_VM_Shred::childSetMemSize( t_CKINT sizeInBytes )
2275 {
2276 // check for negative
2277 if( sizeInBytes < 0 ) sizeInBytes = 0;
2278 // mem is call stack (for function calls / local vars)
2279 memStackSize = sizeInBytes;
2280 // return
2281 return childGetMemSize();
2282 }
2283 // get value (if 0, return default)
2284 t_CKINT Chuck_VM_Shred::childGetMemSize()
2285 { return memStackSize > 0 ? memStackSize : CKVM_MEM_STACK_SIZE; }
2286
2287
2288
2289
2290 //-----------------------------------------------------------------------------
2291 // name: childSetRegSize() | 1.5.1.3
2292 // desc: set hint; affects children shreds sporked from this one
2293 //-----------------------------------------------------------------------------
2294 t_CKINT Chuck_VM_Shred::childSetRegSize( t_CKINT sizeInBytes )
2295 {
2296 // check for negative
2297 if( sizeInBytes < 0 ) sizeInBytes = 0;
2298 // reg is operand stack (for evaluating expressions)
2299 regStackSize = sizeInBytes;
2300 // return
2301 return regStackSize;
2302 }
2303 // get value (if 0, return default)
2304 t_CKINT Chuck_VM_Shred::childGetRegSize()
2305 { return regStackSize > 0 ? regStackSize : CKVM_REG_STACK_SIZE; }
2306
2307
2308
2309
2310 //-----------------------------------------------------------------------------
2311 // mechanism to observe the growth of maximum stacks depth (reg and mem) across
2312 // all shreds; when enabled, this is called every instruction in the VM;
2313 // used to gauge stack utilization and to assess default shred stacks sizes
2314 // 1.5.1.5 (ge) added
2315 //-----------------------------------------------------------------------------
2316 static t_CKUINT g_mem_stack_depth_reached = 0;
2317 static t_CKUINT g_reg_stack_depth_reached = 0;
2318 static void ckvm_observe_stackdepth_across_all_shreds( Chuck_VM_Shred * currentShred )
2319 {
2320 // track stack depth
2321 t_CKBOOL printStackInfo = FALSE;
2322
2323 // mem stack (for local variables)
2324 t_CKUINT mem_depth = currentShred->mem->sp - currentShred->mem->stack;
2325 if( mem_depth > g_mem_stack_depth_reached )
2326 {
2327 g_mem_stack_depth_reached = mem_depth;
2328 printStackInfo = TRUE;
2329 }
2330
2331 // mem stack (for operands, e.g., in expression or in array initializer lists)
2332 t_CKUINT reg_depth = currentShred->reg->sp - currentShred->reg->stack;
2333 if( reg_depth > g_reg_stack_depth_reached )
2334 {
2335 g_reg_stack_depth_reached = reg_depth;
2336 printStackInfo = TRUE;
2337 }
2338
2339 // something new to print
2340 if( printStackInfo )
2341 {
2342 CK_FPRINTF_STDERR( "[chuck]:(VM DEBUG) global max stack depths -> mem:%lu reg:%lu\n",
2343 g_mem_stack_depth_reached, g_reg_stack_depth_reached );
2344 }
2345 }
2346
2347
2348
2349
2350 //-----------------------------------------------------------------------------
2351 // name: run()
2352 // desc: run this shred's VM code
2353 //-----------------------------------------------------------------------------
2354 t_CKBOOL Chuck_VM_Shred::run( Chuck_VM * vm )
2355 {
2356 // get the code
2357 instr = code->instr;
2358 is_running = TRUE;
2359 // pointer to running state
2360 const t_CKBOOL * loop_running = &(vm_ref->runningState());
2361
2362 // go!
2363 while( is_running && *loop_running && !is_abort )
2364 {
2365 //-----------------------------------------------------------------------------
2366 CK_VM_STACK_DEBUG( CK_FPRINTF_STDERR( "CK_VM_DEBUG =--------------------------------=\n" ) );
2367 CK_VM_STACK_DEBUG( CK_FPRINTF_STDERR( "CK_VM_DEBUG shred %04lu code %s pc %04lu %s( %s )\n",
2368 this->xid, this->code->name.c_str(), this->pc, instr[pc]->name(),
2369 instr[pc]->params() ) );
2370 CK_VM_STACK_DEBUG( t_CKBYTE * t_mem_sp = this->mem->sp );
2371 CK_VM_STACK_DEBUG( t_CKBYTE * t_reg_sp = this->reg->sp );
2372 //-----------------------------------------------------------------------------
2373 // execute the instruction
2374 instr[pc]->execute( vm, this );
2375 //-----------------------------------------------------------------------------
2376 CK_VM_STACK_DEBUG( CK_FPRINTF_STDERR( "CK_VM_DEBUG mem sp in: 0x%08lx out: 0x%08lx\n",
2377 (unsigned long)t_mem_sp, (unsigned long)this->mem->sp ) );
2378 CK_VM_STACK_DEBUG( CK_FPRINTF_STDERR( "CK_VM_DEBUG reg sp in: 0x%08lx out: 0x%08lx\n",
2379 (unsigned long)t_reg_sp, (unsigned long)this->reg->sp ) );
2380 //-----------------------------------------------------------------------------
2381 // detect operand stack overflow | 1.5.1.5
2382 if( overflow_( this->reg ) )
2383 { ck_handle_overflow( this, vm_ref, "shred operand stack exceeded" ); break; }
2384 // detect mem stack overflow ("catch all") | 1.5.1.5
2385 // NOTE func-call & alloc instrucions already detect
2386 if( overflow_( this->mem ) && is_running ) // <- is_running==FALSE if already detected
2387 { ck_handle_overflow( this, vm_ref, "shred memory stack exceeded" ); break; }
2388
2389 // set to next_pc;
2390 pc = next_pc;
2391 // advance program counter
2392 next_pc++;
2393
2394 // track number of cycles
2395 CK_TRACK( this->stat->cycles++ );
2396 // if enabled, update shred stacks depth observation | 1.5.1.5
2397 CK_VM_STACK_OBSERVE( ckvm_observe_stackdepth_across_all_shreds( this ) );
2398 }
2399
2400 // check abort
2401 if( is_abort )
2402 {
2403 // log
2404 EM_log( CK_LOG_SYSTEM, "aborting shred (id: %lu)", this->xid );
2405 // done
2406 is_done = TRUE;
2407 }
2408
2409 // is the shred finished
2410 return !is_done;
2411 }
2412
2413
2414
2415
2416 //-----------------------------------------------------------------------------
2417 // name: yield() | 1.5.0.5 (ge) made this a function from scattered code
2418 // desc: yield the shred in vm (without advancing time, politely yield to run
2419 // all other shreds waiting to run at the current
2420 // same in effect as 0::second +=> now;
2421 //-----------------------------------------------------------------------------
2422 t_CKBOOL Chuck_VM_Shred::yield()
2423 {
2424 // need a VM to yield on
2425 if( !this->vm_ref ) return FALSE;
2426
2427 // check for immediate mode exception | 1.5.1.5 (ge)
2428 if( this->checkImmediatModeException() ) return FALSE;
2429
2430 // suspend this shred
2431 this->is_running = FALSE;
2432 // reshredule this at the current time
2433 vm_ref->shreduler()->shredule( this, this->now );
2434
2435 // done
2436 return TRUE;
2437 }
2438
2439
2440
2441
2442 #ifndef __DISABLE_SERIAL__
2443 //-----------------------------------------------------------------------------
2444 // name: add_serialio()
2445 // desc: add serial IO (for event synchronization)
2446 //-----------------------------------------------------------------------------
2447 t_CKVOID Chuck_VM_Shred::add_serialio( Chuck_IO_Serial * serial )
2448 {
2449 // instantiate list if needed
2450 if( m_serials == NULL )
2451 m_serials = new list<Chuck_IO_Serial *>;
2452 // add reference
2453 serial->add_ref();
2454 // append to list
2455 m_serials->push_back( serial );
2456 }
2457
2458
2459
2460
2461 //-----------------------------------------------------------------------------
2462 // name: remove_serialio()
2463 // desc: remove serial IO
2464 //-----------------------------------------------------------------------------
2465 t_CKVOID Chuck_VM_Shred::remove_serialio( Chuck_IO_Serial * serial )
2466 {
2467 // check
2468 if( m_serials == NULL ) return;
2469 // remove from list
2470 m_serials->remove( serial );
2471 // release
2472 serial->release();
2473 }
2474 #endif
2475
2476
2477
2478
2479 //-----------------------------------------------------------------------------
2480 // name: pushLoopCounter()
2481 // desc: make and push new loop counter
2482 //-----------------------------------------------------------------------------
2483 t_CKUINT * Chuck_VM_Shred::pushLoopCounter()
2484 {
2485 // new pointer
2486 t_CKUINT * counter = new t_CKUINT;
2487 // add to stack
2488 m_loopCounters.push_back(counter);
2489 // return it
2490 return counter;
2491 }
2492
2493
2494
2495
2496 //-----------------------------------------------------------------------------
2497 // name: currentLoopCounter()
2498 // desc: get top loop counter
2499 //-----------------------------------------------------------------------------
2500 t_CKUINT * Chuck_VM_Shred::currentLoopCounter()
2501 {
2502 // check it
2503 if( m_loopCounters.size() == 0 ) return NULL;
2504 // return it
2505 return m_loopCounters[m_loopCounters.size()-1];
2506 }
2507
2508
2509
2510
2511 //-----------------------------------------------------------------------------
2512 // name: popLoopCounter()
2513 // desc: pop and clean up loop counter
2514 //-----------------------------------------------------------------------------
2515 bool Chuck_VM_Shred::popLoopCounter()
2516 {
2517 // check it
2518 if( m_loopCounters.size() == 0 ) return false;
2519 // delete
2520 delete m_loopCounters[m_loopCounters.size()-1];
2521 // return it
2522 m_loopCounters.pop_back();
2523 // done
2524 return true;
2525 }
2526
2527
2528
2529
2530 //-----------------------------------------------------------------------------
2531 // name: checkImmediatModeException() | 1.5.1.5 (ge) added
2532 // desc: check for immediate mode exception, if detected print and set state
2533 //-----------------------------------------------------------------------------
2534 t_CKBOOL Chuck_VM_Shred::checkImmediatModeException( t_CKUINT linepos )
2535 {
2536 // check for immediate mode
2537 if( this->immediateMode() )
2538 {
2539 // we have a problem
2540 EM_exception( "ImmediateModeTemporalViolation:" );
2541 // check linepos
2542 if( linepos ) EM_exception( " |- on line %lu within %s", linepos, this->name.c_str() );
2543 else EM_exception( " |- within %s", this->name.c_str() );
2544 // more info
2545 EM_error3(
2546 "\nThis exception is thrown if shred has been placed in IMMEDIATE MODE\n"
2547 "and performs any time/event-related, context-switching operations, including:\n"
2548 " 1) advancing time (including by 0 duration),\n"
2549 " 2) or waiting on an Event,\n"
2550 " 3) or callling `me.yield()` or `Machine.eval()`;\n"
2551 " (the latter implicits yields to runs code on a new shred)." );
2552 // more info
2553 EM_error3(
2554 "\nIMMEDIATE MODE is set by the ChucK virtual machine in specific cases\n"
2555 "where the programmer is to provide a time-critical callback function\n"
2556 "that is expected to return \"immediately\", i.e., without any shreduling.\n"
2557 "Examples include `tick()` in Chugens and `update()` in GGens." );
2558 // potential fix
2559 EM_error3(
2560 "\nPotential fix: ensure the function in question has no time/event operations as\n"
2561 "described above, either directly in the function or its function calls.\n"
2562 "(NB `spork ~` and `Machine.add()` can be used in this mode, as these are\n"
2563 "non-context-switching.)\n------");
2564 // set violation
2565 is_immediate_mode_violation = TRUE;
2566 // report back
2567 return TRUE;
2568 }
2569
2570 // situation normal
2571 return FALSE;
2572 }
2573
2574
2575
2576 //-----------------------------------------------------------------------------
2577 // name: Chuck_VM_Shreduler()
2578 // desc: constructor
2579 //-----------------------------------------------------------------------------
2580 Chuck_VM_Shreduler::Chuck_VM_Shreduler()
2581 {
2582 now_system = 0;
2583 vm_ref = NULL;
2584 shred_list = NULL;
2585 m_current_shred = NULL;
2586 m_dac = NULL;
2587 m_adc = NULL;
2588 m_bunghole = NULL;
2589 m_num_dac_channels = 0;
2590 m_num_adc_channels = 0;
2591
2592 set_adaptive( 0 );
2593 }
2594
2595
2596
2597
2598 //-----------------------------------------------------------------------------
2599 // name: ~Chuck_VM_Shreduler()
2600 // desc: destructor
2601 //-----------------------------------------------------------------------------
2602 Chuck_VM_Shreduler::~Chuck_VM_Shreduler()
2603 {
2604 this->shutdown();
2605 }
2606
2607
2608
2609
2610 //-----------------------------------------------------------------------------
2611 // name: initialize()
2612 // desc: initialize shreduler
2613 //-----------------------------------------------------------------------------
2614 t_CKBOOL Chuck_VM_Shreduler::initialize()
2615 {
2616 return TRUE;
2617 }
2618
2619
2620
2621
2622 //-----------------------------------------------------------------------------
2623 // name: shutdown()
2624 // desc: shutdown shreduler
2625 //-----------------------------------------------------------------------------
2626 t_CKBOOL Chuck_VM_Shreduler::shutdown()
2627 {
2628 return TRUE;
2629 }
2630
2631
2632
2633
2634 //-----------------------------------------------------------------------------
2635 // name: set_adaptive()
2636 // desc: set adaptive mode (and adapative mode max block size)
2637 //-----------------------------------------------------------------------------
2638 void Chuck_VM_Shreduler::set_adaptive( t_CKUINT max_block_size )
2639 {
2640 m_max_block_size = max_block_size > 1 ? max_block_size : 0;
2641 m_adaptive = m_max_block_size > 1;
2642 m_samps_until_next = -1;
2643 }
2644
2645
2646
2647
2648 //-----------------------------------------------------------------------------
2649 // name: add_blocked()
2650 // desc: add shred to the shreduler's blocked list
2651 //-----------------------------------------------------------------------------
2652 t_CKBOOL Chuck_VM_Shreduler::add_blocked( Chuck_VM_Shred * shred )
2653 {
2654 // add shred to map, using pointer
2655 blocked[shred] = shred;
2656
2657 return TRUE;
2658 }
2659
2660
2661
2662
2663 //-----------------------------------------------------------------------------
2664 // name: remove_blocked()
2665 // desc: remove shred from the shreduler's blocked list
2666 //-----------------------------------------------------------------------------
2667 t_CKBOOL Chuck_VM_Shreduler::remove_blocked( Chuck_VM_Shred * shred )
2668 {
2669 // remove from hash
2670 std::map<Chuck_VM_Shred *, Chuck_VM_Shred *>::iterator iter;
2671 iter = blocked.find( shred );
2672 blocked.erase( iter );
2673
2674 // remove from event
2675 if( shred->event != NULL )
2676 {
2677 Chuck_Event * event_to_release = shred->event;
2678 // this call causes shred->event to become a null pointer
2679 shred->event->remove( shred );
2680 // but, we still have to release the event afterward
2681 // to signify that the shred is done using the event
2682 CK_SAFE_RELEASE( event_to_release );
2683 }
2684
2685 return TRUE;
2686 }
2687
2688
2689
2690
2691 //-----------------------------------------------------------------------------
2692 // name: shredule()
2693 // desc: shredule a shred in the shreduler
2694 //-----------------------------------------------------------------------------
2695 t_CKBOOL Chuck_VM_Shreduler::shredule( Chuck_VM_Shred * shred )
2696 {
2697 return this->shredule( shred, now_system );
2698 }
2699
2700
2701
2702
2703 //-----------------------------------------------------------------------------
2704 // name: shredule()
2705 // desc: shredule a shred in the shreduler by wake time
2706 //-----------------------------------------------------------------------------
2707 t_CKBOOL Chuck_VM_Shreduler::shredule( Chuck_VM_Shred * shred,
2708 t_CKTIME wake_time )
2709 {
2710 // sanity check
2711 if( shred->prev || shred->next )
2712 {
2713 // something is really wrong here - no shred can be
2714 // shreduled more than once
2715 EM_error2( 0, "(VM) internal consistency check failed in shredule()" );
2716 EM_error2( 0, "(VM) |- (shred shreduled while shreduled)" );
2717
2718 return FALSE;
2719 }
2720
2721 // sanity check
2722 if( wake_time < (this->now_system - .5) )
2723 {
2724 // trying to enqueue on a time that is less than now
2725 EM_error2( 0, "(VM) internal consistency check failed in shredule()" );
2726 EM_error2( 0, "(VM) |- (wake time is past) - %f : %f", wake_time, this->now_system );
2727
2728 return FALSE;
2729 }
2730
2731 // check for immediate mode and report exception | 1.5.1.5 (ge)
2732 if( shred->checkImmediatModeException() )
2733 {
2734 // let's not shredule!
2735 return FALSE;
2736 }
2737
2738 // set wake time
2739 shred->wake_time = wake_time;
2740
2741 // list empty
2742 if( !shred_list )
2743 shred_list = shred;
2744 else
2745 {
2746 // pointers to the shred queue
2747 Chuck_VM_Shred * curr = shred_list;
2748 Chuck_VM_Shred * prev = NULL;
2749
2750 while( curr )
2751 {
2752 // found the place to insert
2753 if( curr->wake_time > wake_time )
2754 break;
2755
2756 prev = curr;
2757 curr = curr->next;
2758 }
2759
2760 if( !prev )
2761 {
2762 shred->next = shred_list;
2763 if( shred_list ) shred_list->prev = shred;
2764 shred_list = shred;
2765 }
2766 else
2767 {
2768 // insert the shred in sorted order
2769 shred->next = prev->next;
2770 shred->prev = prev;
2771 if( prev->next ) prev->next->prev = shred;
2772 prev->next = shred;
2773 }
2774 }
2775
2776 t_CKTIME diff = shred_list->wake_time - this->now_system;
2777 if( diff < 0 ) diff = 0;
2778 // if( diff < m_samps_until_next )
2779 m_samps_until_next = diff;
2780
2781 return TRUE;
2782 }
2783
2784
2785
2786
2787 //-----------------------------------------------------------------------------
2788 // name: advance_v()
2789 // desc: advance the shreduler, v is for vectorize
2790 //-----------------------------------------------------------------------------
2791 void Chuck_VM_Shreduler::advance_v( t_CKINT & numLeft, t_CKINT & offset )
2792 {
2793 t_CKINT i, j, numFrames;
2794 SAMPLE gain[256], sum;
2795
2796 #ifdef __CHUCK_USE_PLANAR_BUFFERS__
2797 // planar buffers means non-interleaved. this is required for some platforms,
2798 // e.g. WebAudio
2799 const SAMPLE * input = vm_ref->input_ref() + offset;
2800 SAMPLE * output = vm_ref->output_ref() + offset;
2801 t_CKUINT buffer_length = vm_ref->most_recent_buffer_length();
2802 #else
2803 // get audio data from VM
2804 const SAMPLE * input = vm_ref->input_ref() + (offset*m_num_adc_channels);
2805 SAMPLE * output = vm_ref->output_ref() + (offset*m_num_dac_channels);
2806 #endif
2807
2808 // compute number of frames to compute; update
2809 numFrames = ck_min( m_max_block_size, numLeft );
2810 if( this->m_samps_until_next >= 0 )
2811 {
2812 numFrames = (t_CKINT)(ck_min( numFrames, this->m_samps_until_next ));
2813 if( numFrames == 0 ) numFrames = 1;
2814 this->m_samps_until_next -= numFrames;
2815 }
2816 numLeft -= numFrames;
2817 offset += numFrames;
2818
2819 // advance system 'now'
2820 this->now_system += numFrames;
2821
2822 // ???
2823 for( j = 0; j < m_num_adc_channels; j++ )
2824 {
2825 // update channel
2826 m_adc->m_multi_chan[j]->m_time = this->now_system;
2827 // cache gain
2828 gain[j] = m_adc->m_multi_chan[j]->m_gain;
2829 }
2830
2831 // INPUT: adaptive block
2832 for( i = 0; i < numFrames; i++ )
2833 {
2834 // clear
2835 sum = 0.0f;
2836 // loop over channels
2837 for( j = 0; j < m_num_adc_channels; j++ )
2838 {
2839 #ifdef __CHUCK_USE_PLANAR_BUFFERS__
2840 // current frame = offset + i
2841 // current channel = j
2842 // sample = buffer size * j + offset + i
2843 // the "+offset" is taken care of in initialization
2844 // the "+i" is taken care of by incrementing input below
2845 m_adc->m_multi_chan[j]->m_current_v[i] = input[buffer_length * j] * gain[j] * m_adc->m_gain;
2846 #else
2847 m_adc->m_multi_chan[j]->m_current_v[i] = input[j] * gain[j] * m_adc->m_gain;
2848 #endif
2849 sum += m_adc->m_multi_chan[j]->m_current_v[i];
2850 }
2851 m_adc->m_current_v[i] = sum / m_num_adc_channels;
2852
2853 // advance pointer
2854 #ifdef __CHUCK_USE_PLANAR_BUFFERS__
2855 input++;
2856 #else
2857 input += m_num_adc_channels;
2858 #endif
2859 }
2860
2861 // ???
2862 for( j = 0; j < m_num_adc_channels; j++ )
2863 {
2864 // update last
2865 m_adc->m_multi_chan[j]->m_last = m_adc->m_multi_chan[j]->m_current_v[numFrames-1];
2866 }
2867 // update last
2868 m_adc->m_last = m_adc->m_current_v[numFrames-1];
2869 // update time
2870 m_adc->m_time = this->now_system;
2871
2872 // PROCESSING
2873 m_dac->system_tick_v( this->now_system, numFrames );
2874
2875 // suck samples
2876 m_bunghole->system_tick_v( this->now_system, numFrames );
2877
2878 // OUTPUT: adaptive block
2879 for( i = 0; i < numFrames; i++ )
2880 {
2881 for( j = 0; j < m_num_dac_channels; j++ )
2882 {
2883 #ifdef __CHUCK_USE_PLANAR_BUFFERS__
2884 // current frame = offset + i
2885 // current channel = j
2886 // sample = buffer size * j + offset + i
2887 // "+offset" taken care of in initialization
2888 // "+i" taken care of by incrementing below
2889 output[buffer_length * j] = m_dac->m_multi_chan[j]->m_current_v[i];
2890 #else
2891 output[j] = m_dac->m_multi_chan[j]->m_current_v[i];
2892 #endif
2893 }
2894
2895 // advance pointer
2896 #ifdef __CHUCK_USE_PLANAR_BUFFERS__
2897 output++;
2898 #else
2899 output += m_num_dac_channels;
2900 #endif
2901 }
2902 }
2903
2904
2905
2906
2907 //-----------------------------------------------------------------------------
2908 // name: advance()
2909 // desc: advance the shreduler
2910 //-----------------------------------------------------------------------------
2911 void Chuck_VM_Shreduler::advance( t_CKINT N )
2912 {
2913 // advance system 'now'
2914 this->now_system += 1;
2915
2916 // tick the dac; TODO: unhardcoded frame size!
2917 SAMPLE sum = 0.0f;
2918 t_CKUINT i;
2919 // input and output
2920 #ifdef __CHUCK_USE_PLANAR_BUFFERS__
2921 const SAMPLE * input = vm_ref->input_ref() + N;
2922 SAMPLE * output = vm_ref->output_ref() + N;
2923 t_CKUINT buffer_length = vm_ref->most_recent_buffer_length();
2924 #else
2925 const SAMPLE * input = vm_ref->input_ref() + (N*m_num_adc_channels);
2926 SAMPLE * output = vm_ref->output_ref() + (N*m_num_dac_channels);
2927 #endif
2928
2929 // INPUT: loop over channels
2930 for( i = 0; i < m_num_adc_channels; i++ )
2931 {
2932 // ge: switched order of lines 1.3.5.3
2933 m_adc->m_multi_chan[i]->m_last = m_adc->m_multi_chan[i]->m_current;
2934 #ifdef __CHUCK_USE_PLANAR_BUFFERS__
2935 // current frame = N
2936 // current channel = i
2937 // sample = buffer size * i + N
2938 // the +N is taken care of by initialization
2939 m_adc->m_multi_chan[i]->m_current = input[buffer_length * i] * m_adc->m_multi_chan[i]->m_gain * m_adc->m_gain;
2940 #else
2941 m_adc->m_multi_chan[i]->m_current = input[i] * m_adc->m_multi_chan[i]->m_gain * m_adc->m_gain;
2942 #endif
2943 m_adc->m_multi_chan[i]->m_time = this->now_system;
2944 sum += m_adc->m_multi_chan[i]->m_current;
2945 }
2946 m_adc->m_last = m_adc->m_current = sum / m_num_adc_channels;
2947 m_adc->m_time = this->now_system;
2948
2949 // PROCESSING
2950 m_dac->system_tick( this->now_system );
2951 // OUTPUT
2952 for( i = 0; i < m_num_dac_channels; i++ )
2953 {
2954 #ifdef __CHUCK_USE_PLANAR_BUFFERS__
2955 // current frame = N
2956 // current channel = i
2957 // sample = buffer size * i + N
2958 // the +N is taken care of by initialization
2959 output[buffer_length * i] = m_dac->m_multi_chan[i]->m_current; // * .5f;
2960 #else
2961 output[i] = m_dac->m_multi_chan[i]->m_current; // * .5f;
2962 #endif
2963 }
2964
2965 // suck samples
2966 m_bunghole->system_tick( this->now_system );
2967 }
2968
2969
2970
2971
2972 //-----------------------------------------------------------------------------
2973 // name: get()
2974 // desc: get the next shred shreduled to run 'now'
2975 // NOTE if a shred is ready to run, it is taken off the ready-to-run list
2976 //-----------------------------------------------------------------------------
2977 Chuck_VM_Shred * Chuck_VM_Shreduler::get( )
2978 {
2979 // shreduler's wait to run list
2980 Chuck_VM_Shred * shred = shred_list;
2981
2982 // check if list empty
2983 if( !shred )
2984 {
2985 // if empty we are done
2986 m_samps_until_next = -1;
2987 return NULL;
2988 }
2989
2990 // check the front of the shred wait-to-run list; ready to run?
2991 if( shred->wake_time <= ( this->now_system + .5 ) )
2992 {
2993 // set beginning of list to next
2994 shred_list = shred->next;
2995
2996 // sever links of ready-to-run shred
2997 shred->next = NULL;
2998 shred->prev = NULL;
2999
3000 // if shred list is non-empty
3001 if( shred_list )
3002 {
3003 // set list head's prev pointer to NULL
3004 shred_list->prev = NULL;
3005 // compute new samps until next
3006 m_samps_until_next = shred_list->wake_time - this->now_system;
3007 // clamp to 0
3008 if( m_samps_until_next < 0 ) m_samps_until_next = 0;
3009 }
3010
3011 // return
3012 return shred;
3013 }
3014
3015 // nothing is ready to run 'now'
3016 return NULL;
3017 }
3018
3019
3020
3021
3022 //-----------------------------------------------------------------------------
3023 // name: highest()
3024 // desc: get ID of shred currently with the highest ID
3025 //-----------------------------------------------------------------------------
3026 t_CKUINT Chuck_VM_Shreduler::highest() const
3027 {
3028 // vessel for shred pointers
3029 std::vector<Chuck_VM_Shred *> shreds;
3030 // highest so far
3031 t_CKUINT n = 0;
3032
3033 // get all shreds
3034 get_all_shreds( shreds );
3035
3036 // loop
3037 for( t_CKUINT i = 0; i < shreds.size(); i++ )
3038 {
3039 // compare
3040 if( shreds[i]->get_id() > n ) n = shreds[i]->get_id();
3041 }
3042
3043 return n;
3044 }
3045
3046
3047
3048
3049 //-----------------------------------------------------------------------------
3050 // name: replace()
3051 // desc: replace a shred in the shreduler with a new shred
3052 //-----------------------------------------------------------------------------
3053 t_CKBOOL Chuck_VM_Shreduler::replace( Chuck_VM_Shred * out, Chuck_VM_Shred * in )
3054 {
3055 assert( FALSE );
3056
3057 // sanity check
3058 if( !out || !in )
3059 return FALSE;
3060
3061 if( !out->prev )
3062 shred_list = in;
3063 else
3064 out->prev->next = in;
3065
3066 if( out->next )
3067 out->next->prev = in;
3068
3069 in->next = out->next;
3070 in->prev = out->prev;
3071
3072 out->next = out->prev = NULL;
3073
3074 in->wake_time = out->wake_time;
3075 in->start = in->wake_time;
3076
3077 return TRUE;
3078 }
3079
3080
3081
3082
3083 //-----------------------------------------------------------------------------
3084 // name: remove()
3085 // desc: remove a shred from the shreduler
3086 //-----------------------------------------------------------------------------
3087 t_CKBOOL Chuck_VM_Shreduler::remove( Chuck_VM_Shred * out )
3088 {
3089 if( !out ) return FALSE;
3090
3091 // if blocked
3092 if( out->event != NULL )
3093 {
3094 return remove_blocked( out );
3095 }
3096
3097 // if current shred | 1.5.1.3 (ge) added
3098 if( out == m_current_shred )
3099 {
3100 // flag as done, and let the VM gracefully clean up the current shred
3101 m_current_shred->is_done = TRUE;
3102 m_current_shred->is_abort = TRUE;
3103 return TRUE;
3104 }
3105
3106 // sanity check
3107 if( !out->prev && !out->next && out != shred_list )
3108 return FALSE;
3109
3110 if( !out->prev )
3111 shred_list = out->next;
3112 else
3113 out->prev->next = out->next;
3114
3115 if( out->next )
3116 out->next->prev = out->prev;
3117
3118 out->next = out->prev = NULL;
3119
3120 return TRUE;
3121 }
3122
3123
3124
3125
3126 //-----------------------------------------------------------------------------
3127 // name: lookup()
3128 // desc: look up a shred by ID
3129 //-----------------------------------------------------------------------------
3130 Chuck_VM_Shred * Chuck_VM_Shreduler::lookup( t_CKUINT xid ) const
3131 {
3132 Chuck_VM_Shred * shred = shred_list;
3133
3134 // current shred?
3135 if( m_current_shred != NULL && m_current_shred->xid == xid )
3136 return m_current_shred;
3137
3138 // look for in shreduled list
3139 while( shred )
3140 {
3141 if( shred->xid == xid )
3142 return shred;
3143
3144 shred = shred->next;
3145 }
3146
3147 // blocked?
3148 std::map<Chuck_VM_Shred *, Chuck_VM_Shred *>::const_iterator iter;
3149 for( iter = blocked.begin(); iter != blocked.end(); iter++ )
3150 {
3151 shred = (*iter).second;
3152 if( shred->xid == xid )
3153 return shred;
3154 }
3155
3156 return NULL;
3157 }
3158
3159
3160
3161
3162 //-----------------------------------------------------------------------------
3163 // name: get_ready_shreds()
3164 // desc: retrieve the ready list of shreds in the shreduler
3165 //
3166 // NOTE shreds on the shreduler's ready list are sorted by
3167 // wake-up time (e.g., as specifiedy by `second => now`)
3168 // NOTE the ready list DO NOT include shreds waiting on Events
3169 // waiting shreds are on the shreduler's blocked list
3170 // NOTE the ready list does not include the shred currently
3171 // executing in the VM
3172 //-----------------------------------------------------------------------------
3173 void Chuck_VM_Shreduler::get_ready_shreds( std::vector<Chuck_VM_Shred *> & shreds,
3174 t_CKBOOL clearVector ) const
3175 {
3176 // clear; if not clear, then will append to existing contents
3177 if( clearVector ) shreds.clear();
3178
3179 // shred pointer
3180 Chuck_VM_Shred * shred = shred_list;
3181
3182 // traverse shred list
3183 while( shred )
3184 {
3185 // add
3186 shreds.push_back( shred );
3187 // next
3188 shred = shred->next;
3189 }
3190 }
3191
3192
3193
3194
3195 //-----------------------------------------------------------------------------
3196 // name: get_ready_shred_ids() | 1.5.0.8 (ge) added
3197 // desc: retrieve list of ready shred IDs
3198 //-----------------------------------------------------------------------------
3199 void Chuck_VM_Shreduler::get_ready_shred_ids( std::vector<t_CKUINT> & shredIDs,
3200 t_CKBOOL clearVector ) const
3201 {
3202 // clear; if not clear, then will append to existing contents
3203 if( clearVector ) shredIDs.clear();
3204
3205 // list for shreds
3206 std::vector<Chuck_VM_Shred *> shreds;
3207 // get shreds
3208 get_ready_shreds( shreds );
3209
3210 // traverse shred list
3211 for( t_CKUINT i = 0; i < shreds.size(); i++ )
3212 {
3213 // append id
3214 shredIDs.push_back( shreds[i]->xid );
3215 }
3216 }
3217
3218
3219
3220
3221 //-----------------------------------------------------------------------------
3222 // name: get_blocked_shreds() | 1.5.0.8 (ge) added
3223 // desc: retrieve the list of active shreds in the shreduler
3224 //
3225 // NOTE active shreds are on the shreduler's ready list, sorted by
3226 // wake-up time (e.g., as specifiedy by `second => now`)
3227 // NOTE active shreds list DO NOT include shreds waiting on Events
3228 // such shreds are on the shreduler's blocked list
3229 //-----------------------------------------------------------------------------
3230 void Chuck_VM_Shreduler::get_blocked_shreds( std::vector<Chuck_VM_Shred *> & shreds,
3231 t_CKBOOL clearVector ) const
3232 {
3233 // clear; if not clear, then will append to existing contents
3234 if( clearVector ) shreds.clear();
3235
3236 // iterate through blocked list
3237 std::map<Chuck_VM_Shred *, Chuck_VM_Shred *>::const_iterator iter;
3238 for( iter = blocked.begin(); iter != blocked.end(); iter++ )
3239 {
3240 // append the shred pointer
3241 shreds.push_back( (*iter).second );
3242 }
3243 }
3244
3245
3246
3247
3248 //-----------------------------------------------------------------------------
3249 // name: get_blocked_shred_ids() | 1.5.0.8 (ge) added
3250 // desc: retrieve list of active shred IDs
3251 //-----------------------------------------------------------------------------
3252 void Chuck_VM_Shreduler::get_blocked_shred_ids( std::vector<t_CKUINT> & shredIDs,
3253 t_CKBOOL clearVector ) const
3254 {
3255 // clear; if not clear, then will append to existing contents
3256 if( clearVector ) shredIDs.clear();
3257
3258 // list for shreds
3259 std::vector<Chuck_VM_Shred *> shreds;
3260 // get shreds
3261 get_blocked_shreds( shreds );
3262
3263 // traverse shred list
3264 for( t_CKUINT i = 0; i < shreds.size(); i++ )
3265 {
3266 // append id
3267 shredIDs.push_back( shreds[i]->xid );
3268 }
3269 }
3270
3271
3272
3273
3274 //-----------------------------------------------------------------------------
3275 // name: get_current_shred()
3276 // desc: get currently executing shred
3277 // NOTE this can only be non-NULL during a Chuck_VM::compute() cycle
3278 //-----------------------------------------------------------------------------
3279 Chuck_VM_Shred * Chuck_VM_Shreduler::get_current_shred() const
3280 {
3281 return m_current_shred;
3282 }
3283
3284
3285
3286
3287 //-----------------------------------------------------------------------------
3288 // name: get_active_get_all_shredsshreds() | 1.5.0.8 (ge) added
3289 // desc: retrieve the list of active shreds in the shreduler
3290 //
3291 // NOTE active shreds are on the shreduler's ready list, sorted by
3292 // wake-up time (e.g., as specifiedy by `second => now`)
3293 // NOTE active shreds list DO NOT include shreds waiting on Events
3294 // such shreds are on the shreduler's blocked list
3295 //-----------------------------------------------------------------------------
3296 void Chuck_VM_Shreduler::get_all_shreds( std::vector<Chuck_VM_Shred *> & shreds,
3297 t_CKBOOL clearVector ) const
3298 {
3299 // clear; if not clear, then will append to existing contents
3300 if( clearVector ) shreds.clear();
3301
3302 // get ready list (FALSE == don't clear vector)
3303 get_ready_shreds( shreds, FALSE );
3304
3305 // get blocked list (FALSE == don't clear vector)
3306 get_blocked_shreds( shreds, FALSE );
3307
3308 // add currently executing shred, if not NULL
3309 // (if not NULL, implies this is called from within VM.compute())
3310 Chuck_VM_Shred * shred = get_current_shred();
3311 if( shred ) shreds.push_back( shred );
3312 }
3313
3314
3315
3316
3317 //-----------------------------------------------------------------------------
3318 // name: get_all_shred_ids() | 1.5.0.8 (ge) added
3319 // desc: retrieve list of active shred IDs
3320 //-----------------------------------------------------------------------------
3321 void Chuck_VM_Shreduler::get_all_shred_ids( std::vector<t_CKUINT> & shredIDs,
3322 t_CKBOOL clearVector ) const
3323 {
3324 // clear; if not clear, then will append to existing contents
3325 if( clearVector ) shredIDs.clear();
3326
3327 // list for shreds
3328 std::vector<Chuck_VM_Shred *> shreds;
3329 // get shreds
3330 get_all_shreds( shreds );
3331
3332 // traverse shred list
3333 for( t_CKUINT i = 0; i < shreds.size(); i++ )
3334 {
3335 // append id
3336 shredIDs.push_back( shreds[i]->xid );
3337 }
3338 }
3339
3340
3341
3342
3343 //-----------------------------------------------------------------------------
3344 // name: status()
3345 // desc: get VM shreduler status
3346 //-----------------------------------------------------------------------------
3347 void Chuck_VM_Shreduler::status( Chuck_VM_Status * status )
3348 {
3349 Chuck_VM_Shred * shred = shred_list;
3350
3351 t_CKUINT srate = vm_ref->srate(); // 1.3.5.3; was: Digitalio::sampling_rate();
3352 t_CKUINT s = (t_CKUINT)now_system;
3353 t_CKUINT h = s/(srate*3600);
3354 s = s - (h*(srate*3600));
3355 t_CKUINT m = s / (srate*60);
3356 s = s - (m*(srate*60));
3357 t_CKUINT sec = s / srate;
3358 s = s - (sec*(srate));
3359 // float millisecond = s / (float)(srate) * 1000.0f;
3360
3361 status->srate = srate;
3362 status->now_system = now_system;
3363 status->t_second = sec;
3364 status->t_minute = m;
3365 status->t_hour = h;
3366
3367 // a vessel for shred pointers
3368 vector<Chuck_VM_Shred *> list;
3369 // get all shreds
3370 get_all_shreds( list );
3371
3372 // sort the list
3373 SortByID_LT byid;
3374 std::sort( list.begin(), list.end(), byid );
3375
3376 // print status
3377 status->clear();
3378 for( t_CKUINT i = 0; i < list.size(); i++ )
3379 {
3380 shred = list[i];
3381 status->list.push_back( new Chuck_VM_Shred_Status(
3382 shred->xid, shred->name, shred->start, shred->event != NULL ) );
3383 }
3384 }
3385
3386
3387
3388
3389 //-----------------------------------------------------------------------------
3390 // name: status()
3391 // desc: output/print status
3392 //-----------------------------------------------------------------------------
3393 void Chuck_VM_Shreduler::status()
3394 {
3395 Chuck_VM_Shred_Status * shred = NULL;
3396
3397 this->status( &m_status );
3398 t_CKUINT h = m_status.t_hour;
3399 t_CKUINT m = m_status.t_minute;
3400 t_CKUINT sec = m_status.t_second;
3401 EM_print2magenta( "(VM status) # of shreds in VM: %ld", m_status.list.size() );
3402 EM_print2magenta( "local time: %s", timestamp_formatted().c_str() );
3403 EM_print2magenta( "chuck time: %.0f::samp (%ldh%ldm%lds)", m_status.now_system, h, m, sec );
3404
3405 // print status
3406 if( m_status.list.size() ) EM_print2vanilla( "--------" );
3407 for( t_CKUINT i = 0; i < m_status.list.size(); i++ )
3408 {
3409 shred = m_status.list[i];
3410 EM_print2vanilla(
3411 "[shred id]: %ld [source]: %s [spork time]: %.2fs ago%s",
3412 shred->xid, mini( shred->name.c_str() ),
3413 (m_status.now_system - shred->start) / m_status.srate,
3414 shred->has_event ? " (blocked)" : "" );
3415 }
3416 if( m_status.list.size() ) EM_print2vanilla( "--------" );
3417 }
3418
3419
3420
3421
3422 //-----------------------------------------------------------------------------
3423 // name: Chuck_VM_Status()
3424 // desc: constructor
3425 //-----------------------------------------------------------------------------
3426 Chuck_VM_Status::Chuck_VM_Status()
3427 {
3428 srate = 0;
3429 now_system = 0;
3430 t_second = t_minute = t_hour = 0;
3431 }
3432
3433
3434
3435
3436 //-----------------------------------------------------------------------------
3437 // name: ~Chuck_VM_Status()
3438 // desc: destructor
3439 //-----------------------------------------------------------------------------
3440 Chuck_VM_Status::~Chuck_VM_Status()
3441 {
3442 this->clear();
3443 }
3444
3445
3446
3447
3448 //-----------------------------------------------------------------------------
3449 // name: clear()
3450 // desc: clear VM status
3451 //-----------------------------------------------------------------------------
3452 void Chuck_VM_Status::clear()
3453 {
3454 for( t_CKUINT i = 0; i < list.size(); i++ )
3455 {
3456 CK_SAFE_DELETE( list[i] );
3457 }
3458
3459 list.clear();
3460 }
3461
3462
3463
3464
3465 //-----------------------------------------------------------------------------
3466 // name: Chuck_VM_MFunInvoker()
3467 // desc: constructor
3468 //-----------------------------------------------------------------------------
3469 Chuck_VM_MFunInvoker::Chuck_VM_MFunInvoker()
3470 {
3471 // zero
3472 invoker_shred = NULL;
3473 instr_pushThis = NULL;
3474 instr_pushReturnVar = NULL;
3475 }
3476
3477
3478
3479
3480 //-----------------------------------------------------------------------------
3481 // name: ~Chuck_VM_MFunInvoker()
3482 // desc: destructor
3483 //-----------------------------------------------------------------------------
3484 Chuck_VM_MFunInvoker::~Chuck_VM_MFunInvoker()
3485 {
3486 cleanup();
3487 }
3488
3489
3490
3491
3492 //-----------------------------------------------------------------------------
3493 // name: setup()
3494 // desc: setup the invoker for use
3495 //-----------------------------------------------------------------------------
3496 t_CKBOOL Chuck_VM_MFunInvoker::setup( Chuck_Func * func, t_CKUINT func_vt_offset, Chuck_VM * vm, Chuck_VM_Shred * caller )
3497 {
3498 // clean up first
3499 if( invoker_shred ) cleanup();
3500
3501 // a vector of VM instructions
3502 vector<Chuck_Instr *> instructions;
3503
3504 // get argument list
3505 a_Arg_List args = func->def()->arg_list;
3506 // argument size in bytes
3507 t_CKUINT args_size_bytes = 0;
3508 // type kind
3509 te_KindOf kind = kindof_VOID;
3510 // iterate over arguments
3511 while( args )
3512 {
3513 // get size
3514 args_size_bytes += args->type->size;
3515 // get kind
3516 kind = getkindof( vm->env(), args->type );
3517
3518 // check kind; allocate instruction (with placeholder values; to be filled when invoked)
3519 switch( kind )
3520 {
3521 case kindof_INT:
3522 // push value INT
3523 instr_args.push_back( new Chuck_Instr_Reg_Push_Imm(0) );
3524 break;
3525
3526 case kindof_FLOAT:
3527 // push value FLOAT
3528 instr_args.push_back( new Chuck_Instr_Reg_Push_Imm2(0) );
3529 break;
3530
3531 case kindof_VEC2: // vec2 / complex / polar
3532 // push value FLOAT FLOAT
3533 instr_args.push_back( new Chuck_Instr_Reg_Push_Imm2(0) );
3534 instr_args.push_back( new Chuck_Instr_Reg_Push_Imm2(0) );
3535 break;
3536
3537 case kindof_VEC3:
3538 // push value FLOA FLOAT FLOAT
3539 instr_args.push_back( new Chuck_Instr_Reg_Push_Imm2(0) );
3540 instr_args.push_back( new Chuck_Instr_Reg_Push_Imm2(0) );
3541 instr_args.push_back( new Chuck_Instr_Reg_Push_Imm2(0) );
3542 break;
3543
3544 case kindof_VEC4:
3545 // push value FLOA FLOAT FLOAT FLOAT
3546 instr_args.push_back( new Chuck_Instr_Reg_Push_Imm2(0) );
3547 instr_args.push_back( new Chuck_Instr_Reg_Push_Imm2(0) );
3548 instr_args.push_back( new Chuck_Instr_Reg_Push_Imm2(0) );
3549 instr_args.push_back( new Chuck_Instr_Reg_Push_Imm2(0) );
3550 break;
3551
3552 // shouldn't get here
3553 case kindof_VOID:
3554 default:
3555 // error
3556 EM_error3( "(internal error) unhandled argument kind in MFunInvoker.init()" );
3557 // clean up
3558 for( t_CKUINT i = 0; i < instr_args.size(); i++ ) CK_SAFE_DELETE( instr_args[i] );
3559 // clear the array
3560 instr_args.clear();
3561 // error out
3562 return FALSE;
3563 }
3564
3565 // next arg
3566 args = args->next;
3567 }
3568 // account for 'this', since this is a member function
3569 args_size_bytes += sz_VOIDPTR;
3570
3571 // push arguments
3572 for( t_CKUINT i = 0; i < instr_args.size(); i++ )
3573 {
3574 // copy references over
3575 instructions.push_back( instr_args[i] );
3576 }
3577 // push this (as func arg) -- will set later
3578 instr_pushThis = new Chuck_Instr_Reg_Push_Imm( 0 );
3579 instructions.push_back( instr_pushThis );
3580 // reg dup last (push this again) (for member func resolution)
3581 instructions.push_back( new Chuck_Instr_Reg_Dup_Last);
3582 // dot member func
3583 instructions.push_back( new Chuck_Instr_Dot_Member_Func(func_vt_offset) );
3584 // func to code
3585 instructions.push_back( new Chuck_Instr_Func_To_Code );
3586 // frame offset; use 0 since we have no local variables
3587 // was: push stack depth (in bytes)
3588 // was: instructions.push_back( new Chuck_Instr_Reg_Push_Imm(args_size_bytes) );
3589 instructions.push_back( new Chuck_Instr_Reg_Push_Imm(0) );
3590 // func call
3591 instructions.push_back( new Chuck_Instr_Func_Call());
3592
3593 // figure out what to assign based on return type kind
3594 kind = getkindof( vm->env(), func->type() );
3595
3596 // if not void
3597 if( kind != kindof_VOID )
3598 {
3599 // push immediate to copy RETURN
3600 instr_pushReturnVar = new Chuck_Instr_Reg_Push_Imm(0);
3601 instructions.push_back( instr_pushReturnVar ); // 1.3.1.0: changed to t_CKUINT
3602 }
3603
3604 // check kind; allocate instruction (with placeholder values; to be filled when invoked)
3605 switch( kind )
3606 {
3607 case kindof_INT: // assign int or object ref
3608 if( isobj(vm->env(), func->type()) ) {
3609 // return type is an Object reference
3610 instructions.push_back( new Chuck_Instr_Assign_Object );
3611 instructions.push_back( new Chuck_Instr_Release_Object3_Pop_Int );
3612 } else {
3613 // return type is a primitive int
3614 instructions.push_back( new Chuck_Instr_Assign_Primitive );
3615 instructions.push_back( new Chuck_Instr_Reg_Pop_Int );
3616 }
3617 break;
3618 case kindof_FLOAT: // assign float
3619 instructions.push_back( new Chuck_Instr_Assign_Primitive2 );
3620 instructions.push_back( new Chuck_Instr_Reg_Pop_Float );
3621 break;
3622 case kindof_VEC2: // assign vec2 / complex / polar
3623 instructions.push_back( new Chuck_Instr_Assign_Primitive4 );
3624 instructions.push_back( new Chuck_Instr_Reg_Pop_Vec2ComplexPolar );
3625 break;
3626 case kindof_VEC3: // assign vec3
3627 instructions.push_back( new Chuck_Instr_Assign_PrimitiveVec3 );
3628 instructions.push_back( new Chuck_Instr_Reg_Pop_Vec3 );
3629 break;
3630 case kindof_VEC4: // assign vec4
3631 instructions.push_back( new Chuck_Instr_Assign_PrimitiveVec4 );
3632 instructions.push_back( new Chuck_Instr_Reg_Pop_Vec4 );
3633 break;
3634
3635 // shouldn't get here
3636 case kindof_VOID:
3637 // do nothing for void return type
3638 break;
3639
3640 default:
3641 // error
3642 EM_error3( "(internal error) unhandled argument kind in MFunInvoker.init()" );
3643 // clean up instructions
3644 for( t_CKUINT i = 0; i < instructions.size(); i++ ) CK_SAFE_DELETE( instructions[i] );
3645 // clear instructions
3646 instructions.clear();
3647 // error out
3648 return FALSE;
3649 }
3650
3651 // end of code
3652 instructions.push_back( new Chuck_Instr_EOC);
3653
3654 // create VM code
3655 Chuck_VM_Code * code = new Chuck_VM_Code;
3656 // allocate instruction array
3657 code->instr = new Chuck_Instr*[instructions.size()];
3658 // number of instructions
3659 code->num_instr = instructions.size();
3660 // copy instructions
3661 for( t_CKUINT i = 0; i < instructions.size(); i++ ) code->instr[i] = instructions[i];
3662 // TODO: should this be > 0
3663 code->stack_depth = 0;
3664 // TODO: should this be this true?
3665 code->need_this = FALSE;
3666
3667 // create dedicated shred
3668 invoker_shred = new Chuck_VM_Shred;
3669 // add reference (although we will hard-delete this shred in cleanup()
3670 // this is needed in case references are added/released along the way,
3671 // e.g., as part of UGens created on this shred, which would add_ref
3672 // as part of origin shred, and would release ref in shred.detach_ugens() | 1.5.4.3 (ge) added
3673 invoker_shred->add_ref();
3674 // set the VM ref (needed by initialize)
3675 invoker_shred->vm_ref = vm;
3676 // initialize with code + allocate stacks
3677 invoker_shred->initialize( code );
3678 // set name
3679 invoker_shred->name = func->signature(FALSE,TRUE);
3680 // enter immediate mode (will throw runtime exception on any time/event ops)
3681 invoker_shred->setImmediateMode( TRUE );
3682
3683 // done
3684 return TRUE;
3685 }
3686
3687
3688
3689
3690 //-----------------------------------------------------------------------------
3691 // helper function
3692 //-----------------------------------------------------------------------------
3693 static Chuck_Instr_Reg_Push_Imm * ckvm_next_instr_as_int( vector<Chuck_Instr *> & v, t_CKUINT & index )
3694 {
3695 // check bounds
3696 if( index >= v.size() )
3697 {
3698 // error
3699 EM_error3( "(internal error) misaligned arguments (get int) in MFunInvoker.invoke()" );
3700 return NULL;
3701 }
3702
3703 return (Chuck_Instr_Reg_Push_Imm *)v[index++];
3704 }
3705 //-----------------------------------------------------------------------------
3706 // helper function
3707 //-----------------------------------------------------------------------------
3708 static Chuck_Instr_Reg_Push_Imm2 * ckvm_next_instr_as_float( vector<Chuck_Instr *> & v, t_CKUINT & index )
3709 {
3710 // check bounds
3711 if( index >= v.size() )
3712 {
3713 // error
3714 EM_error3( "(internal error) misaligned arguments (get float) in MFunInvoker.invoke()" );
3715 return NULL;
3716 }
3717
3718 return (Chuck_Instr_Reg_Push_Imm2 *)v[index++];
3719 }
3720
3721
3722
3723
3724 //-----------------------------------------------------------------------------
3725 // name: invoke()
3726 // desc: invoke the mfun
3727 //-----------------------------------------------------------------------------
3728 Chuck_DL_Return Chuck_VM_MFunInvoker::invoke( Chuck_Object * obj, const vector<Chuck_DL_Arg> & args, Chuck_VM_Shred * parent_shred )
3729 {
3730 // the return value
3731 Chuck_DL_Return RETURN;
3732 // instruction pointers
3733 Chuck_Instr_Reg_Push_Imm * instr_pushInt = NULL;
3734 Chuck_Instr_Reg_Push_Imm2 * instr_pushFloat = NULL;
3735 // index
3736 t_CKUINT index = 0;
3737 // no shred?
3738 if( !invoker_shred ) return RETURN;
3739 // verify
3740 assert( instr_pushThis != NULL );
3741
3742 // set the actual argument values into the instructions
3743 for( t_CKUINT i = 0; i < args.size(); i++ )
3744 {
3745 // the current arg
3746 Chuck_DL_Arg arg = args[i];
3747 // check the argument kind
3748 switch( arg.kind )
3749 {
3750 case kindof_INT:
3751 instr_pushInt = ckvm_next_instr_as_int(instr_args, index); if( !instr_pushInt ) goto error;
3752 instr_pushInt->set( arg.value.v_int );
3753 break;
3754 case kindof_FLOAT:
3755 instr_pushFloat = ckvm_next_instr_as_float(instr_args, index); if( !instr_pushFloat ) goto error;
3756 instr_pushFloat->set( arg.value.v_float );
3757 break;
3758 case kindof_VEC2:
3759 instr_pushFloat = ckvm_next_instr_as_float(instr_args, index); if( !instr_pushFloat ) goto error;
3760 instr_pushFloat->set( arg.value.v_vec2.x );
3761 instr_pushFloat = ckvm_next_instr_as_float(instr_args, index); if( !instr_pushFloat ) goto error;
3762 instr_pushFloat->set( arg.value.v_vec2.y );
3763 break;
3764 case kindof_VEC3:
3765 instr_pushFloat = ckvm_next_instr_as_float(instr_args, index); if( !instr_pushFloat ) goto error;
3766 instr_pushFloat->set( arg.value.v_vec3.x );
3767 instr_pushFloat = ckvm_next_instr_as_float(instr_args, index); if( !instr_pushFloat ) goto error;
3768 instr_pushFloat->set( arg.value.v_vec3.y );
3769 instr_pushFloat = ckvm_next_instr_as_float(instr_args, index); if( !instr_pushFloat ) goto error;
3770 instr_pushFloat->set( arg.value.v_vec3.z );
3771 break;
3772 case kindof_VEC4:
3773 instr_pushFloat = ckvm_next_instr_as_float(instr_args, index); if( !instr_pushFloat ) goto error;
3774 instr_pushFloat->set( arg.value.v_vec4.x );
3775 instr_pushFloat = ckvm_next_instr_as_float(instr_args, index); if( !instr_pushFloat ) goto error;
3776 instr_pushFloat->set( arg.value.v_vec4.y );
3777 instr_pushFloat = ckvm_next_instr_as_float(instr_args, index); if( !instr_pushFloat ) goto error;
3778 instr_pushFloat->set( arg.value.v_vec4.z );
3779 instr_pushFloat = ckvm_next_instr_as_float(instr_args, index); if( !instr_pushFloat ) goto error;
3780 instr_pushFloat->set( arg.value.v_vec4.w );
3781 break;
3782 case kindof_VOID:
3783 default:
3784 // error
3785 EM_error3( "(internal error) unhandle argument kind in MFunInvoker.invoke()" );
3786 goto error;
3787 }
3788 }
3789
3790 // arguments not matched, more expected
3791 if( index < instr_args.size() )
3792 {
3793 // error
3794 EM_error3( "(internal error) misaligned arguments (left over) in MFunInvoker.invoke()" );
3795 goto error;
3796 }
3797
3798 // set this pointer
3799 instr_pushThis->set( (t_CKUINT)obj );
3800 // set the return var, if the function was set up to return a value
3801 if( instr_pushReturnVar ) instr_pushReturnVar->set( (t_CKUINT)&RETURN );
3802
3803 // reset shred: program counter
3804 invoker_shred->pc = 0;
3805 // next pc
3806 invoker_shred->next_pc = 1;
3807
3808 // set parent
3809 invoker_shred->parent = parent_shred;
3810 // commented out: parent if any should have been set in setup()
3811 // invoker_shred->parent = obj->originShred();
3812
3813 // set parent base_ref; in case mfun is part of a non-public class
3814 // that can access file-global variables outside the class definition
3815 if( invoker_shred->parent ) invoker_shred->base_ref = invoker_shred->parent->base_ref;
3816 else invoker_shred->base_ref = invoker_shred->mem;
3817
3818 // shred in dump (all done)
3819 invoker_shred->is_dumped = FALSE;
3820 // shred done
3821 invoker_shred->is_done = FALSE;
3822 // shred running
3823 invoker_shred->is_running = FALSE;
3824 // shred abort
3825 invoker_shred->is_abort = FALSE;
3826 // set the instr
3827 invoker_shred->instr = invoker_shred->code->instr;
3828 // zero out the id (shred is in immediate mode and cannot be shreduled)
3829 invoker_shred->xid = 0;
3830 // inherit now from vm
3831 invoker_shred->now = invoker_shred->vm_ref->now();
3832 // run shred on VM
3833 invoker_shred->run( invoker_shred->vm_ref );
3834
3835 // done; by the point, return should have been filled with return value, if func has one
3836 return RETURN;
3837
3838 error:
3839 // do the same thing for now
3840 return RETURN;
3841 }
3842
3843
3844
3845
3846 //-----------------------------------------------------------------------------
3847 // name: cleanup()
3848 // desc: clean up
3849 //-----------------------------------------------------------------------------
3850 void Chuck_VM_MFunInvoker::cleanup()
3851 {
3852 // release shred reference
3853 // 1.5.4.3 (ge) updated to hard-DELETE; in case of reference loops between shred and UGen created on it
3854 // NB this should also cleanup the code and VM instruction we created in setup
3855 CK_SAFE_DELETE( invoker_shred );
3856
3857 // clear the arg instructions
3858 instr_args.clear();
3859
3860 // zero out
3861 instr_pushThis = NULL;
3862 instr_pushReturnVar = NULL;
3863 }
3864
3865
3866
3867
3868 //-----------------------------------------------------------------------------
3869 // name: Chuck_VM_DtorInvoker()
3870 // desc: constructor
3871 //-----------------------------------------------------------------------------
3872 Chuck_VM_DtorInvoker::Chuck_VM_DtorInvoker()
3873 {
3874 // zero
3875 invoker_shred = NULL;
3876 instr_pushThis = NULL;
3877 }
3878
3879
3880
3881
3882 //-----------------------------------------------------------------------------
3883 // name: ~Chuck_VM_DtorInvoker()
3884 // desc: destructor
3885 //-----------------------------------------------------------------------------
3886 Chuck_VM_DtorInvoker::~Chuck_VM_DtorInvoker()
3887 {
3888 cleanup();
3889 }
3890
3891
3892
3893
3894 //-----------------------------------------------------------------------------
3895 // name: setup()
3896 // desc: setup the invoker for use
3897 //-----------------------------------------------------------------------------
3898 t_CKBOOL Chuck_VM_DtorInvoker::setup( Chuck_Func * dtor, Chuck_VM * vm )
3899 {
3900 // clean up first
3901 if( invoker_shred ) cleanup();
3902
3903 // a vector of VM instructions
3904 vector<Chuck_Instr *> instructions;
3905
3906 // push this (as func arg) -- will set later
3907 instr_pushThis = new Chuck_Instr_Reg_Push_Imm( 0 );
3908 instructions.push_back( instr_pushThis );
3909 // push destructor VM code
3910 instructions.push_back( new Chuck_Instr_Reg_Push_Code(dtor->code) );
3911 // push stack offset; 0 since this is a dedicated shred for invoking
3912 instructions.push_back( new Chuck_Instr_Reg_Push_Imm(0) );
3913 // func call
3914 instructions.push_back( new Chuck_Instr_Func_Call());
3915 // end of code
3916 instructions.push_back( new Chuck_Instr_EOC);
3917
3918 // create VM code
3919 Chuck_VM_Code * code = new Chuck_VM_Code;
3920 // allocate instruction array
3921 code->instr = new Chuck_Instr*[instructions.size()];
3922 // number of instructions
3923 code->num_instr = instructions.size();
3924 // copy instructions
3925 for( t_CKUINT i = 0; i < instructions.size(); i++ ) code->instr[i] = instructions[i];
3926 // TODO: should this be > 0
3927 code->stack_depth = 0;
3928 // TODO: should this be this true?
3929 code->need_this = FALSE;
3930
3931 // create dedicated shred
3932 invoker_shred = new Chuck_VM_Shred;
3933 // add reference (although we will hard-delete this shred in cleanup()
3934 // this is needed in case references are added/released along the way,
3935 // e.g., as part of UGens created on this shred, which would add_ref
3936 // as part of origin shred, and would release ref in shred.detach_ugens() | 1.5.4.3 (ge) added
3937 invoker_shred->add_ref();
3938 // set the VM ref (needed by initialize)
3939 invoker_shred->vm_ref = vm;
3940 // initialize with code + allocate stacks
3941 invoker_shred->initialize( code );
3942 // set name
3943 invoker_shred->name = dtor->signature(FALSE,TRUE);
3944 // enter immediate mode (will throw runtime exception on any time/event ops)
3945 invoker_shred->setImmediateMode( TRUE );
3946
3947 // done
3948 return TRUE;
3949 }
3950
3951
3952
3953
3954 //-----------------------------------------------------------------------------
3955 // name: invoke()
3956 // desc: invoke the dtor
3957 //-----------------------------------------------------------------------------
3958 void Chuck_VM_DtorInvoker::invoke( Chuck_Object * obj, Chuck_VM_Shred * parent_shred )
3959 {
3960 // no shred?
3961 if( !invoker_shred ) return;
3962 // verify
3963 assert( instr_pushThis != NULL );
3964
3965 // set this pointer
3966 instr_pushThis->set( (t_CKUINT)obj );
3967 // reset shred: program counter
3968 invoker_shred->pc = 0;
3969 // next pc
3970 invoker_shred->next_pc = 1;
3971 // set parent
3972 invoker_shred->parent = parent_shred;
3973
3974 // set parent base_ref; in case mfun is part of a non-public class
3975 // that can access file-global variables outside the class definition
3976 if( invoker_shred->parent )
3977 { invoker_shred->base_ref = invoker_shred->parent->base_ref; }
3978 else
3979 { invoker_shred->base_ref = invoker_shred->mem; }
3980
3981 // shred in dump (all done)
3982 invoker_shred->is_dumped = FALSE;
3983 // shred done
3984 invoker_shred->is_done = FALSE;
3985 // shred running
3986 invoker_shred->is_running = FALSE;
3987 // shred abort
3988 invoker_shred->is_abort = FALSE;
3989 // set the instr
3990 invoker_shred->instr = invoker_shred->code->instr;
3991 // zero out the id (shred is in immediate mode and cannot be shreduled)
3992 invoker_shred->xid = 0;
3993 // inherit now from vm
3994 invoker_shred->now = invoker_shred->vm_ref->now();
3995 // run shred on VM
3996 invoker_shred->run( invoker_shred->vm_ref );
3997 }
3998
3999
4000
4001
4002 //-----------------------------------------------------------------------------
4003 // name: cleanup()
4004 // desc: clean up
4005 //-----------------------------------------------------------------------------
4006 void Chuck_VM_DtorInvoker::cleanup()
4007 {
4008 // release shred reference
4009 // NB this should also cleanup the code and VM instruction we created in setup
4010 CK_SAFE_RELEASE( invoker_shred );
4011
4012 // zero out
4013 instr_pushThis = NULL;
4014 }
4015
4016
4017
4018
4019 //-----------------------------------------------------------------------------
4020 // name: Chuck_VM_SInitInvoker()
4021 // desc: constructor
4022 //-----------------------------------------------------------------------------
4023 Chuck_VM_SInitInvoker::Chuck_VM_SInitInvoker()
4024 {
4025 // zero
4026 invoker_shred = NULL;
4027 the_code = NULL;
4028 the_class = NULL;
4029 }
4030
4031
4032
4033
4034 //-----------------------------------------------------------------------------
4035 // name: ~Chuck_VM_SInitInvoker()
4036 // desc: destructor
4037 //-----------------------------------------------------------------------------
4038 Chuck_VM_SInitInvoker::~Chuck_VM_SInitInvoker()
4039 {
4040 cleanup();
4041 }
4042
4043
4044
4045
4046 //-----------------------------------------------------------------------------
4047 // name: setup()
4048 // desc: setup the invoker for use; static_itor should end with EOC
4049 //-----------------------------------------------------------------------------
4050 t_CKBOOL Chuck_VM_SInitInvoker::setup( Chuck_Type * type,
4051 Chuck_VM_Code * static_code,
4052 Chuck_VM * vm )
4053 {
4054 // clean up first
4055 if( invoker_shred ) cleanup();
4056
4057 // remember
4058 CK_SAFE_REF_ASSIGN( the_code, static_code );
4059 CK_SAFE_REF_ASSIGN( the_class, type );
4060
4061 // create dedicated shred
4062 invoker_shred = new Chuck_VM_Shred;
4063 // add reference (although we will hard-delete this shred in cleanup()
4064 // this is needed in case references are added/released along the way,
4065 // e.g., as part of UGens created on this shred, which would add_ref
4066 // as part of origin shred, and would release ref in shred.detach_ugens()
4067 invoker_shred->add_ref();
4068 // set the VM ref (needed by initialize)
4069 invoker_shred->vm_ref = vm;
4070 // initialize with code + allocate stacks
4071 invoker_shred->initialize( static_code );
4072 // set name
4073 invoker_shred->name = static_code->name;
4074 // enter immediate mode (will throw runtime exception on any time/event ops)
4075 invoker_shred->setImmediateMode( TRUE );
4076
4077 // done
4078 return TRUE;
4079 }
4080
4081
4082
4083
4084 //-----------------------------------------------------------------------------
4085 // name: invoke()
4086 // desc: invoke the dtor
4087 //-----------------------------------------------------------------------------
4088 void Chuck_VM_SInitInvoker::invoke( Chuck_VM_Shred * parent_shred )
4089 {
4090 // no shred?
4091 if( !invoker_shred ) return;
4092 // verify
4093 assert( the_class != NULL );
4094
4095 // log
4096 EM_log( CK_LOG_DEBUG, "initializing static data for '%s'", the_class->name().c_str() );
4097
4098 // reset shred: program counter
4099 invoker_shred->pc = 0;
4100 // next pc
4101 invoker_shred->next_pc = 1;
4102 // set parent
4103 invoker_shred->parent = parent_shred;
4104
4105 // set parent base_ref; in case mfun is part of a non-public class
4106 // that can access file-global variables outside the class definition
4107 if( invoker_shred->parent )
4108 { invoker_shred->base_ref = invoker_shred->parent->base_ref; }
4109 else
4110 { invoker_shred->base_ref = invoker_shred->mem; }
4111
4112 // shred in dump (all done)
4113 invoker_shred->is_dumped = FALSE;
4114 // shred done
4115 invoker_shred->is_done = FALSE;
4116 // shred running
4117 invoker_shred->is_running = FALSE;
4118 // shred abort
4119 invoker_shred->is_abort = FALSE;
4120 // set the instr
4121 invoker_shred->instr = invoker_shred->code->instr;
4122 // zero out the id (shred is in immediate mode and cannot be shreduled)
4123 invoker_shred->xid = 0;
4124 // inherit now from vm
4125 invoker_shred->now = invoker_shred->vm_ref->now();
4126 // run shred on VM
4127 invoker_shred->run( invoker_shred->vm_ref );
4128 }
4129
4130
4131
4132
4133 //-----------------------------------------------------------------------------
4134 // name: cleanup()
4135 // desc: clean up
4136 //-----------------------------------------------------------------------------
4137 void Chuck_VM_SInitInvoker::cleanup()
4138 {
4139 // release type reference
4140 CK_SAFE_RELEASE( the_class );
4141 // release code reference
4142 CK_SAFE_RELEASE( the_code );
4143
4144 // DELETE invoker shred
4145 CK_SAFE_DELETE( invoker_shred );
4146 }
4147
4148
4149
4150
4151 // begin CK_VM_DEBUG implementation
4152 //-----------------------------------------------------------------------------
4153 #if CK_VM_DEBUG_ENABLE
4154 //-----------------------------------------------------------------------------
4155 // Chuck_VM_Debug implementation | 1.5.0.5 (ge) added
4156 //-----------------------------------------------------------------------------
4157 // static member
4158 Chuck_VM_Debug * Chuck_VM_Debug::our_instance = NULL;
4159 // internal macro | automatically use our log level
4160 #define DEBUG_LOG( ... ) do{ CK_LOG( m_log_level, __VA_ARGS__ ); } while(0)
4161
4162
4163
4164
4165 //-----------------------------------------------------------------------------
4166 // name: info_backtrace()
4167 // desc: get call stack as string
4168 //-----------------------------------------------------------------------------
4169 std::string Chuck_VM_Debug::info_backtrace()
4170 {
4171 // return ck_backtrace();
4172 return "[not available]";
4173 }
4174
4175
4176 //-----------------------------------------------------------------------------
4177 // name: backtrace()
4178 // desc: print call stack as string
4179 //-----------------------------------------------------------------------------
4180 void Chuck_VM_Debug::backtrace( const std::string & note )
4181 {
4182 CK_FPRINTF_STDERR( "---- stack trace (%s) ----\n", note.c_str() );
4183 CK_FPRINTF_STDERR( "%s", info_backtrace().c_str() );
4184 CK_FPRINTF_STDERR( "--------------------------\n" );
4185 }
4186
4187
4188 //-----------------------------------------------------------------------------
4189 // name: Chuck_VM_Debug()
4190 // desc: constructor
4191 //-----------------------------------------------------------------------------
4192 Chuck_VM_Debug::Chuck_VM_Debug()
4193 {
4194 // default log level
4195 m_log_level = CK_LOG_DEBUG;
4196
4197 // stats
4198 reset_stats();
4199 }
4200
4201
4202 //-----------------------------------------------------------------------------
4203 // name: ~Chuck_VM_Debug()
4204 // desc: destructor
4205 //-----------------------------------------------------------------------------
4206 Chuck_VM_Debug::~Chuck_VM_Debug()
4207 {
4208 // TODO clean up map
4209 }
4210
4211
4212 //-----------------------------------------------------------------------------
4213 // name: instance()
4214 // desc: return static instance
4215 //-----------------------------------------------------------------------------
4216 Chuck_VM_Debug * Chuck_VM_Debug::instance()
4217 {
4218 // if no instance
4219 if( !our_instance )
4220 {
4221 // allocate
4222 our_instance = new Chuck_VM_Debug();
4223 }
4224
4225 return our_instance;
4226 }
4227
4228
4229 //-----------------------------------------------------------------------------
4230 // call this right after instantiation (tracking)
4231 //-----------------------------------------------------------------------------
4232 void Chuck_VM_Debug::construct( Chuck_VM_Object * obj, const std::string & note )
4233 {
4234 // check
4235 if( !obj )
4236 {
4237 DEBUG_LOG( "CONSTRUCT(%s): *** NULL OBJECT ***" );
4238 return;
4239 }
4240
4241 // log it
4242 DEBUG_LOG( "%s(%s): %s", TC::color(TC::FG_MAGENTA,"CONSTRUCT",true).c_str(), note.c_str(), this->info(obj).c_str() );
4243 // count
4244 m_numConstructed++;
4245 // FYI not adding to map here, constructor won't have type info beyond Chuck_VM_Object
4246 }
4247
4248
4249 //-----------------------------------------------------------------------------
4250 // call this right before destruct (tracking)
4251 //-----------------------------------------------------------------------------
4252 void Chuck_VM_Debug::destruct( Chuck_VM_Object * obj, const std::string & note )
4253 {
4254 // check
4255 if( !obj )
4256 {
4257 DEBUG_LOG( "DESTRUCT(%s): *** NULL OBJECT ***" );
4258 return;
4259 }
4260
4261 // log it
4262 DEBUG_LOG( "%s(%s): %s", TC::color(TC::FG_YELLOW,"DESTRUCT",true).c_str(), note.c_str(), this->info(obj).c_str() );
4263 // count
4264 m_numDestructed++;
4265 // remove it from map
4266 remove( obj );
4267 }
4268
4269
4270 //-----------------------------------------------------------------------------
4271 // name: add_ref()
4272 // desc: add reference
4273 //-----------------------------------------------------------------------------
4274 void Chuck_VM_Debug::add_ref( Chuck_VM_Object * obj, const std::string & note )
4275 {
4276 // check
4277 if( !obj )
4278 {
4279 DEBUG_LOG( "ADD_REF(%s): *** NULL OBJECT ***" );
4280 return;
4281 }
4282
4283 // log it
4284 DEBUG_LOG( "%s(%s): %s", TC::green("ADD_REF",true).c_str(), note.c_str(), this->info(obj).c_str() );
4285 // count
4286 m_numAddRefs++;
4287 // add it to map (constructor won't have type info beyond Chuck_VM_Object)
4288 insert( obj );
4289 }
4290
4291
4292 //-----------------------------------------------------------------------------
4293 // name: release()
4294 // desc: release reference
4295 //-----------------------------------------------------------------------------
4296 void Chuck_VM_Debug::release( Chuck_VM_Object * obj, const std::string & note )
4297 {
4298 // check
4299 if( !obj )
4300 {
4301 DEBUG_LOG( "RELEASE(%s): *** NULL OBJECT ***" );
4302 return;
4303 }
4304
4305 DEBUG_LOG( "%s(%s): %s", TC::orange("RELEASE",true).c_str(), note.c_str(), this->info(obj).c_str() );
4306 // count
4307 m_numReleases++;
4308 }
4309
4310
4311 //-----------------------------------------------------------------------------
4312 // print stats
4313 //-----------------------------------------------------------------------------
4314 void Chuck_VM_Debug::print_stats()
4315 {
4316 DEBUG_LOG( TC::blue("VM DEBUG: total constructed: %ld",true).c_str(), m_numConstructed );
4317 DEBUG_LOG( TC::blue("VM DEBUG: total destructed: %ld",true).c_str(), m_numDestructed );
4318 DEBUG_LOG( TC::blue("VM DEBUG: total add refs: %ld",true).c_str(), m_numAddRefs );
4319 DEBUG_LOG( TC::blue("VM DEBUG: total release refs: %ld",true).c_str(), m_numReleases );
4320 }
4321
4322
4323 //-----------------------------------------------------------------------------
4324 // reset stats
4325 //-----------------------------------------------------------------------------
4326 void Chuck_VM_Debug::reset_stats()
4327 {
4328 // stats
4329 m_numConstructed = 0;
4330 m_numDestructed = 0;
4331 m_numAddRefs = 0;
4332 m_numReleases = 0;
4333 }
4334
4335
4336 //-----------------------------------------------------------------------------
4337 // set log level to print to
4338 //-----------------------------------------------------------------------------
4339 void Chuck_VM_Debug::set_log_evel( t_CKUINT level )
4340 {
4341 m_log_level = level;
4342 }
4343
4344
4345 //-----------------------------------------------------------------------------
4346 // one func to try to print them all
4347 //-----------------------------------------------------------------------------
4348 void Chuck_VM_Debug::print( Chuck_VM_Object * obj, const std::string & note )
4349 {
4350 DEBUG_LOG( "%s%s", (note != "" ? note +" " : " ").c_str(), info(obj).c_str() );
4351 }
4352
4353
4354 //-----------------------------------------------------------------------------
4355 // one func to get info using runtime types
4356 //-----------------------------------------------------------------------------
4357 std::string Chuck_VM_Debug::info( Chuck_VM_Object * obj )
4358 {
4359 // check
4360 if( !obj ) return "[NULL info]";
4361
4362 // get the type
4363 string type = mini_type(typeid(*obj).name());
4364 // info str [POINTER:REFCOUNT](TYPE)
4365 string ret = string("[") + ptoa(obj) + ":" + TC::blue(ck_itoa(obj->refcount()),true) + "](" + TC::green(type,true) + "): ";
4366
4367 // match on type name
4368 if( type == "Chuck_Object" ) ret += info_obj( (Chuck_Object *)obj );
4369 else if( type == "Chuck_Type" ) ret += info_type( (Chuck_Type *)obj );
4370 else if( type == "Chuck_Func") ret += info_func( (Chuck_Func *)obj );
4371 else if( type == "Chuck_Value") ret += info_value( (Chuck_Value *)obj );
4372 else if( type == "Chuck_Namespace") ret += info_namespace( (Chuck_Namespace *)obj );
4373 else if( type == "Chuck_Context") ret += info_context( (Chuck_Context *)obj );
4374 else if( type == "Chuck_Env") ret += info_env( (Chuck_Env *)obj );
4375 else if( type == "Chuck_UGen_Info") ret += info_ugen_info( (Chuck_UGen_Info *)obj );
4376 else if( type == "Chuck_VM_Code") ret += info_code( (Chuck_VM_Code *)obj );
4377 else if( type == "Chuck_VM_Shred") ret += info_shred( (Chuck_VM_Shred *)obj );
4378 else if( type == "Chuck_VM") ret += info_vm( (Chuck_VM *)obj );
4379
4380 // no match
4381 return ret;
4382 }
4383
4384
4385 //-----------------------------------------------------------------------------
4386 // info by type
4387 //-----------------------------------------------------------------------------
4388 std::string Chuck_VM_Debug::info_obj( Chuck_Object * obj )
4389 {
4390 if( !obj ) return "[NULL obj]";
4391 return string("Object of type:") + info_type(obj->type_ref);
4392 }
4393
4394 std::string Chuck_VM_Debug::info_type( Chuck_Type * type )
4395 {
4396 if( !type ) return "[NULL type]";
4397
4398 // construct value string
4399 string s = string("'") + type->name() + "'";
4400
4401 // namescpace
4402 // if( type->owner ) s += info_namespace( type->owner ) + " ";
4403 // function?
4404 if( type->func ) s += info_func( type->func );
4405
4406 // backtrace();
4407 return s;
4408 }
4409
4410 std::string Chuck_VM_Debug::info_func( Chuck_Func * func )
4411 {
4412 if( !func ) return "[NULL func]";
4413 return func->base_name + "() " + "symbol: '" + func->name + "'";
4414 }
4415
4416 std::string Chuck_VM_Debug::info_value( Chuck_Value * v )
4417 {
4418 // check
4419 if( !v ) return "[NULL value]";
4420 // construct value string
4421 string s;
4422
4423 // type
4424 s += info_type(v->type) + " ";
4425 // name space
4426 if( v->owner ) s += info_namespace(v->owner) + ".";
4427 // value name
4428 s += v->name + "; ";
4429 // part of a class?
4430 // if( v->owner_class ) s += info_type(v->owner_class);
4431
4432 return s;
4433 }
4434
4435 std::string Chuck_VM_Debug::info_namespace( Chuck_Namespace * nspc )
4436 {
4437 if( !nspc ) return "[NULL namespace]";
4438 return nspc->name;
4439 }
4440
4441 std::string Chuck_VM_Debug::info_context( Chuck_Context * context )
4442 {
4443 if( !context ) return "[NULL context]";
4444
4445 // return string
4446 string s = string("'") + context->filename + "' ";
4447 // public class def set?
4448 // s += string("public-class-def: ") + (context->public_class_def ? "SET" : "EMPTY");
4449
4450 return s;
4451
4452 }
4453
4454 std::string Chuck_VM_Debug::info_env( Chuck_Env * env )
4455 {
4456 if( !env ) return "[NULL env]";
4457 return "";
4458 }
4459
4460 std::string Chuck_VM_Debug::info_ugen_info( Chuck_UGen_Info * ug )
4461 {
4462 if( !ug ) return "[NULL ugen_info]";
4463 return "";
4464 }
4465
4466 std::string Chuck_VM_Debug::info_code( Chuck_VM_Code * code )
4467 {
4468 if( !code ) return "[NULL code]";
4469 return code->name;
4470
4471 }
4472
4473 std::string Chuck_VM_Debug::info_shred( Chuck_VM_Shred * shred )
4474 {
4475 if( !shred ) return "[NULL shred]";
4476 return shred->name;
4477 }
4478
4479 std::string Chuck_VM_Debug::info_vm( Chuck_VM * vm )
4480 {
4481 if( !vm ) return "[NULL vm]";
4482 return "";
4483 }
4484
4485 // insert into object map
4486 void Chuck_VM_Debug::insert( Chuck_VM_Object * obj )
4487 {
4488 // map key
4489 string key = mini_type(typeid(*obj).name());
4490
4491 // insert
4492 m_objects_map[key][obj] = obj;
4493 }
4494
4495 // remove from object map
4496 void Chuck_VM_Debug::remove( Chuck_VM_Object * obj )
4497 {
4498 // map key
4499 string key = mini_type(typeid(*obj).name());
4500 // check
4501 if( !contains(obj) ) return;
4502 // remove
4503 m_objects_map[key].erase( obj );
4504 }
4505
4506 // is present?
4507 t_CKBOOL Chuck_VM_Debug::contains( Chuck_VM_Object * obj )
4508 {
4509 // map key
4510 string key = mini_type(typeid(*obj).name());
4511 // find it
4512 return m_objects_map.find( key ) != m_objects_map.end() &&
4513 m_objects_map[key].find(obj) != m_objects_map[key].end();
4514 }
4515
4516 //-----------------------------------------------------------------------------
4517 // number of objects being tracked
4518 //-----------------------------------------------------------------------------
4519 t_CKUINT Chuck_VM_Debug::num_objects()
4520 {
4521 // outer iter
4522 std::map< std::string, std::map<Chuck_VM_Object *, Chuck_VM_Object *> >::iterator maps = m_objects_map.begin();
4523 // count
4524 t_CKUINT count = 0;
4525
4526 // iterate
4527 for( ; maps != m_objects_map.end(); maps++ )
4528 {
4529 // count
4530 count += maps->second.size();
4531 }
4532
4533 return count;
4534 }
4535
4536 //-----------------------------------------------------------------------------
4537 // compare functin for Chuck_VM_Object *
4538 //-----------------------------------------------------------------------------
4539 bool vm_obj_cmp( Chuck_VM_Object * lhs, Chuck_VM_Object * rhs )
4540 {
4541 if( !lhs || !rhs ) return false;
4542 return lhs->refcount() > rhs->refcount();
4543 }
4544
4545 //-----------------------------------------------------------------------------
4546 // print all objects being tracked
4547 //-----------------------------------------------------------------------------
4548 void Chuck_VM_Debug::print_all_objects()
4549 {
4550 // outer iter
4551 std::map< std::string, std::map<Chuck_VM_Object *, Chuck_VM_Object *> >::iterator maps = m_objects_map.begin();
4552 // vector
4553 vector<Chuck_VM_Object *> vec;
4554
4555 // iterate
4556 for( ; maps != m_objects_map.end(); maps++ )
4557 {
4558 // print
4559 DEBUG_LOG( "%s (%d)", TC::blue(maps->first.c_str(),true).c_str(), maps->second.size() );
4560 // push
4561 EM_pushlog();
4562 // inner
4563 std::map<Chuck_VM_Object *, Chuck_VM_Object *>::iterator objs = maps->second.begin();
4564 // clear
4565 vec.clear();
4566 // iterate
4567 for( ; objs != maps->second.end(); objs++ )
4568 {
4569 // push vector
4570 vec.push_back( objs->second );
4571 }
4572 // sort
4573 sort( vec.begin(), vec.end(), vm_obj_cmp );
4574 // print
4575 for( t_CKINT i = 0; i < vec.size(); i++ )
4576 {
4577 print( vec[i] );
4578 }
4579 // pop
4580 EM_poplog();
4581 }
4582 }
4583
4584 #endif // #if CK_VM_DEBUG_ENABLE