1 // Created on: 1995-02-23
2 // Created by: Remi LEQUETTE
3 // Copyright (c) 1995-1999 Matra Datavision
4 // Copyright (c) 1999-2012 OPEN CASCADE SAS
6 // The content of this file is subject to the Open CASCADE Technology Public
7 // License Version 6.5 (the "License"). You may not use the content of this file
8 // except in compliance with the License. Please obtain a copy of the License
9 // at http://www.opencascade.org and read it completely before using this file.
11 // The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
12 // main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
14 // The Original Code and all software distributed under the License is
15 // distributed on an "AS IS" basis, without warranty of any kind, and the
16 // Initial Developer hereby disclaims all such warranties, including without
17 // limitation, any warranties of merchantability, fitness for a particular
18 // purpose or non-infringement. Please see the License for the specific terms
19 // and conditions governing the rights and limitations under the License.
21 #include <Standard_Macro.hxx>
22 #include <Standard_Stream.hxx>
23 #include <Standard_SStream.hxx>
24 #include <Standard_Version.hxx>
27 #include <Draw_Appli.hxx>
28 #include <Draw_Chronometer.hxx>
29 #include <Draw_Printer.hxx>
31 #include <Message.hxx>
32 #include <Message_Messenger.hxx>
34 #include <OSD_MemInfo.hxx>
35 #include <OSD_MAllocHook.hxx>
36 #include <OSD_Chronometer.hxx>
38 #include <OSD_Exception_CTRL_BREAK.hxx>
50 #define RLIM_INFINITY 0x7fffffff
52 static clock_t CPU_CURRENT; // cpu time already used at last
53 // cpulimit call. (sec.)
57 #include <sys/resource.h>
67 #if defined(HAVE_TIME_H)
75 #ifdef HAVE_SYS_SIGNAL_H
76 # include <sys/signal.h>
79 #if defined (__hpux) || defined ( HPUX )
80 #define RLIM_INFINITY 0x7fffffff
86 extern Standard_Boolean Draw_Batch;
88 static clock_t CPU_LIMIT; // Cpu_limit in Sec.
90 //=======================================================================
92 //=======================================================================
94 extern Standard_Boolean Draw_Chrono;
96 static Standard_Integer chronom(Draw_Interpretor& di,
97 Standard_Integer n,const char** a)
99 if ((n == 1) || (*a[1] == '0') || (*a[1] == '1')) {
101 Draw_Chrono = !Draw_Chrono;
103 Draw_Chrono = (*a[1] == '1');
105 if (Draw_Chrono) di << "Chronometers activated."<<"\n";
106 else di << "Chronometers desactivated."<<"\n";
109 Handle(Draw_Drawable3D) D = Draw::Get(a[1]);
110 Handle(Draw_Chronometer) C;
112 C = Handle(Draw_Chronometer)::DownCast(D);
115 C = new Draw_Chronometer();
116 Draw::Set(a[1],C,Standard_False);
122 if (!strcasecmp(a[2],"reset"))
124 if (!strcasecmp(a[2],"start"))
126 if (!strcasecmp(a[2],"stop"))
128 if (!strcasecmp(a[2],"show"))
135 static Standard_Integer dchronom(Draw_Interpretor& I,
136 Standard_Integer n,const char** a)
138 if ((n == 1) || (*a[1] == '0') || (*a[1] == '1')) {
140 Draw_Chrono = !Draw_Chrono;
142 Draw_Chrono = (*a[1] == '1');
144 if (Draw_Chrono) I << "Chronometers activated."<<"\n";
145 else I << "Chronometers desactivated."<<"\n";
148 Handle(Draw_Drawable3D) D = Draw::Get(a[1]);
149 Handle(Draw_Chronometer) C;
151 C = Handle(Draw_Chronometer)::DownCast(D);
154 C = new Draw_Chronometer();
155 Draw::Set(a[1],C,Standard_False);
161 if (!strcasecmp(a[2],"reset"))
163 if (!strcasecmp(a[2],"start"))
165 if (!strcasecmp(a[2],"stop"))
167 if (!strcasecmp(a[2],"show")) {
179 //=======================================================================
182 //=======================================================================
184 static Standard_Integer ifbatch(Draw_Interpretor& DI, Standard_Integer , const char** )
194 //=======================================================================
197 //=======================================================================
199 extern Standard_Boolean Draw_Spying;
200 extern filebuf Draw_Spyfile;
202 static Standard_Integer spy(Draw_Interpretor& di, Standard_Integer n, const char** a)
205 Draw_Spyfile.close();
206 Draw_Spying = Standard_False;
208 if (!Draw_Spyfile.open(a[1],ios::out)) {
209 di << "Cannot open "<<a[1]<<" for writing"<<"\n";
212 Draw_Spying = Standard_True;
217 static Standard_Integer dlog(Draw_Interpretor& di, Standard_Integer n, const char** a)
219 if (n != 2 && n != 3)
221 cout << "Enable or disable logging: " << a[0] << " {on|off}" << endl;
222 cout << "Reset log: " << a[0] << " reset" << endl;
223 cout << "Get log content: " << a[0] << " get" << endl;
227 if (! strcmp (a[1], "on") && n == 2)
229 di.SetDoLog (Standard_True);
230 // di.Log() << "dlog on" << endl; // for symmetry
232 else if (! strcmp (a[1], "off") && n == 2)
234 di.SetDoLog (Standard_False);
236 else if (! strcmp (a[1], "reset") && n == 2)
240 else if (! strcmp (a[1], "get") && n == 2)
242 di << di.Log().str().c_str();
244 else if (! strcmp (a[1], "add") && n == 3)
246 di.Log() << a[2] << "\n";
249 cout << "Unrecognized option(s): " << a[1] << endl;
255 static Standard_Integer decho(Draw_Interpretor& di, Standard_Integer n, const char** a)
259 cout << "Enable or disable echoing: " << a[0] << " {on|off}" << endl;
263 if (! strcmp (a[1], "on"))
265 di.SetDoEcho (Standard_True);
267 else if (! strcmp (a[1], "off"))
269 di.SetDoEcho (Standard_False);
272 cout << "Unrecognized option: " << a[1] << endl;
278 static Standard_Integer dbreak(Draw_Interpretor& di, Standard_Integer, const char**)
283 catch (OSD_Exception_CTRL_BREAK) {
284 di << "User pressed Control-Break";
285 return 1; // Tcl exception
291 static Standard_Integer dversion(Draw_Interpretor& di, Standard_Integer, const char**)
293 // print OCCT version and OCCTY-specific macros used
294 di << "Open CASCADE Technology " << OCC_VERSION_STRING_EXT << "\n";
295 #if defined(DEB) || defined(_DEBUG)
296 di << "Debug mode\n";
299 di << "TBB enabled (HAVE_TBB)\n";
301 di << "TBB disabled\n";
304 di << "GL2PS enabled (HAVE_GL2PS)\n";
306 di << "GL2PS disabled\n";
308 #ifdef HAVE_FREEIMAGE
309 di << "FreeImage enabled (HAVE_FREEIMAGE)\n";
311 di << "FreeImage disabled\n";
314 di << "OpenCL enabled (HAVE_OPENCL)\n";
316 di << "OpenCL disabled\n";
319 di << "Exceptions disabled (No_Exception)\n";
321 di << "Exceptions enabled\n";
324 // check compiler, OS, etc. using pre-processor macros provided by compiler
325 // see "Pre-defined C/C++ Compiler Macros" http://sourceforge.net/p/predef/wiki/
326 // note that only modern compilers that are known to be used for OCCT are recognized
328 // compiler; note that GCC and MSVC are last as other compilers (e.g. Intel) can also define __GNUC__ and _MSC_VER
329 #if defined(__INTEL_COMPILER)
330 di << "Compiler: Intel " << __INTEL_COMPILER << "\n";
331 #elif defined(__BORLANDC__)
332 di << "Compiler: Borland C++ (__BORLANDC__ = " << __BORLANDC__ << ")\n";
333 #elif defined(__clang__)
334 di << "Compiler: Clang " << __clang_major__ << "." << __clang_minor__ << "." << __clang_patchlevel__ << "\n";
335 #elif defined(__SUNPRO_C)
336 di << "Compiler: Sun Studio (__SUNPRO_C = " << __SUNPROC_C << ")\n";
337 #elif defined(_MSC_VER)
338 di << "Compiler: MS Visual C++ " << (int)(_MSC_VER/100-6) << "." << (int)((_MSC_VER/10)-60-10*(int)(_MSC_VER/100-6)) << " (_MSC_FULL_VER = " << _MSC_FULL_VER << ")\n";
339 #elif defined(__GNUC__)
340 di << "Compiler: GCC " << __GNUC__ << "." << __GNUC_MINOR__ << "." << __GNUC_PATCHLEVEL__ << "\n";
342 di << "Compiler: unrecognized\n";
345 // Cygwin and MinGW specifics
346 #if defined(__CYGWIN__)
349 #if defined(__MINGW64__)
350 di << "MinGW 64 " << __MINGW64_MAJOR_VERSION << "." << __MINGW64_MINOR_VERSION << "\n";
351 #elif defined(__MINGW32__)
352 di << "MinGW 32 " << __MINGW32_MAJOR_VERSION << "." << __MINGW32_MINOR_VERSION << "\n";
356 #if defined(__amd64) || defined(__x86_64) || defined(_M_AMD64)
357 di << "Architecture: AMD64\n";
358 #elif defined(__i386) || defined(_M_IX86) || defined(__X86__)|| defined(_X86_)
359 di << "Architecture: Intel x86\n";
360 #elif defined(_M_IA64) || defined(__ia64__)
361 di << "Architecture: Intel Itanium (IA 64)\n";
362 #elif defined(__sparc__) || defined(__sparc)
363 di << "Architecture: SPARC\n";
365 di << "Architecture: unrecognized\n";
369 #if defined(_WIN32) || defined(__WINDOWS__) || defined(__WIN32__)
370 di << "OS: Windows\n";
371 #elif defined(__APPLE__) || defined(__MACH__)
372 di << "OS: Mac OS X\n";
374 di << "OS: SUN Solaris\n";
375 #elif defined(__ANDROID__) /* must be before Linux */
376 #include <android/api-level.h>
377 di << "OS: Android (__ANDROID_API__ = " << __ANDROID_API__ << ")\n";
378 #elif defined(__linux__)
380 #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
381 #include <sys/param.h>
382 di << "OS: BSD (BSD = " << BSD << ")\n";
384 di << "OS: unrecognized\n";
390 //=======================================================================
393 //=======================================================================
395 static Standard_Integer Draw_wait(Draw_Interpretor& , Standard_Integer n, const char** a)
397 Standard_Integer w = 10;
399 w = Draw::Atoi(a[1]);
400 time_t ct = time(NULL) + w;
401 while (time(NULL) < ct) {};
405 //=======================================================================
406 //function : cpulimit
408 //=======================================================================
410 static unsigned int __stdcall CpuFunc (void * /*param*/)
416 Standard_Real anUserSeconds, aSystemSeconds;
417 OSD_Chronometer::GetProcessCPU (anUserSeconds, aSystemSeconds);
418 aCurrent = clock_t(anUserSeconds + aSystemSeconds);
420 if ((aCurrent - CPU_CURRENT) >= CPU_LIMIT)
422 cout << "Process killed by CPU limit (" << CPU_LIMIT << " sec)" << endl;
429 static void CpuFunc (int)
431 cout << "Process killed by CPU limit (" << CPU_LIMIT << " sec)" << endl;
437 static Standard_Integer cpulimit(Draw_Interpretor&, Standard_Integer n, const char** a)
440 static Standard_Integer cpulimit(Draw_Interpretor& di, Standard_Integer n, const char** a)
444 // Windows specific code
446 static int aFirst = 1;
448 unsigned int __stdcall CpuFunc (void *);
452 CPU_LIMIT = RLIM_INFINITY;
455 CPU_LIMIT = Draw::Atoi (a[1]);
456 Standard_Real anUserSeconds, aSystemSeconds;
457 OSD_Chronometer::GetProcessCPU (anUserSeconds, aSystemSeconds);
458 CPU_CURRENT = clock_t(anUserSeconds + aSystemSeconds);
460 if (aFirst) // Launch the thread only at the 1st call.
463 _beginthreadex (NULL, 0, CpuFunc, NULL, 0, &aThreadID);
472 rlp.rlim_max = RLIM_INFINITY;
474 rlp.rlim_cur = RLIM_INFINITY;
476 rlp.rlim_cur = Draw::Atoi(a[1]);
477 CPU_LIMIT = rlp.rlim_cur;
480 status=setrlimit(RLIMIT_CPU,&rlp);
482 di << "status cpulimit setrlimit : " << status << "\n";
484 // set signal handler to print a message before death
485 struct sigaction act, oact;
486 memset (&act, 0, sizeof(act));
487 act.sa_handler = CpuFunc;
488 sigaction (SIGXCPU, &act, &oact);
495 //=======================================================================
496 //function : mallochook
498 //=======================================================================
500 static Standard_Integer mallochook(Draw_Interpretor& di, Standard_Integer n,
506 usage: mallochook cmd\n\
507 where cmd is one of:\n\
508 set [<op>] - set callback to malloc/free; op is one of the following:\n\
509 0 - set callback to NULL,\n\
510 1 - set callback OSD_MAllocHook::CollectBySize (default)\n\
511 2 - set callback OSD_MAllocHook::LogFileHandler\n\
512 reset - reset the CollectBySize handler\n\
513 report1 [<outfile>]\n\
514 - write report from CollectBySize handler in <outfile>\n\
516 - open file for writing the log with LogFileHandler\n\
517 close - close the log file with LogFileHandler\n\
518 report2 [<flag>] [<logfile>] [<outfile>]\n\
519 - scan <logfile> written with LogFileHandler\n\
520 and make synthesized report in <outfile>; <flag> can be:\n\
521 0 - simple stats by sizes (default),\n\
522 1 - with alive allocation numbers\n\
523 By default <logfile> is \"mem-log.txt\", <outfile> is \"mem-stat.txt\""
527 if (strcmp(a[1], "set") == 0)
529 int aType = (n > 2 ? Draw::Atoi(a[2]) : 1);
530 if (aType < 0 || aType > 2)
532 di << "unknown op of the command set" << "\n";
537 OSD_MAllocHook::SetCallback(NULL);
538 di << "callback is unset" << "\n";
542 OSD_MAllocHook::SetCallback(OSD_MAllocHook::GetCollectBySize());
543 di << "callback is set to CollectBySize" << "\n";
545 else //if (aType == 2)
547 OSD_MAllocHook::SetCallback(OSD_MAllocHook::GetLogFileHandler());
548 di << "callback is set to LogFileHandler" << "\n";
551 else if (strcmp(a[1], "reset") == 0)
553 OSD_MAllocHook::GetCollectBySize()->Reset();
554 di << "CollectBySize handler is reset" << "\n";
556 else if (strcmp(a[1], "open") == 0)
558 const char* aFileName = (n > 2 ? a[2] : "mem-log.txt");
559 if (!OSD_MAllocHook::GetLogFileHandler()->Open(aFileName))
561 di << "cannot create file " << aFileName << " for writing" << "\n";
564 di << "log file " << aFileName << " is opened for writing" << "\n";
566 else if (strcmp(a[1], "close") == 0)
568 OSD_MAllocHook::GetLogFileHandler()->Close();
569 di << "log file is closed" << "\n";
571 else if (strcmp(a[1], "report1") == 0)
573 const char* aOutFile = "mem-stat.txt";
576 if (OSD_MAllocHook::GetCollectBySize()->MakeReport(aOutFile))
578 di << "report " << aOutFile << " has been created" << "\n";
582 di << "cannot create report " << aOutFile << "\n";
586 else if (strcmp(a[1], "report2") == 0)
588 Standard_Boolean includeAlive = Standard_False;
589 const char* aLogFile = "mem-log.txt";
590 const char* aOutFile = "mem-stat.txt";
593 includeAlive = (Draw::Atoi(a[2]) != 0);
601 if (OSD_MAllocHook::LogFileHandler::MakeReport(aLogFile, aOutFile, includeAlive))
603 di << "report " << aOutFile << " has been created" << "\n";
607 di << "cannot create report " << aOutFile << " from the log file "
614 di << "unrecognized command " << a[1] << "\n";
620 //==============================================================================
623 //==============================================================================
625 static int dlocale (Draw_Interpretor& di, Standard_Integer n, const char** argv)
627 int category = LC_ALL;
630 const char *cat = argv[1];
631 if ( ! strcmp (cat, "LC_ALL") ) category = LC_ALL;
632 else if ( ! strcmp (cat, "LC_COLLATE") ) category = LC_COLLATE;
633 else if ( ! strcmp (cat, "LC_CTYPE") ) category = LC_CTYPE;
634 else if ( ! strcmp (cat, "LC_MONETARY") ) category = LC_MONETARY;
635 else if ( ! strcmp (cat, "LC_NUMERIC") ) category = LC_NUMERIC;
636 else if ( ! strcmp (cat, "LC_TIME") ) category = LC_TIME;
639 cout << "Error: cannot recognize argument " << cat << " as one of LC_ macros" << endl;
643 const char* locale = (n > 2 ? argv[2] : NULL);
644 const char* result = setlocale (category, locale);
648 cout << "Error: unsupported locale specification: " << locale << endl;
652 //==============================================================================
653 //function : dmeminfo
655 //==============================================================================
657 static int dmeminfo (Draw_Interpretor& theDI,
658 Standard_Integer theArgNb,
659 const char** theArgVec)
661 OSD_MemInfo aMemInfo;
664 theDI << aMemInfo.ToString();
668 for (Standard_Integer anIter = 1; anIter < theArgNb; ++anIter)
670 TCollection_AsciiString anArg (theArgVec[anIter]);
672 if (anArg == "virt" || anArg == "v")
674 theDI << Standard_Real (aMemInfo.Value (OSD_MemInfo::MemVirtual)) << " ";
676 else if (anArg == "heap" || anArg == "h")
678 theDI << Standard_Real (aMemInfo.Value (OSD_MemInfo::MemHeapUsage)) << " ";
680 else if (anArg == "wset" || anArg == "w")
682 theDI << Standard_Real (aMemInfo.Value (OSD_MemInfo::MemWorkingSet)) << " ";
684 else if (anArg == "wsetpeak")
686 theDI << Standard_Real (aMemInfo.Value (OSD_MemInfo::MemWorkingSetPeak)) << " ";
688 else if (anArg == "swap")
690 theDI << Standard_Real (aMemInfo.Value (OSD_MemInfo::MemSwapUsage)) << " ";
692 else if (anArg == "swappeak")
694 theDI << Standard_Real (aMemInfo.Value (OSD_MemInfo::MemSwapUsagePeak)) << " ";
696 else if (anArg == "private")
698 theDI << Standard_Real (aMemInfo.Value (OSD_MemInfo::MemPrivate)) << " ";
702 std::cerr << "Unknown argument '" << theArgVec[anIter] << "'!\n";
709 void Draw::BasicCommands(Draw_Interpretor& theCommands)
711 static Standard_Boolean Done = Standard_False;
713 Done = Standard_True;
715 ios::sync_with_stdio();
717 const char* g = "DRAW General Commands";
719 theCommands.Add("batch", "returns 1 in batch mode",
721 theCommands.Add("spy","spy [file], Save commands in file. no file close",
723 theCommands.Add("wait","wait [time(10)], wait time seconds",
724 __FILE__,Draw_wait,g);
725 theCommands.Add("cpulimit","cpulimit [nbseconds], no args remove limits",
726 __FILE__,cpulimit,g);
727 theCommands.Add("chrono","chrono [ name start/stop/reset/show]",
729 theCommands.Add("dchrono","dchrono [ name start/stop/reset/show]",
730 __FILE__,dchronom,g);
731 theCommands.Add("mallochook",
732 "debug memory allocation/deallocation, w/o args for help",
733 __FILE__, mallochook, g);
734 theCommands.Add ("meminfo",
735 "meminfo [virt|v] [heap|h] [wset|w] [wsetpeak] [swap] [swappeak] [private]"
736 " : memory counters for this process",
737 __FILE__, dmeminfo, g);
739 // Logging commands; note that their names are hard-coded in the code
740 // of Draw_Interpretor, thus should not be changed without update of that code!
741 theCommands.Add("dlog", "manage logging of commands and output; run without args to get help",
743 theCommands.Add("decho", "switch on / off echo of commands to cout; run without args to get help",
746 theCommands.Add("dbreak", "raises Tcl exception if user has pressed Control-Break key",
748 theCommands.Add("dversion", "provides information on OCCT build configuration (version, compiler, OS, C library, etc.)",
749 __FILE__,dversion,g);
750 theCommands.Add("dlocale", "set and / or query locate of C subsystem (function setlocale())",