PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label debugging. Show all posts
Showing posts with label debugging. Show all posts

Monday, November 14, 2022

[FIXED] How can I get useful error messages in PHP?

 November 14, 2022     debugging, error-handling, php     No comments   

Issue

Quite often I will try and run a PHP script and just get a blank screen back. No error message; just an empty screen. The cause might have been a simple syntax error (wrong bracket, missing semicolon), or a failed function call, or something else entirely.

It is very difficult to figure out what went wrong. I end up commenting out code, entering "echo" statements everywhere, etc. trying to narrow down the problem. But there surely must be a better way, right?

Is there a way to get PHP to produce a useful error message, like Java does?


Solution

For syntax errors, you need to enable error display in the php.ini. By default these are turned off because you don't want a "customer" seeing the error messages. Check this page in the PHP documentation for information on the 2 directives: error_reporting and display_errors. display_errors is probably the one you want to change. If you can't modify the php.ini, you can also add the following lines to an .htaccess file:

php_flag  display_errors        on
php_value error_reporting       2039

You may want to consider using the value of E_ALL (as mentioned by Gumbo) for your version of PHP for error_reporting to get all of the errors. more info

3 other items: (1) You can check the error log file as it will have all of the errors (unless logging has been disabled). (2) Adding the following 2 lines will help you debug errors that are not syntax errors:

error_reporting(-1);
ini_set('display_errors', 'On');

(3) Another option is to use an editor that checks for errors when you type, such as PhpEd. PhpEd also comes with a debugger which can provide more detailed information. (The PhpEd debugger is very similar to xdebug and integrates directly into the editor so you use 1 program to do everything.)

Cartman's link is also very good: http://www.ibm.com/developerworks/library/os-debug/



Answered By - Darryl Hein
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I debug "Error: spawn ENOENT" on node.js?

 November 14, 2022     child-process, debugging, error-handling, node.js, spawn     No comments   

Issue

When I get the following error:

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: spawn ENOENT
    at errnoException (child_process.js:1000:11)
    at Process.ChildProcess._handle.onexit (child_process.js:791:34)

What procedure can I follow to fix it?

Author note: Lots of issues with this error encouraged me to post this question for future references.

Related questions:

  • using spawn function with NODE_ENV=production
  • node.js child_process.spawn ENOENT error - only under supervisord
  • spawn ENOENT node.js error
  • https://stackoverflow.com/questions/27603713/nodejs-spawn-enoent-error-on-travis-calling-global-npm-package
  • Node JS - child_process spawn('npm install') in Grunt task results in ENOENT error
  • Running "foreman" task Fatal error: spawn ENOENT
  • unhandled error event in node js Error: spawn ENOENT at errnoException (child_process.js:975:11)
  • Node.js SpookyJS: error executing hello.js
  • https://stackoverflow.com/questions/26572214/run-grunt-on-a-directory-nodewebkit
  • Run exe file with Child Process NodeJS
  • Node: child_process.spawn not working on Java even though it's in the path (ENOENT)
  • spawn ENOENT error with NodeJS (PYTHON related)
  • image resizing is not working in node.js (partial.js) (non-installed dependency)
  • npm install error ENOENT (build dependency problem)
  • Cannot install node.js - oracle module on Windows 7 (build dependency problem)
  • Error installing gulp using nodejs on windows (strange case)

Solution

How to research the spawn call raising the error:

  • Use NODE_DEBUG=child_process, Credits to @karl-richter. Simple, quick, October 2019
  • Use a wrapper to decorate child_process.spawn, Credits to @jiaji-zhou. Simple, quick, January 2015
  • Long procedure, credits to @laconbass. Complex, time-cost, December 2014

Known, usual causes

  1. Environment issues

    • The command executable does not exist within the system (dependency not being installed). see prominc's answer
    • The command executable does not exist within a directory of those specified by PATH environment variable.
    • The executable binary was compiled with uncompatible libraries. see danilo-ramirez answer
  2. Windows-only bugs/quirks

    • '.cmd' extension / shell: true. see li-zheng answer
    • Administrator permisions. see steve's answer
  3. Wrong spawn('command', ['--argument', 'list'], { cwd, env, ...opts }) usage

    • Specified working directory (opts.cwd) does not exist · see leeroy-brun's answer
    • Argument list within command String spawn('command --wrong --argument list')
    • Env vars within command string spawn('ENV_VAR=WRONG command')
    • Argument list Array specified as String spawn('cmd', '--argument list')
    • Unset PATH env variable spawn('cmd', [], { env: { variable } } => spawn('cmd', [], { env: { ...process.env, variable } }

There are 2 posible origins for ENOENT:

  1. Code you are writing
  2. Code you depend on

When origin is code you depend on, usual cause is an Environment Issue (or windows quirk)




Answered By - laconbass
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I diagnose an Access violation (0xC0000005) at EIP=0x00000000?

 November 14, 2022     access-violation, debugging, error-handling, excel, labview     No comments   

Issue

While running a .exe in LabView 2021, I need to access an Excel file on the computer. The .exe opens the file in Excel to read from it. But, as soon as it tries to, the .exe crashes and throws the above error. It gives a possible cause, and it blames this vi.

This code has worked in the past and I have not edited it since.

What could be causing this exception, specifically one at EIP=0x00000000? How can I diagnose the problem? How could I tell if it is a problem in the program code or a permissions conflict on the hosting computer?


Solution

First, try using the .NET API instead of the ActiveX. It should be more stable. Second, you have to wire all the inputs of the invoke node with a Type: Missing node.enter image description here



Answered By - Lior Bilia
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, November 5, 2022

[FIXED] Why can I not edit a method that contains an anonymous method in the debugger?

 November 05, 2022     anonymous-methods, c#, debugging, lambda, visual-studio-2010     No comments   

Issue

So, every time I have written a lambda expression or anonymous method inside a method that I did not get quite right, I am forced to recompile and restart the entire application or unit test framework in order to fix it. This is seriously annoying, and I end up wasting more time than I saved by using these constructs in the first place. It is so bad that I try to stay away from them if I can, even though Linq and lambdas are among my favourite C# features.

I suppose there is a good technical reason for why it is this way, and perhaps someone knows? Furthermore, does anyone know if it will be fixed in VS2010?

Thanks.


Solution

Yes there is a very good reason for why you cannot do this. The simple reason is cost. The cost of enabling this feature in C# (or VB) is extremely high.

Editing a lambda function is a specific case of a class of ENC issues that are very difficult to solve with the current ENC (Edit'n'Continue) architecture. Namely, it's very difficult to ENC any method which where the ENC does one of the following:-

  1. Generates Metadata in the form of a class
  2. Edits or generates a generic method

The first issue is more of a logic constraint but it also bumps into a couple of limitations in the ENC architecture. Namely the problem is generating the first class isn't terribly difficult. What's bothersome is generating the class after the second edit. The ENC engine must start tracking the symbol table for not only the live code, but the generated classes as well. Normally this is not so bad, but this becomes increasingly difficult when the shape of a generated class is based on the context in which it is used (as is the case with lambdas because of closures). More importantly, how do you resolve the differences against instances of the classes that are already alive in the process?

The second issue is a strict limitation in the CLR ENC architecture. There is nothing that C# (or VB) can do to work around this.

Lambdas unfortunately hit both of these issues dead on. The short version is that ENC'ing a lambda involves lots of mutations on existing classes (which may or may not have been generated from other ENC's). The big problem comes in resolving the differences between the new code and the existing closure instances alive in the current process space. Also, lambdas tend to use generics a lot more than other code and hit issue #2.

The details are pretty hairy and a bit too involved for a normal SO answer. I have considered writing a lengthy blog post on the subject. If I get around to it I'll link it back into this particular answer.



Answered By - JaredPar
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, October 28, 2022

[FIXED] How to fully dump / print variable to console in the Dart language?

 October 28, 2022     console, dart, debugging, is-empty, javascript     No comments   

Issue

Hey there I am searching for a function which is printing a dynamic variable as completely as possible to the console in Dart language.

In PHP for instance I would use var_dump() in order to get all information about a variable.

In JavaScript I would do one of the following:

1) Convert Object to JSON and print console.log(JSON.stringify(obj))

2) Or a custom function like this:

 function dump(arr,level) {
  var dumped_text = "";
  if(!level) level = 0;

  //The padding given at the beginning of the line.
  var level_padding = "";
  for(var j=0;j<level+1;j++) level_padding += "    ";

  if(typeof(arr) == 'object') { //Array/Hashes/Objects 
   for(var item in arr) {
    var value = arr[item];

    if(typeof(value) == 'object') { //If it is an array,
     dumped_text += level_padding + "'" + item + "' ...\n";
     dumped_text += dump(value,level+1);
    } else {
     dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
    }
   }
  } else { //Stings/Chars/Numbers etc.
   dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
  }
  return dumped_text;
 }

However in Dart if I do print(variable) I get something like Instance of 'FooBarObject'. I cannot just convert an object to JSON like in JavaScript as this is not possible for all objects.

So my question in detail:

Is where a function or custom function in dart which can print a variable with unknown type (object, array, etc.) including all (public) properties as well as nested objects and variables to my console? Or which function is closest to this desire?


Solution

There is no built in function that generates such an output.

print(variable) prints variable.toString() and Instance of 'FooBarObject' is the default implementation. You can override it in custom classes and print something different.

You can use reflection (https://www.dartlang.org/articles/libraries/reflection-with-mirrors) to build a function yourself that investigates all kinds of properties of an instance and prints it the way you want. There is almost no limitation of what you can do and for debugging purposes it's definitely a fine option.

For production web application it should be avoided because it limits tree-shaking seriously and will cause the build output size to increase notable. Flutter (mobile) doesn't support reflection at all.

You can also use one of the JSON serialization packages, that make it easy to add serialization to custom classes and then print the serialized value. For example

  • https://pub.dartlang.org/packages/dson

I think there are others, but I don't know about (dis)advantages, because I usually roll my own using https://pub.dartlang.org/packages/source_gen



Answered By - Günter Zöchbauer
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, October 18, 2022

[FIXED] How to run a Flask app in debug mode with using pipenv and docker?

 October 18, 2022     debugging, docker, flask, pipenv     No comments   

Issue

I set my app.py to debug mode:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html', title='Title Here')

# ...
# more routes here
# ...

if __name__ == '__main__':
    app.run(debug=True) 

The Python library called geopandas is messing my local machine up, that's why I decided to dockerise my app, and it works perfectly! (Except the flask debug mode)

My Dockerfile looks like this. I tried the debugpy library with no success:

FROM python:3.9-slim as base

# Setup env
ENV LANG C.UTF-8
ENV LC_ALL C.UTF-8
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONFAULTHANDLER 1


FROM base AS python-deps

# Install pipenv and compilation dependencies
RUN pip install pipenv
RUN apt-get update && apt-get install -y --no-install-recommends gcc

# Install python dependencies in /.venv
COPY Pipfile .
COPY Pipfile.lock .
RUN PIPENV_VENV_IN_PROJECT=1 pipenv install geopandas
RUN PIPENV_VENV_IN_PROJECT=1 pipenv install debugpy
RUN PIPENV_VENV_IN_PROJECT=1 pipenv install --deploy
CMD pipenv debugpy

FROM base AS runtime

# Copy virtual env from python-deps stage
COPY --from=python-deps /.venv /.venv
ENV PATH="/.venv/bin:$PATH"

WORKDIR /home


# Install application into container
COPY . .

Then I build the image with this:

docker build -t <IMAGE-NAME:HERE> .

Then I initialise the docker container with this script:

docker run --rm -ti --mount type=bind,source=/"$(pwd)",target=/home -p 5000:5000 <IMAGE-NAME:HERE> flask run --port 5000 --host 0.0.0.0 --debugger

And everything is working but the debug mode:

 * Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:5000
 * Running on http://172.17.0.2:5000

Any ideas?


Solution

First, to answer your question:

flask --debug run --port 5000 --host 0.0.0.0

Debug mode enables --debugger and also --reload.

I have had great success using Docker as the runtime for my Flask application during development. It makes development quite a bit easier, especially when paired with Docker compose once your app grows a bit and you need other services like a database or a redis instance.

I'm a little confused as to why your CMD is before your runtime stage, and why you're using pipenv debugpy instead of pipenv run debugpy. (That said, I have no experience with debugpy, so maybe this is actually correct.) Anyway, I'd encourage you to investigate ENTRYPOINT to see if it might simplify invocation.

As an aside, you should consider creating a docker-compose.yml file and starting your service with docker compose up. The docker CLI incantation above is already starting to become unwieldy. This is untested, but should get you started:

version: "3.9"

services:
  web:
    image: <IMAGE_NAME>
   
    # Fix slow shutdown of web container
    # See: https://stackoverflow.com/a/62854251/1749551
    init: true
    
    environment:
      FLASK_ENV: development # Implies --debug
      PORT: 5000
    ports:
      - 5000:5000
    restart: always
    entrypoint: "flask run --host=0.0.0.0"

    # To enable pdb within Docker:
    # https://hackernoon.com/debugging-using-pdb-in-dockerized-environment-i21n2863
    stdin_open: true
    tty: true

    # Bind the project directory into the container so changes are reflected by Flask
    volumes:
      - .:/home

And lastly, be conscious of what COPY . . will pick up and add to your image.



Answered By - Nick K9
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, September 28, 2022

[FIXED] How to use _whyIsThisViewNotFocusable in tvOS?

 September 28, 2022     debugging, focus, tvos, uikit     No comments   

Issue

To debug the focus issues _whyIsThisViewNotFocusable method is available in the tvOS, But in debug in shouldUpdateFocusInContext with this command like this po [mainView _whyIsThisViewNotFocusable] or po mainView _whyIsThisViewNotFocusable it gives me error :

error: <EXPR>:1:9: error: consecutive statements on a line must be separated by ';'
mainView _whyIsThisViewNotFocusable

So what is the correct use of _whyIsThisViewNotFocusable ?

I seen this question in some stack-overflow answers but because of less reputation i can't comment in that post/answer


Solution

Presumably you're using swift so you shouldn't use obj-c in the debugger. Instead use:

po mainView.performSelector(Selector("_whyIsThisViewNotFocusable")) 


Answered By - Wain
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, September 26, 2022

[FIXED] Why does Fiddler response has weird unicode characters after decoding?

 September 26, 2022     debugging, fiddler, fiddler-everywhere, http, networking     No comments   

Issue

So I was debugging game with Fiddler, and found that the HTTP request is partially decoded and partially not decoded. The non-decoded part consists of incomprehensible unicodes:

POST https://example.com/something HTTP/1.1
Host: example.com
User-Agent: UnityPlayer/2020.3.32f1 (UnityWebRequest/1.0, libcurl/7.80.0-DEV)
Accept: */*
Accept-Encoding: deflate, gzip
Content-Type: application/octet-stream
x_acts: Duel.matching
atoken: 23128e425359819ac4253c93e72cbc944095812015c1ff83843f9f62ff1e
X-Unity-Version: 2020.3.32f1
Content-Length: 311

`   |  [  Õ£F #   =-  a  = } E& W J &! Ä     _  iU x_      I   cc  "`Hp!   B    x @ h~{"info":[{"n":"2","m":168,"params":{"rule":{"mode":2,"type":5}}}],"vae":"344142"}

I had the same problem in both Fiddler Classic and Fiddler Everywhere. I gave CA, and selected Decrypt option. It would be understandable if whole request is either completely decoded or completely encoded, but it is both. Is there something I'm missing? Thanks!


Solution

The content type of the request is set to application/octet-stream which means the request body data is binary data of any format (proprietary or standardized like PNG, ZIP, ...).

Binary data can contain plain text parts like in your example some JSON data. If you don't know the data format used for sending you can not decode the data, which means the data that Fiddler display to you are the real data that has been send. Therefore you should look at the data in hex mode and check if you can identify the format. A common binary encoding format is Google Protobuf, a decoding format that is not supported by Fiddler. If you have access to the game client which sends this data you could reverse engineer the executable and see what libraries it loads. May be one of the libraries is belongs to an encoding format. But of course the data format can be totally proprietary, then you would have to reverse engineer the executable in a tool like Ghidra, IDAPro, ... to understand what data is sent and how it is encoded.



Answered By - Robert
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, September 21, 2022

[FIXED] Why does this config always shows my default web server?

 September 21, 2022     apache, debugging, virtualhost, web, webserver     No comments   

Issue

I have the attached config, I am trying to display mysite.com (defined as vhost at the very end) but it always shows the default index page, the one I have in /var/www/html/domains/default/index.php

I know one cause can be wrong permission code on my vhost folder, but I don't think that is the case now, I don't see that common forbidden error in logs and for debugging purposes I set the full path of sub-directories to belong to apache:apache

I also tried to move my vhost at the top of the .conf but it made no difference.

ServerRoot "/etc/httpd"


Listen *:80
Listen *:443

Include conf.modules.d/*.conf


User apache
Group apache


ServerAdmin root@localhost


ServerName vm3.mysite.com:80

<Directory />
    AllowOverride all
    Require all granted
</Directory>



DocumentRoot "/var/www/html/domains/default"

<Directory "/var/www">
    AllowOverride All
    Require all granted
</Directory>

<Directory "/var/www/html">
    Options Indexes FollowSymLinks


    AllowOverride All

    Require all granted
</Directory>

<IfModule dir_module>
    DirectoryIndex index.html
</IfModule>

<Files ".ht*">
    Require all denied
</Files>

ErrorLog "logs/error_log"

LogLevel warn

<IfModule log_config_module>
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common

    <IfModule logio_module>
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>

    CustomLog "logs/access_log" combined
</IfModule>

<IfModule alias_module>

    ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"

</IfModule>

<Directory "/var/www/cgi-bin">
    AllowOverride None
    Options None
    Require all granted
</Directory>

<IfModule mime_module>
    TypesConfig /etc/mime.types

    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz

    AddType text/html .shtml
    AddOutputFilter INCLUDES .shtml
</IfModule>

AddDefaultCharset UTF-8

<IfModule mime_magic_module>
    MIMEMagicFile conf/magic
</IfModule>


EnableSendfile on

IncludeOptional conf.d/*.conf


<VirtualHost mysite.com:80>
        DocumentRoot /var/www/html/domains/mysite.com
        ServerName mysite.com
        <Directory "/var/www/html/domains/mysite.com">
                allow from all
                Options None
                Require all granted
        </Directory>
</VirtualHost>


KeepAlive on

Solution

You have vm3.mysite.com configured outside of a VirtualHost block, which apache is using unconditionally and ignoring the mysite.com vhost. You could fix this by moving vm3.mysite.com into a separate vhost (where they occur in the config file doesn't really matter, so long as they're both in a vhost).

Here is your config, with some of the directives reorganized for clarity, and the relevant bits moved into a proper VirtualHost block at the bottom:

ServerRoot "/etc/httpd"

Listen *:80
Listen *:443

User apache
Group apache

KeepAlive on
EnableSendfile on
Include conf.modules.d/*.conf
IncludeOptional conf.d/*.conf

<Directory "/var/www">
    AllowOverride All
    Require all granted
</Directory>

<Directory "/var/www/html">
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

<IfModule dir_module>
    DirectoryIndex index.html
</IfModule>

<Files ".ht*">
    Require all denied
</Files>

ErrorLog "logs/error_log"

LogLevel warn

<IfModule log_config_module>
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common
    <IfModule logio_module>
        LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>
    CustomLog "logs/access_log" combined
</IfModule>

<IfModule alias_module>
    ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
</IfModule>

<Directory "/var/www/cgi-bin">
    AllowOverride None
    Options None
    Require all granted
</Directory>

<IfModule mime_module>
    TypesConfig /etc/mime.types
    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz
    AddType text/html .shtml
    AddOutputFilter INCLUDES .shtml
</IfModule>

AddDefaultCharset UTF-8

<IfModule mime_magic_module>
    MIMEMagicFile conf/magic
</IfModule>

<VirtualHost vm3.mysite.com:80>
    ServerAdmin root@localhost
    ServerName vm3.mysite.com
    DocumentRoot "/var/www/html/domains/default"
    <Directory />
        AllowOverride all
        Require all granted
    </Directory>
</VirtualHost>

<VirtualHost mysite.com:80>
    DocumentRoot /var/www/html/domains/mysite.com
    ServerName mysite.com
    <Directory "/var/www/html/domains/mysite.com">
        allow from all
        Options None
        Require all granted
    </Directory>
</VirtualHost>

To keep things better organized, you might consider moving those vhosts to a separate config file under conf.d/<your_file>.conf which will be included in the main config automatically. This would allow you to keep your vhost settings separate from the general server config and avoid most of the previous confusion.



Answered By - AfroThundr
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, September 20, 2022

[FIXED] How to debug an apache virtual host configuration?

 September 20, 2022     apache, debugging, virtualhost     No comments   

Issue

Once again, I have a problem with my apache virtual host configuration. (The default configuration is used instead of my specific one).

The problem is not really the misconfiguration but how to solve it.

Does anyone has good advices to do resolve this kind of problem quickly?

Some more informations.

The default conf file is this one:

NameVirtualHost *
<VirtualHost *>
        ServerAdmin webmaster@localhost

        DocumentRoot /var/www/
        <Directory />
                Options FollowSymLinks
                AllowOverride None
        </Directory>
        <Directory /var/www/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
        </Directory>

        ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
        <Directory "/usr/lib/cgi-bin">
                AllowOverride None
                Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                Order allow,deny
                Allow from all
        </Directory>

        ErrorLog /var/log/apache2/error.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        CustomLog /var/log/apache2/access.log combined
        ServerSignature On

    Alias /doc/ "/usr/share/doc/"
    <Directory "/usr/share/doc/">
        Options Indexes MultiViews FollowSymLinks
        AllowOverride None
        Order deny,allow
        Deny from all
        Allow from 127.0.0.0/255.0.0.0 ::1/128
    </Directory>

</VirtualHost>

And the virtual host config that doesn't apply is this one:

<VirtualHost *:*>

ProxyPreserveHost On
ProxyPass / http://ip.ip.ip.ip:8088/
ProxyPassReverse / http://ip.ip.ip.ip:8088/
ServerName wiki.mydomain.com

</VirtualHost>

Solution

Syntax check

To check configuration files for syntax errors:

# Red Hat-based (Fedora, CentOS), Arch-based and OSX
httpd -t

# Debian-based (Ubuntu)
apache2ctl -t

# MacOS
apachectl -t

List virtual hosts

To list all virtual hosts, and their locations:

# Red Hat-based (Fedora, CentOS), Arch-based and OSX
httpd -S

# Debian-based (Ubuntu)
apache2ctl -S

# MacOS
apachectl -S


Answered By - sqren
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, September 18, 2022

[FIXED] How can I write to the console in PHP?

 September 18, 2022     console, debugging, php, printing     No comments   

Issue

Is it possible write a string or log into the console?

What I mean

Just like in JSP, if we print something like system.out.println("some"), it will be there at the console, not at a page.


Solution

Firefox

On Firefox you can use an extension called FirePHP which enables the logging and dumping of information from your PHP applications to the console. This is an addon to the awesome web development extension Firebug.

  • http://www.studytrails.com/blog/using-firephp-in-firefox-to-debug-php/

Chrome

However if you are using Chrome there is a PHP debugging tool called Chrome Logger or webug (webug has problems with the order of logs).

More recently Clockwork is in active development which extends the Developer Tools by adding a new panel to provide useful debugging and profiling information. It provides out of the box support for Laravel 4 and Slim 2 and support can be added via its extensible API.

Using Xdebug

A better way to debug your PHP would be via Xdebug. Most browsers provide helper extensions to help you pass the required cookie/query string to initialize the debugging process.

  • Chrome - Xdebug Helper
  • Firefox - The easiest Xdebug
  • Opera - Xdebug
  • Safari - Xdebug Toggler


Answered By - Malachi
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, September 13, 2022

[FIXED] How to get a Kony application's name at runtime

 September 13, 2022     cross-platform, debugging, mobile, temenos-quantum     No comments   

Issue

I'm writing a logger module for a Kony app to print out debugging statements. The Kony SDK already has a kony.print function but I'd like this logger to print out the application's name as a prefix to each statement, to get something like:

FooApp: x is 1
FooApp: a is ["hello", "world"]

The point here is to make it easier for me to filter/find my debug statements in the Xcode or Android Studio logs while debugging.

So I'm aiming to write something like:

var Logger = (function(){

    var prefix = ""; //kony.getAppId()?

    return{
        print: function(message){
            kony.print(`${prefix}: ${message}`);
        }
    };
})();

So the question is whether there is anything like a kony.getAppId() function, a constant or equivalent I can query to get the appropriate value for prefix in order to make the module reusable, rather than hard-code it for every project.


Solution

I've found that there's an appConfig variable built into every Kony app that includes useful information about the application like its name and version. So now I can initialise the prefix variable in my module like this:

var prefix = appConfig.appId || appConfig.appName;

I hope this is useful to others.



Answered By - Mig82
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, September 12, 2022

[FIXED] How to know at runtime whether a Kony app was built in debug or release mode

 September 12, 2022     cross-platform, debugging, temenos-quantum     No comments   

Issue

I'd like to be able to determine programmatically whether the app was built in debug or release mode. I'd like to be able to write something like:

if(isDebug) {
    //do domething.
}
else {
    //do something else.
}

Solution

After using the Chrome debugger I was able to unearth the solution. There's a constant set during the build process which you can query in order to determine whether the app has been built in debug or release mode.

if(kony.constants.RUNMODE === "debug" || appConfig.isDebug) {
    //do domething.
}
else {
    //do something else.
}


Answered By - Mig82
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, August 26, 2022

[FIXED] How do I debug a WordPress plugin?

 August 26, 2022     debugging, wordpress     No comments   

Issue

I've recently inherited a WordPress plugin that has a few bugs in it. My problem is that I'm also new to WordPress and I don't know how to log debug messages so that I can figure out what's going on.

I really just need a way to create a popup or log to a console.


Solution

There's this excellent Q&A at WordPress Stack Exchange, lots of knowledgeable folks explaining their debugging techniques: How do you debug plugins?

In the Javascript arena you basically need <script>console.log('the value is' + variable);</script>. And use Google Chrome inspector and/or Firebug.

In PHP, it depends on where things are happening or where you want the output.


Debugging in WordPress

Official documentation in the Codex.

Example wp-config.php for Debugging

// Enable WP_DEBUG mode
define( 'WP_DEBUG', true );

// Enable Debug logging to the /wp-content/debug.log file
define( 'WP_DEBUG_LOG', true );

// Disable display of errors and warnings 
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', 0 );

// Use dev versions of core JS and CSS files (only needed if you are modifying these core files)
define( 'SCRIPT_DEBUG', true );

Printing information to a log file

The following uses an OSX/Unix/Linux system path, adjust for Windows.

/* Log to File
 * Description: Log into system php error log, usefull for Ajax and stuff that FirePHP doesn't catch
 */
function my_log_file( $msg, $name = '' )
{
    // Print the name of the calling function if $name is left empty
    $trace=debug_backtrace();
    $name = ( '' == $name ) ? $trace[1]['function'] : $name;

    $error_dir = '/Applications/MAMP/logs/php_error.log';
    $msg = print_r( $msg, true );
    $log = $name . "  |  " . $msg . "\n";
    error_log( $log, 3, $error_dir );
}

Then, in you code call the function my_log_file( $post, 'The post contents are:' );


Print directly in the rendered Html

/* Echo variable
 * Description: Uses <pre> and print_r to display a variable in formated fashion
 */
function echo_log( $what )
{
    echo '<pre>'.print_r( $what, true ).'</pre>';
}

And wherever needed use it like: echo_log( $post );.


FirePHP

This extension will log information directly in the browser console. Refer to the following Q&A at WordPress Answers: How to use WP-FirePHP extension?.


Query Monitor

This is a must have on a debug toolkit, the plugin has many features, one of them is its Logs tab, just drop this in your code and have it listed in the plugin interface in your page:

do_action( 'qm/debug', 'This happened!' );
do_action( 'qm/debug', $your_var );
do_action( 'qm/debug', [$var1, $var2] );



Answered By - brasofilo
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, August 21, 2022

[FIXED] What are the negative consequences of turning debug heap off? (_NO_DEBUG_HEAP==1)

 August 21, 2022     debugging, environment-variables, heap-memory, visual-studio-2012     No comments   

Issue

The initial phase of my program loads in significant amounts of data into STL containers. I found that it was taking several minutes before I could reach the real meat of my program.

After some searching, I found that I could set _NO_DEBUG_HEAP==1 within my VS2012 Configuration Properties->Debugging->Environment variable...turning off utilization of the windows debug heap. This gave me a 10x improvement in debugging speed. I have not yet found any description what what debugging functionality I lose by doing so.

In summary: what checks were completed and what debug info was being generated by using the windows debug heap?

Thank you.


Solution

The debug heap impacts performance in two ways:

First, it adds checks to the heap integrity during heap operations. I haven't found details on these checks, but one assumes that on each allocation or free, it involves verifying the integrity of the data structures used to manage the heap.

Second, it disables the low-fragmentation heap (LFH) option. In a release build, you get LFH by default. In a debug build, you don't--unless you use the _NO_DEBUG_HEAP. This isn't necessarily a speed penalty, but it might be.

There are clues in the documentation for HeapSetInformation.

Note that the C and C++ runtime libraries provide memory management built on top of the system heap APIs, and they also have debug and non-debug modes that can affect performance. There is more detailed documentation about what the debug CRT does. You might check and see if turning off the CRT debugging is enough to get you a significant boost in performance without messing with the debug mode of the process heap.



Answered By - Adrian McCarthy
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, August 19, 2022

[FIXED] How do I set specific environment variables when debugging in Visual Studio?

 August 19, 2022     debugging, environment-variables, visual-studio     No comments   

Issue

On a class library project, I set the "Start Action" on the Debug tab of the project properties to "Start external program" (NUnit in this case). I want to set an environment variable in the environment this program is started in. How do I do that? (Is it even possible?)

EDIT:

It's an environment variable that influences all .NET applications (COMplus_Version, it sets the runtime version) so setting it system wide really isn't an option.

As a workaround I just forced NUnit to start in right .NET version (2.0) by setting it in nunit.exe.config, though unfortunately this also means all my .NET 1.1 unit tests are now also run in .NET 2.0. I should probably just make a copy of the executable so it can have its own configuration file...

(I am keeping the question open (not accepting an answer) in case someone does happen to find out how (it might be useful for other purposes too after all...))


Solution

In Visual Studio 2008 and Visual Studio 2005 at least, you can specify changes to environment variables in the project settings.

Open your project. Go to Project -> Properties... Under Configuration Properties -> Debugging, edit the 'Environment' value to set environment variables.

For example, if you want to add the directory "c:\foo\bin" to the path when debugging your application, set the 'Environment' value to "PATH=%PATH%;c:\foo\bin".

Here's a screenshot of the settings dialog



Answered By - John Dibling
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, August 17, 2022

[FIXED] How to prevent the Output window in VS from disappearing?

 August 17, 2022     debugging, output, visual-studio, window     No comments   

Issue

when I press Start to run my application in VS 2017 Community my Output window disappears. (I use it for i.e. Debug.WriteLine().)
How to prevent this?

P.S. The output window I`m refering to (not the command line window!): The output window

Thanks
~Julius


Solution

After starting your application (debug mode), click View > Output (Ctrl + Alt + O) to show the output window. Stop your application and restart Visual Studio. Next time you run your application the output window should be visible automatically because Visual Studio remembers your opened windows in debug mode.



Answered By - Martin D.
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, August 16, 2022

[FIXED] Why is the ratio of the Surface Area to Volume Ratios of a Octahedron and Cube, a constant, not reflected in my program?

 August 16, 2022     debugging, geometry, math, output, python     No comments   

Issue

I've reached a wall in publishing my paper due to the issue of two platonic solids I'm coding for their SA:V: The cube and octahedron.

Normally, when one derivates the SA:V ratio for a cube and octahedron, it will come out to 6/a and (3*sqrt(6))/a, respectively.

When you take those ratios as a ratio, you get a constant non 1:1 ratio for all size regimes so, how is my output a 1:1 relationship?

Output (click link):

Graph of Ratios:

Table

Relevant code for both shapes in all instances for user request, tabulation, and graphing (ignore icosahedron code): First Instance:

    elif name_of_polyhedron == 'Octahedron':
        a = d/math.sqrt(2)
        SA_vex_octa = ((2*math.sqrt(3))*a**2)
        V_vex_octa = (((math.sqrt(2))/(3))*a**3)
        ratio_vex_octa = (SA_vex_octa/V_vex_octa)
        print('The surface area of your octahedron is as follows:' +str(SA_vex_octa)+ 'm^2')
        print('The volume of your octahedron is as follows:' +str(V_vex_octa)+ 'm^3')
        print('The surface area to volume ratio of your octahedron is as follows:' 
        +str(ratio_vex_octa))
        print('See how your ratio compares below!')
    elif name_of_polyhedron == 'Icosahedron':
        a = 4*(1/(math.sqrt(10+2*math.sqrt(5))))*((1/2)*d)
        SA_vex_icosa = 5*(a**2)*math.sqrt(3)
        V_vex_icosa = (5/12)*(a**3)*(3+sqrt(5))
        ratio_vex_icosa = SA_vex_icosa/V_vex_icosa
        print('The surface area of your icosahedron is as follows:' +str(SA_vex_icosa)+ 'm^2')
        print('The volume of your icosahedron is as follows:' +str(V_vex_icosa)+ 'm^3')
        print('The surface area to volume ratio of your icosahedron is as follows:' 
        +str(ratio_vex_icosa))
        print('See how your ratio compares below!')
    elif name_of_polyhedron == 'Cube':
        a = d/math.sqrt(3)
        SA_vex_cube = 6*a**2
        V_vex_cube = a**3
        ratio_vex_cube = SA_vex_cube/V_vex_cube
        print('The surface area of your cube is as follows:' +str(SA_vex_cube)+ 'm^2')
        print('The volume of your cube is as follows:' +str(V_vex_cube)+ 'm^3')
        print('The surface area to volume ratio of your cube is as follows:' +str(ratio_vex_cube))
        print('See how your ratio compares below!')

#Second Instance

a_4 = d/math.sqrt(2)
SA_vex_octa = (2*math.sqrt(3))*(a_4)**2
V_vex_octa = ((math.sqrt(2))/(3))*(a_4)**3
ratio_vex_octa = SA_vex_octa/V_vex_octa

a_5 = 4*(1/(math.sqrt(10+2*math.sqrt(5))))*((1/2)*d)
SA_vex_icosa = 5*((a_5)**2)*math.sqrt(3)
V_vex_icosa = (5/12)*((a_5)**3)*(3+math.sqrt(5))
ratio_vex_icosa = SA_vex_icosa/V_vex_icosa

a_6 = d/math.sqrt(3)
SA_vex_cube = 6*(a_6)**2
V_vex_cube = (a_6)**3
ratio_vex_cube = SA_vex_cube/V_vex_cube

#Third Instance

a_3 = (2/math.sqrt(6))*d
a_4 = d/math.sqrt(2)
a_5 = (2/(math.sqrt(10+2*math.sqrt(5))))*d
a_6 = d/math.sqrt(3)
a_7 = (2/(math.sqrt(3)*(1+math.sqrt(5)))*d)
a_8 = ((2/(math.sqrt(10+2*math.sqrt(5))))*d)
a_9 = ((2/(math.sqrt(50+22*math.sqrt(5))))*d)
a_10 = ((3/(math.sqrt(3)*(3+math.sqrt(5))))*d)
a_11 = ((2/(math.sqrt(50+22*math.sqrt(5))))*d)
SA_vex_tetra = (((a_3)**2)*math.sqrt(3))
V_vex_tetra = ((((a_3)**3)/12)*math.sqrt(2))
ratio_vex_tetra = [SA_vex_tetra/V_vex_tetra]
SA_vex_octa = (2*math.sqrt(3))*(a_4)**2
V_vex_octa = ((math.sqrt(2))/(3))*(a_4)**3
ratio_vex_octa = SA_vex_octa/V_vex_octa
SA_vex_icosa = 5*((a_5)**2)*math.sqrt(3)
V_vex_icosa = (5/12)*(a_5)**3*(3+math.sqrt(5))
ratio_vex_icosa = SA_vex_icosa/V_vex_icosa
SA_vex_cube = 6*(a_6)**2
V_vex_cube = (a_6)**3
ratio_vex_cube = SA_vex_cube/V_vex_cube

Table/Graph where they occur:

import matplotlib.pyplot as plt
from tabulate import tabulate
z = [('Tetrahedon',a_2,'Platonic',d,SA_vex_tetra,V_vex_tetra,ratio_vex_tetra),
   ('Octahedron',a_2,'Platonic',d,SA_vex_octa,V_vex_octa,ratio_vex_octa),
   ('Icosahedron',a_2,'Platonic',d,SA_vex_icosa,V_vex_icosa,ratio_vex_icosa),
   ('Cube',a_2,'Platonic',d,SA_vex_cube,V_vex_cube,ratio_vex_cube),
   ('Dodecahedron',a_2,'Platonic',d,SA_vex_dodeca,V_vex_dodeca,ratio_vex_dodeca),
   ('Cuboctahedron',a_2,'Archimedes',d,SA_vex_cubocta,V_vex_cubocta,ratio_vex_cubocta),
   ('Rhombicuboctahedron',a_2,'Archimedes',d,SA_vex_rhocubocta,V_vex_rhocubocta,ratio_vex_X), 
   ('Snub Cube',a_2,'Archimedes',d,SA_vex_scube,V_vex_scube,ratio_vex_scube),
   ('Snub Dodecahedron',a_2,'Archimedes',d,SA_vex_sndodeca,V_vex_sndodeca,ratio_vex_sndodeca),
   ('Rhombicosidodecahedron',a_2,'Archimedes',d,SA_vex_ridodeca,V_vex_ridodeca,ratio_vex_ridodeca),
   ('Truncated Octahedron',a_2,'Archimedes',d,SA_vex_ridodeca,V_vex_ridodeca,ratio_vex_sndodeca),
   ('Deltoidal Icositetrahedron','Catalan',a_2,d,SA_vex_delicotetra,V_vex_delicotetra,ratio_vex_X),
   ('Great Dodecahedron',a_1,'Kepler-Poinsot',d,SA_cav_gdodeca,V_cav_gdodeca,ratio_cav_gdodeca),
   ('Great Icosahedron',a_1,'Kepler-Poinsot',d,SA_cav_gicosa,V_cav_gicosa,ratio_cav_gicosa),
   ('Great-Stellated Dodecahedron',a_1,'Kepler-Poinsot',d,SA_cav_gsdodeca,V_cav_gsdodeca,ratio_X_X),
   ('Small-Stellated Dodecahedron',a_1,'Kepler Poinsot',d,SA_cav_ssdodeca,V_cav_ssdodeca,X),
   ('Stellated Octahedron',a_1,'Da Vinci',d,SA_cav_stocta,V_cav_stocta,ratio_cav_stocta),
   ('Medial Rhombic Triacontahedron',a_1,'A-R',(Wenninger)',d,SA_cav_mrtria,V_cav_mrtria,X),
   ('Dodecadodecahedron',a_1,'A-R (Wenninger)',d,SA_cav_ddodeca,V_cav_ddodeca,ratio_cav_ddodeca),
   ('Medial Triambic Icosahedron',a_1,'A-R', (Wenninger)',d,SA_cav_mticosa,V_cav_mticosa,X),
   ('Small Ditrigonal Icosidodecahedron',a_1,'A-R',(Wenninger)',d,SA_cav_sdicosi,V_cav_sdicosi,X),
   ('Excavated Dodecahedron',a_1,'A-R',(Wenninger)',d,SA_cav_exdodeca,V_cav_exdodeca,X),
   ('Sphere',a_12,a_12,d,SA_sphere,V_sphere,ratio_sphere)]
   table_1 = tabulate(z, headers=['Shape','Type','Subtype','C.D. (m)',
         'SA (m^2)','V(m^3)','SA:V'], tablefmt='fancy_grid') #orgtbl or f or pretty
   print(table_1)

Platonic_Array_Ratios = [ratio_vex_tetra,ratio_vex_octa,
                         ratio_vex_icosa,ratio_vex_cube,
                         ratio_vex_dodeca,ratio_sphere]



plt.title('Surface Area to Volume Ratio of Platonic Polyhedra Against Referential Sphere for 
Given 
Diameter')
plt.barh(['Tetrahedron', 'Octahedron', 
        'Icosahedron', 'Cube', 
        'Dodecahedron', 'Sphere'], Platonic_Array_Ratios)
plt.show()

# Platonic
plt.scatter(d,ratio_vex_tetra,label='Tetrahedron', color='b')
plt.scatter(d,ratio_vex_octa,label='Octahedron', color='g')
plt.scatter(d,ratio_vex_icosa,label='Icosahedron', color='y')
plt.scatter(d,ratio_vex_cube,label='Cube', color='m')
plt.scatter(d,ratio_vex_dodeca,label='Dodecahedron', color='c')

plt.scatter(d,ratio_sphere,label='Referential Sphere', color='r')
plt.axvline(x=d_vertical_slash, color='k')

plt.title('Comparison of SA:V of Platonic polyhedra against Referential Sphere with D(m)')
plt.xlabel('Circumspherical Diameter/Diagonal (m)')
plt.ylabel('Ratio Index')

plt.grid(alpha=.4,linestyle='--')

plt.xscale("log")

plt.legend(loc = 1)
plt.show()

I've meticulously quadruple checked the calculations by hand and by widgets online...they are all correct and match each other in all of the calculations the program outputs, but something it still wrong. It seems as if one is overwriting the other, but where?

Note: There is no error message in this code. I also apologize for the long code. I had to copy and paste things all together in some cases for reproducibility or just to give greater context. X is just a placeholder for formatting.


Solution

You are calculating "Surface Area to Volume Ratio of Platonic Polyhedra Against Referential Sphere for Given Diameter" [boldface added]

So before you compare the cube to the octahedron, you compare the cube to the sphere of the cube's diameter, and the octahedron to the sphere of the octahedron's diameter.

(I presume this means circumscribed spheres; I'm not going to check inscribed spheres.)

The SA/V ratio of a sphere is 6/d, where d is the diameter.

The maximum diameter of a cube of edge-length a is sqrt(3)a, so the cube/sphere ratio is (6/a)/(6/(sqrt(3)a)) = sqrt(3)

The maximum diameter of an octahedron of edge-length a is sqrt(2)a, so the octahedron/sphere ratio is (3sqrt(6)/a)/(6/(sqrt(2)a)) = sqrt(3)

So the ratio comes out to 1:1, due to the comparison to spheres.



Answered By - Beta
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, August 5, 2022

[FIXED] How do I find where an exception was thrown in C++?

 August 05, 2022     c++, debugging, exception-handling     No comments   

Issue

I have a program that throws an uncaught exception somewhere. All I get is a report of an exception being thrown, and no information as to where it was thrown. It seems illogical for a program compiled to contain debug symbols not to notify me of where in my code an exception was generated.

Is there any way to tell where my exceptions are coming from short of setting 'catch throw' in gdb and calling a backtrace for every single thrown exception?


Solution

Here's some info that may be of use in debugging your problem

If an exception is uncaught, the special library function std::terminate() is automatically called. Terminate is actually a pointer to a function and default value is the Standard C library function std::abort(). If no cleanups occur for an uncaught exception†, it may actually be helpful in debugging this problem as no destructors are called.
†It is implementation-defined whether or not the stack is unwound before std::terminate() is called.


A call to abort() is often useful in generating a core dump that can be analyzed to determine the cause of the exception. Make sure that you enable core dumps via ulimit -c unlimited (Linux).


You can install your own terminate() function by using std::set_terminate(). You should be able to set a breakpoint on your terminate function in gdb. You may be able to generate a stack backtrace from your terminate() function and this backtrace may help in identifying the location of the exception.

There is a brief discussion on uncaught exceptions in Bruce Eckel's Thinking in C++, 2nd Ed that may be helpful as well.


Since terminate() calls abort() by default (which will cause a SIGABRT signal by default), you may be able to set a SIGABRT handler and then print a stack backtrace from within the signal handler. This backtrace may help in identifying the location of the exception.


Note: I say may because C++ supports non-local error handling through the use of language constructs to separate error handling and reporting code from ordinary code. The catch block can be, and often is, located in a different function/method than the point of throwing. It has also been pointed out to me in the comments (thanks Dan) that it is implementation-defined whether or not the stack is unwound before terminate() is called.

Update: I threw together a Linux test program called that generates a backtrace in a terminate() function set via set_terminate() and another in a signal handler for SIGABRT. Both backtraces correctly show the location of the unhandled exception.

Update 2: Thanks to a blog post on Catching uncaught exceptions within terminate, I learned a few new tricks; including the re-throwing of the uncaught exception within the terminate handler. It is important to note that the empty throw statement within the custom terminate handler works with GCC and is not a portable solution.

Code:

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#ifndef __USE_GNU
#define __USE_GNU
#endif

#include <execinfo.h>
#include <signal.h>
#include <string.h>

#include <iostream>
#include <cstdlib>
#include <stdexcept>

void my_terminate(void);

namespace {
    // invoke set_terminate as part of global constant initialization
    static const bool SET_TERMINATE = std::set_terminate(my_terminate);
}

// This structure mirrors the one found in /usr/include/asm/ucontext.h
typedef struct _sig_ucontext {
   unsigned long     uc_flags;
   struct ucontext   *uc_link;
   stack_t           uc_stack;
   struct sigcontext uc_mcontext;
   sigset_t          uc_sigmask;
} sig_ucontext_t;

void crit_err_hdlr(int sig_num, siginfo_t * info, void * ucontext) {
    sig_ucontext_t * uc = (sig_ucontext_t *)ucontext;

    // Get the address at the time the signal was raised from the EIP (x86)
    void * caller_address = (void *) uc->uc_mcontext.eip;
    
    std::cerr << "signal " << sig_num 
              << " (" << strsignal(sig_num) << "), address is " 
              << info->si_addr << " from " 
              << caller_address << std::endl;

    void * array[50];
    int size = backtrace(array, 50);

    std::cerr << __FUNCTION__ << " backtrace returned " 
              << size << " frames\n\n";

    // overwrite sigaction with caller's address
    array[1] = caller_address;

    char ** messages = backtrace_symbols(array, size);

    // skip first stack frame (points here)
    for (int i = 1; i < size && messages != NULL; ++i) {
        std::cerr << "[bt]: (" << i << ") " << messages[i] << std::endl;
    }
    std::cerr << std::endl;

    free(messages);

    exit(EXIT_FAILURE);
}

void my_terminate() {
    static bool tried_throw = false;

    try {
        // try once to re-throw currently active exception
        if (!tried_throw++) throw;
    }
    catch (const std::exception &e) {
        std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
                  << e.what() << std::endl;
    }
    catch (...) {
        std::cerr << __FUNCTION__ << " caught unknown/unhandled exception." 
                  << std::endl;
    }

    void * array[50];
    int size = backtrace(array, 50);    

    std::cerr << __FUNCTION__ << " backtrace returned " 
              << size << " frames\n\n";

    char ** messages = backtrace_symbols(array, size);

    for (int i = 0; i < size && messages != NULL; ++i) {
        std::cerr << "[bt]: (" << i << ") " << messages[i] << std::endl;
    }
    std::cerr << std::endl;

    free(messages);

    abort();
}

int throw_exception() {
    // throw an unhandled runtime error
    throw std::runtime_error("RUNTIME ERROR!");
    return 0;
}

int foo2() {
    throw_exception();
    return 0;
}

int foo1() {
    foo2();
    return 0;
}

int main(int argc, char ** argv) {
    struct sigaction sigact;

    sigact.sa_sigaction = crit_err_hdlr;
    sigact.sa_flags = SA_RESTART | SA_SIGINFO;

    if (sigaction(SIGABRT, &sigact, (struct sigaction *)NULL) != 0) {
        std::cerr << "error setting handler for signal " << SIGABRT 
                  << " (" << strsignal(SIGABRT) << ")\n";
        exit(EXIT_FAILURE);
    }

    foo1();

    exit(EXIT_SUCCESS);
}

Output:

my_terminate caught unhanded exception. what(): RUNTIME ERROR!
my_terminate backtrace returned 10 frames

[bt]: (0) ./test(my_terminate__Fv+0x1a) [0x8048e52]
[bt]: (1) /usr/lib/libstdc++-libc6.2-2.so.3 [0x40045baa]
[bt]: (2) /usr/lib/libstdc++-libc6.2-2.so.3 [0x400468e5]
[bt]: (3) /usr/lib/libstdc++-libc6.2-2.so.3(__rethrow+0xaf) [0x40046bdf]
[bt]: (4) ./test(throw_exception__Fv+0x68) [0x8049008]
[bt]: (5) ./test(foo2__Fv+0xb) [0x8049043]
[bt]: (6) ./test(foo1__Fv+0xb) [0x8049057]
[bt]: (7) ./test(main+0xc1) [0x8049121]
[bt]: (8) ./test(__libc_start_main+0x95) [0x42017589]
[bt]: (9) ./test(__eh_alloc+0x3d) [0x8048b21]

signal 6 (Aborted), address is 0x1239 from 0x42029331
crit_err_hdlr backtrace returned 13 frames

[bt]: (1) ./test(kill+0x11) [0x42029331]
[bt]: (2) ./test(abort+0x16e) [0x4202a8c2]
[bt]: (3) ./test [0x8048f9f]
[bt]: (4) /usr/lib/libstdc++-libc6.2-2.so.3 [0x40045baa]
[bt]: (5) /usr/lib/libstdc++-libc6.2-2.so.3 [0x400468e5]
[bt]: (6) /usr/lib/libstdc++-libc6.2-2.so.3(__rethrow+0xaf) [0x40046bdf]
[bt]: (7) ./test(throw_exception__Fv+0x68) [0x8049008]
[bt]: (8) ./test(foo2__Fv+0xb) [0x8049043]
[bt]: (9) ./test(foo1__Fv+0xb) [0x8049057]
[bt]: (10) ./test(main+0xc1) [0x8049121]
[bt]: (11) ./test(__libc_start_main+0x95) [0x42017589]
[bt]: (12) ./test(__eh_alloc+0x3d) [0x8048b21]



Answered By - jschmier
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, July 17, 2022

[FIXED] What is NUXT Warning "Emitted value instead of an instance of Error" about?

 July 17, 2022     debugging, javascript, nuxt.js, vue.js, warnings     No comments   

Issue

I got this compiling warnings after applying this NUXT tutorial for adding Bulma as Global CSS:

nuxt-starter@1.0.0 dev /home/lsoave/Vue/nuxt-starter nuxt

nuxt:build App root: /home/lsoave/Vue/nuxt-starter +0ms nuxt:build Generating /home/lsoave/Vue/nuxt-starter/.nuxt files... +2ms
nuxt:build Generating files... +8ms nuxt:build Generating routes... +13ms nuxt:build Building files... +31ms nuxt:build Adding webpack middleware... +688ms ████████████████████ 100%

Build completed in 5.51s

WARNING Compiled with 14 warnings
13:30:56

warning in ./node_modules/bulma/css/bulma.css

(Emitted value instead of an instance of Error) postcss-custom-properties: /home/lsoave/Vue/sass/grid/columns.sass:469:4: Custom property ignored: not scoped to the top-level :root element (.columns.is-variable { ... --columnGap: ... })

@ ./node_modules/bulma/css/bulma.css 4:14-118 13:3-17:5 14:22-126
@ ./.nuxt/App.js @ ./.nuxt/index.js
@ ./.nuxt/client.js
@ multi webpack-hot-middleware/client?name=client&reload=true&timeout=30000&path=/__webpack_hmr ./.nuxt/client.js

...

Does anybody know why and how to get rid of those ?


Solution

As @P3trur0 stated in the comment, you should add the following to nuxt.config.js:

  /*
  ** Build configuration
  */
  build: {
    ...,
    postcss: {
      plugins: {
        "postcss-custom-properties": false
      }
    },
  }


Answered By - Shawn Lauzon
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing