71
\$\begingroup\$

Your task is to write a program that executes in as many languages as possible, with as few characters as you can. To avoid trivial solutions, the program must print the name of the language it was run in.

Scoring

Your program has to work in at least 5 languages. A program's score is given as:

$$\frac {\text{(number of languages)}^{1.5}} {\text{(length of program)}}$$

The highest score wins.

\$\endgroup\$
4
  • \$\begingroup\$ Would using a solution like using print() for Perl, Python, PHP, Processing and R be considered trivial or is it acceptable? \$\endgroup\$
    – anon
    Sep 10, 2012 at 23:34
  • 4
    \$\begingroup\$ A can't see a problem with it. The difficulty would be switching print's input per language. \$\endgroup\$
    – mjgpy3
    Sep 11, 2012 at 2:57
  • \$\begingroup\$ I should have given a higher weight to the number of languages... it seems choosing to have exactly 5 is the most optimal. I wonder how many languages would have been in the winner entry if the score were n * n / length \$\endgroup\$
    – vsz
    Sep 11, 2012 at 18:47
  • \$\begingroup\$ I was going to suggest that too. Based on the answers provided, I don't believe I interpreted your question properly. \$\endgroup\$
    – anon
    Sep 11, 2012 at 23:10

17 Answers 17

42
\$\begingroup\$

Bash, C, C++, Obj-C, Obj-C++, Perl, PHP, Ruby, 183 chars

score ~ 0.1236

For the C and C-like codes I owe a debt to @baby-rabbit. The others are inspired by the recognition that many languages have an eval statement that will grudgingly accept invalid syntax.

Outputs the language name to standard output. Sometimes generates a lot of error messages on standard error, so suppress them with 2>/dev/null as you run them.

#if 0
'PHP<?/*';eval "print\$=?'Perl':'Ruby';echo Bash";exit
__END__
#endif
#include <stdio.h>
main(){puts(
#ifdef __OBJC__
"obj-"
#endif
"C"
#ifdef __cplusplus
"++"
#endif
);}//*/?>'

The php solution outputs 'PHP' (including the single quotes), which may be bending the rules a little bit.

Last edit: shaved 12 chars from insight that $= is false in Ruby, 60 in Perl, and print$=?... is almost surely an error in Bash. Shaved 7 more from insight the Perl/Ruby/Bash test can now go into a single eval statement.

If the rules can tolerate more bending, I present this 8 language, 43 character solution (score 0.5262)

print("phperluarscriptrubypythoncatebg13");

for which the output includes the name of the interpreter for php, perl, lua, rscript, ruby, python, cat, and rot13.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ TI-Basic supports the last one; just add 6 characters and get print("phperluarscriptrubypythontibasicatebg13"); \$\endgroup\$
    – Timtech
    Dec 31, 2013 at 0:36
  • 1
    \$\begingroup\$ @Timtech no, TI-Basic uses the Disp or Output( or text( tokens, there is no print( command. And including a string as part of an otherwise real-valued expression results in an ERR:INVALID SYNTAX, not the display of the string (not even as a return value). (Also, there is no ;; TI-Basic uses :) \$\endgroup\$ Feb 5, 2014 at 21:57
  • \$\begingroup\$ @AJMansfield Too true, how could I forget :? \$\endgroup\$
    – Timtech
    Feb 5, 2014 at 23:17
  • 14
    \$\begingroup\$ Can you replace echo Bash with ps -ocomm= -p$$? This will output the name of the shell for at least bash, zsh, ksh, csh and tcsh, maybe others. \$\endgroup\$ May 30, 2014 at 19:22
20
\$\begingroup\$

C, C++, BF, BASH and Ruby; 280 chars

Score is about 0.040

#include "stdio.h"
#define s "C"
#ifdef __cplusplus
#define s "C++"
#endif
#ifndef s
#"+++++++++[>++++++++++>+++++++++<<-]>>-.<++++.>-.++++++++.<----.>---.<+++++++.>---.++++++++.<<++++++++++.[-]"
if [ 1 == 2 ];then
puts "Ruby"
exit
fi
echo "BASH"
exit
end
#endif
main(){puts(s);}

Note that I am using a Linux system.

The code is run or compiled with the following commands (the file's name is test.c)

C:

gcc test.c

When run with ./a.out, output is C

C++:

c++ test.c

When run with ./a.out, output is C++

BASH:

./test.c

Outputs: BASH

Ruby:

ruby test.c

Outputs: Ruby

BrainF***:

Verified using the following:

Outputs: brainfuck

Note that if the JS debugger is used, then the first two minus signs need to be removed. They were included to offset the plus signs in the string literal "C++". This was a very fun project, I'm working on adding more languages.

Just to add further clarity, here are my interpreter's/compiler's specs:

  • gcc version 4.6.3

  • ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-linux]

  • GNU bash, version 4.2.24(1)-release (x86_64-pc-linux-gnu)

SIDE NOTE

Using @baby-rabbit's trick I was able to extend my code to be executable in 7 languages (objective-C and objective-c++ being added). This is not my solution since I did copy some, but I thought I would show it off.

Update 9.12 Added SmallTalk run with gnu-smalltalk!

SmallTalk, C, C++, Objective-C, Objective-C++, BASH, BF, Ruby; 384 chars (Score: 0.059)

#if (a)
##(true) ifTrue: ['SmallTalk' printNl]
##(ObjectMemory quit)
#"+++++++++++[>++++++++++>+++++++++<<-]>>-.<++++.>-.++++++++.<----.>---.<+++++++.>---.++++++++.<<++++++++++.[-]"
if [ 1 == 2 ];then
puts 'Ruby'
exit
fi
echo 'BASH'
exit
end
=begin
#endif
#include "stdio.h"
main(){puts(
#ifdef __OBJC__
"Objective-"
#endif
"C"
#ifdef __cplusplus
"++"
#endif
);}
#ifdef b
=end
#endif

In the above code you will need to rename the file to produce the langauge's name for objective-c, obj-c++, c and c++.

\$\endgroup\$
3
  • \$\begingroup\$ would it be shorter if you output brainf***? \$\endgroup\$
    – mob
    Sep 11, 2012 at 20:15
  • \$\begingroup\$ Yes it would, I believe. \$\endgroup\$
    – mjgpy3
    Sep 12, 2012 at 3:42
  • \$\begingroup\$ You should use if [ 1 = 2 ] instead of if [ 1 == 2 ], because scripts without a hashbang are executed by sh, not bash. sh may or may not be bash, on Debian it's dash. \$\endgroup\$ May 1, 2014 at 15:13
13
\$\begingroup\$

bash, c, c++, obj-c, obj-c++; 134 chars; score=0.083

#if x
echo "bash"
exit
#endif
#include <stdio.h>
int main(){puts(
#ifdef __OBJC__
"obj-"
#endif
"c"
#ifdef __cplusplus
"++"
#endif
);}

rename file and run/compile as:

  • sh file.sh
  • cc file.c
  • cc file.cpp
  • cc file.m
  • cc file.mm

(where cc is clang-421.10.42)

\$\endgroup\$
1
  • \$\begingroup\$ +1 since many other upvoted answers were inspired by yours. \$\endgroup\$
    – Kevin
    Jan 1, 2014 at 21:17
11
\$\begingroup\$

Lua, Ruby, VimL, Sed, Befunge (129 chars; ~0.087 points)

Not sure if this one counts--the sed-part is embedded in the shebang line which is arguably a hack to get around the restriction. This also means that it should be run as an executable and not directly with sed.

I was lucky that all the other languages (sans Befunge) automagically ignores the shebang line (though apparently Ruby refuses to run the file if it has a shebang line that doesn't contain the string 'ruby' in it).

#!sed sanava;s/.*/sed/;q;ruby
--"".to_i#>"egnufeB">:#,_@
if 0
then
if IO
then
puts"Ruby"
else
print"Lua"
end
else
echo"VimL"
end

Sample usage:

% lua tmp/glot.poly
Lua
% ruby tmp/glot.poly
Ruby
% ./tmp/glot.poly
sed
% cfunge tmp/glot.poly       # Requires Befunge-98
Befunge

:source tmp/glot.poly        # from vim
VimL                         # displayed as message
\$\endgroup\$
1
  • 5
    \$\begingroup\$ Wow, a solution that does not include C \$\endgroup\$
    – vsz
    Sep 11, 2012 at 20:11
9
\$\begingroup\$

AsciiDots, Befunge-93, C, C++, ><>, Funge-98, GolfScript, lua, MinkoLang, Python 2, Python 3, Ruby, vi (0.170444 points)

#/* ["39-egnufeB">:|;ooo"><>"
n,n=1,1--[[],0][1]#>52*,@
"""""GolfScript"
puts"Ruby\n"
__END__
:puts{"""
print("Python %d"%(3/2*2));
"""stoDiicsA"$\<ESC>dggivi<ESC>ZZ*/
#include<stdio.h>
main(){puts(sizeof'a'-1?"C":"C++");}
//>"Minkolang"9[O]."
//^}>"89-egnuF"#[v,<]"]]print"lua"--"""

<ESC> stands for the literal escape character 27

I know this is an old post, but it was interesting so I had to give it a shot :P

\$\endgroup\$
8
\$\begingroup\$

BF, Bash, Batch, C, vi (163 characters; score ≈ .0686)

(<ESC> stands for ASCII code 27.)

rem (){ ((0));};true /*
rem ;goto(){ rem;}
rem ivi<ESC>ZZ'++++++++[>NUL ++++++++<NUL -]>NUL ++.++++.*/;main(){puts("C");}/*'
goto a
echo Bash
exit
:a
echo Batch
rem */

I tested this, as a batch file, with the MS-DOS 6.22 version of COMMAND.COM. By default, that interpreter mixes lines of source code with the output. To prevent that from happening, execute echo off before running the batch file.

To execute the vi code, which I have only tested using Vim, use the following command:

cat /dev/null > tmpfile && vi -s polyglot.sh tmpfile > /dev/null 2>&1 && cat tmpfile
\$\endgroup\$
1
  • 1
    \$\begingroup\$ You could use touch tmpfile or : > tmpfile instead of cat /dev/null > tmpfile. \$\endgroup\$ Dec 30, 2013 at 22:32
6
\$\begingroup\$

Every Python Release, 18.37291 points

import sys
print('Python '+'.'.join(map(str,sys.version_info[:-2])))

Technically valid, if you consider all the python versions to be different languages. There are currently 116 python versions, which I believe gives me a score of around 18.37291.

(Also I understand if this isn't considered a valid answer, this was just for fun)

\$\endgroup\$
3
  • \$\begingroup\$ you still get my +1 just for fun. \$\endgroup\$
    – vsz
    Aug 5, 2019 at 18:15
  • \$\begingroup\$ Is printing the complete version number viable? (This golfs down 4 bytes and extends the possible Python versions.) \$\endgroup\$
    – user85052
    Sep 14, 2019 at 12:38
  • \$\begingroup\$ Also is this okay? tio.run/##K6gsycjPM/7/… \$\endgroup\$
    – user85052
    Sep 14, 2019 at 12:44
5
\$\begingroup\$

bash, zsh, ksh, csh, tcsh, 15 chars, score 0.745

This one's a bit of a stretch since they're all related languages, but there are differences:

ps -ocomm= -p$$
\$\endgroup\$
2
  • \$\begingroup\$ What about dash? \$\endgroup\$
    – Elliot A.
    Feb 6, 2016 at 15:37
  • \$\begingroup\$ @Elliota List of languages that worked on tio.run: Bash, Dash, ksh, OSH, tcsh, Zsh. bosh displayed sh and yash displayed ps. \$\endgroup\$
    – user100411
    Jul 15, 2021 at 9:41
4
\$\begingroup\$

16 languages, 348 bytes, score: 0.183908046

#include <stdio.h>
#if 0
#replace "C(gcc)" "C(ecpp)"
#replace "C++(gcc)" "C++(ecpp)"
#endif
#ifdef __clang__
#define d 2
#elif __TINYC__
#define d 4
#else
#define d 0
#endif // rk:start print: "rk" \
ps -ocomm= -p$$; exit;
int x=sizeof('a')%2+d;char*arr[]={"C(gcc)","C++(gcc)","C(clang)","C++(clang)","C(tcc)"};int main(){puts(arr[x]);}

This works in C(gcc), C++(gcc), C(ecpp), C++(ecpp), C(clang), C++(clang), C(tcc), sh, dash, bash, zsh, ksh, csh, tcsh, rk, and SIL.

\$\endgroup\$
3
\$\begingroup\$

Bash, C, Gawk, Perl, vi (145 characters; score ≈ .077)

(<BS> stands for ASCII code 8. <ESC> stands for ASCII code 27.)

#define echo//<BS><BS><BS>vi<ESC>ZZ
#define BEGIN A()
#define B\
{
echo Bash ;exit;
#define C\
}
BEGIN {printf(A=="A"?"Perl":"Gawk");exit;}
main(){puts("C");}

To execute the vi code, which I have only tested using Vim, use this command:

cat /dev/null > tmpfile && vi -s polyglot.sh tmpfile > /dev/null 2>&1 && cat tmpfile
\$\endgroup\$
3
\$\begingroup\$

Java, Lisp, Whitespace, Intercal, PHP, Befunge-98; score =.0189

This was originally an answer to this.

 ;\\0"egnufeB">:#,_@SSSTTTSTTTL
;TL
;SSSSSTTSTSSSL
;TL
;SSSSSTTSTSSTL
;TL
;SSSSSTSTSTSSL
;TL
;SSSSSTTSSTSTL
;TL
;SSSSSTSTSSTTL
;TL
;SSSSSTTTSSSSL
;TL
;SSSSSTTSSSSTL
;TL
;SSSSSTTSSSTTL
;TL
;SSSSSTTSSTSTL
;SSL
;L
;L
;L
;public class H{ public static void main(String []a){System.out.println("JAVA");}}
;/*
(print "LISP")
;*/
;//<?php
; echo "PHP"
;//?>
;/*
#|
DO ,1 <- #8
DO ,1 SUB #1 <- #110
DO ,1 SUB #2 <- #32
DO ,1 SUB #3 <- #72
DO ,1 SUB #4 <- #136
DO ,1 SUB #5 <- #88
DO ,1 SUB #6 <- #136
PLEASE DO ,1 SUB #7 <- #64
DO ,1 SUB #8 <- #80
PLEASE READ OUT ,1
PLEASE NOTE |#
;*/
;// PLEASE GIVE UP
\$\endgroup\$
4
  • \$\begingroup\$ This won't work in Java; every line until public class... will cause a compiler problem. \$\endgroup\$
    – Ypnypn
    May 1, 2014 at 2:53
  • \$\begingroup\$ Interesting... I distinctly remember testing this in a compiler and it working... or perhaps my memory fails me... \$\endgroup\$ May 1, 2014 at 2:55
  • 1
    \$\begingroup\$ @Ypnypn Remember that "T" is a tab,"S" is a space, and "L" is a line feed in white-space, which is why it does not cause a compiler error. \$\endgroup\$ May 1, 2014 at 2:57
  • \$\begingroup\$ Oh; that makes sense. \$\endgroup\$
    – Ypnypn
    May 1, 2014 at 2:58
3
\$\begingroup\$

Befunge, 05AB1E (legacy), Vyxal, Red, Python 1, Vim, Zsh - 71.5 / 114 characters ≈ 0.164 score

'a;# "egnufeB"\\,,,,,,,@"05AB1E",q', 2>2
'a;`Vyxal`,Q', 2>2#;echo Zsh
print 'Red quit;' * 0+'Python', 1>0#<0x1B>}dHiVim

Try it in Befunge! 05AB1E! Vyxal! Red! Python! Vim! Zsh!

\$\endgroup\$
2
\$\begingroup\$

This is a cheap selection of languages, but here goes:

CoffeeScript, JScript, Mozilla Javascript (≈ JavaScript 1.3), ECMAScript Edition 5, ECMAScript Edition 3, 223 chars, score ≈ 0.0501)

a="undefined"
x="ECMAScript 3"
if(Array.prototype.map)
 x="ECMAScript 5"
if(typeof CoffeeScript!=a)
 x="CoffeeScript"
if(typeof uneval!=a)
 x="Mozilla JavaScript"
if(typeof WScript!=a)
 WScript.echo("JScript")
else alert(x)
\$\endgroup\$
6
  • 5
    \$\begingroup\$ JavaScript, JavaScript, JavaScript (≈ JavaScript), JavaScript, JavaScript, 263 chars, (score ≈ 0). you can also make it shorter a="undefined";if(typeof arguments!=a)...else if(typeof WScript!=a... oh and you can also try golfing it.... \$\endgroup\$ Oct 21, 2013 at 12:22
  • \$\begingroup\$ @tryingToGetProgrammingStraight Putting everything on one line like that is not valid syntax in CoffeeScript (which is a separate language from Javascript). The others are arguable, but since it wasn't specified how different the languages have to be, I think the fact that the different implementations have different specified behaviors allows them to be treated as separate. \$\endgroup\$ Oct 21, 2013 at 14:56
  • \$\begingroup\$ i also cant write a multi-line comment, the only golfing you seem to have used is leaving out {/}/;... the idea is to use a to avoid reusing "undefined", you could also do b=alert and then b("this is also still just javascript"). anyway The golden rule of CoffeeScript is: "It's just JavaScript" (from coffeescript.org), you can also use some jquery to add a sixth language.... \$\endgroup\$ Oct 21, 2013 at 15:55
  • 1
    \$\begingroup\$ @tryingToGetProgrammingStraight Adding jQuery would be absurd, since jQuery is a library, not a language. CoffeeScript is definitely not the same language as ECMAScript. The definition of a language is a set of finite strings over a finite alphabet. The set of strings representing valid CoffeeScript programs is not the same as the set of strings representing valid ECMAScript. \$\endgroup\$ Oct 22, 2013 at 21:57
  • 1
    \$\begingroup\$ Can you do [].map instead of Array.prototype.map? \$\endgroup\$ Feb 6, 2016 at 21:24
2
\$\begingroup\$

Windows Batch, TI-Basic, Golf-Basic 84, Quomplex, and GTB 5*2/93 = 0.11

::¤Quomplex¤:"'*[]'":~"GTB":g;1:d`"GOLF-BASIC 84":g`1:"TI-BASIC":Lbl 1:End
echo Windows Batch

How it works

Windows Batch was the easiest, because :: starts a comment. Fairly simple to implement.

TI-Basic doesn't support lowercase letters or backticks, causing it to skip the statements d`"GOLF-BASIC 84":g`1, which Golf-Basic evaulates, Displaying the message and forwarding to Label 1, where it is promptly ended. This is similar for GTB, with its handy display character, ~. By the way, a string with no display will be put in Ans. If there are no Display commands following it, Ans will be outputted (not the case here).

Quomplex was snuck in at the beginning because its complex syntax won't allow for much to be skipped. All it does is add "Quomplex" to the output, and then for the mastery of the program...

The Mastery of the Programming Syntax

:"'*[]'"

Pure genius. Quomplex ignores : and takes "' and '" as strings, leaving it to output the stack and perish in an infinite while loop ([]). Meanwhile, Golf-Basic and TI-Basic take the whole "'*[]'" as a string, because ' is a mathematical operator, not a string operator.

\$\endgroup\$
3
  • \$\begingroup\$ Strictly speaking, : indicates a label in a batch file, not a comment. It's true that it doesn't execute anything on its own, though. \$\endgroup\$
    – Mark
    Apr 24, 2014 at 20:19
  • \$\begingroup\$ @Mark True, but is is :: (still a label though). I'd rather use it than REM, especially since it is required in TI-Basic. \$\endgroup\$
    – Timtech
    Apr 24, 2014 at 22:13
  • \$\begingroup\$ Right - I was just being pedantic. Also, +1 for using batch files in the first place. :-) \$\endgroup\$
    – Mark
    Apr 25, 2014 at 0:26
2
\$\begingroup\$

JScript, EcmaScript Edition 3, 5, 6, 2016, Node, Mozilla JavaScript (score ≈ 0.1342)

This answer is originally based off Peter Olson's answer, but minus the CoffeeScript (as whitespace-significant languages can be horrible for golfing).

I also added Node, ES6 and ES2016 and golfed the code a little, almost tripling the original score.

$=this,y="EcmaScript ",x=$.module?"Node":$.uneval?"Mozilla JavaScript":"".padStart?y+2016:$.Map?y+6:[].map?y+5:y+3,($.WScript||$.alert)(x)
\$\endgroup\$
2
\$\begingroup\$

PE/bash/x86/C/Ruby/Python2, 330 bytes

score ≈ 0.0445

xxd:

00000000: 4d5a 7544 3d27 5c27 273b 0a23 2f2a 0a27  MZuD='\'';.#/*.'
00000010: 3b65 6368 6f20 6261 7368 2023 273b 7072  ;echo bash #';pr
00000020: 696e 7420 2830 616e 6427 5275 6279 2729  int (0and'Ruby')
00000030: 6f72 2750 7974 686f 6e32 2723 4000 0000  or'Python2'#@...
00000040: 5045 0000 4c01 0100 b802 00cd 10b8 0013  PE..L...........
00000050: eb2e 0000 7000 0301 0b01 0000 7075 7473  ....p.......puts
00000060: 0000 0065 7869 7400 f000 0000 6d73 7663  ...exit.....msvc
00000070: 7274 0000 0000 4000 0400 0000 0400 0000  rt....@.........
00000080: bb0f 00bd 8c7c eb58 0400 0000 7838 3600  .....|.X....x86.
00000090: 0004 0000 0100 0000 0000 0000 0300 0000  ................
000000a0: 0000 0000 0000 0000 0000 0000 0000 0000  ................
000000b0: 0000 0000 0200 0000 0000 0000 0000 0000  ................
000000c0: 0d01 0000 0000 0000 2e74 6578 7400 0000  .........text...
000000d0: 4500 0000 f000 0000 4500 0000 f000 0000  E.......E.......
000000e0: b903 00ba 0000 cd10 ebfe 0000 0000 0000  ................
000000f0: 6840 0040 00ff 1501 0140 00ff 1505 0140  h@.@.....@.....@
00000100: 005a 0000 0061 0000 0000 0000 0000 0000  .Z...a..........
00000110: 0000 0000 0000 0000 006c 0000 0001 0100  .........l......
00000120: 0000 0000 0000 0000 0000 0000 0000 0000  ................
00000130: 0000 0000 002a 2f0d 6d61 696e 2829 7b70  .....*/.main(){p
00000140: 7574 7328 2243 2229 3b7d                 uts("C");}

source:

; nasm

base equ 0x400000

;
; DOS header
;
; The only two fields that matter are e_magic and e_lfanew

mzhdr:
    dw "MZ"              ; DOS e_magic
    jnz a
    db "='\'';",10,"#/*",10,"';echo bash #';print (0and'Ruby')or'Python2'#"
    times 64 - 4 - ($-$$) db 0
    dd 64                ; DOS e_lfanew


;
; NT headers
;

PE: dd "PE"              ; PE signature

;
; NT file header
;

filehdr:
    dw 0x014C            ; Machine (Intel 386)
    dw 1                 ; NumberOfSections
;    dd 0                 ; TimeDateStamp UNUSED
;    dd 0                 ; PointerToSymbolTable UNUSED
;    dd 0                 ; NumberOfSymbols UNUSED
a:
    mov ax,2        ; 3 bytes
    int 0x10        ; 2 bytes  ; clear screen
    mov ax,0x1300   ; 3 bytes
    jmp b           ; 2 bytes
    dw 0            ; 2 bytes

    dw opthdrsize        ; SizeOfOptionalHeader
    dw 0x103             ; Characteristics

;
; NT optional header
;

opthdr:
    dw 0x10B                    ; Magic (PE32)
;    db 0                        ; MajorLinkerVersion UNUSED
;    db 0                        ; MinorLinkerVersion UNUSED
;    dd 0                        ; SizeOfCode UNUSED
;    dd 0                        ; SizeOfInitializedData UNUSED
;    dd 0                        ; SizeOfUninitializedData UNUSED
puts_: db 0,0,"puts",0
exit_: db 0,0,"exit",0
    dd start                    ; AddressOfEntryPoint
;    dd 0                        ; BaseOfCode UNUSED
;    dd 0                        ; BaseOfData UNUSED
crt: db "msvcrt",0,0
    dd base                     ; ImageBase
    dd 4                        ; SectionAlignment
    dd 4                        ; FileAlignment
;    dw 0                        ; MajorOperatingSystemVersion UNUSED
;    dw 0                        ; MinorOperatingSystemVersion UNUSED
;    dw 0                        ; MajorImageVersion UNUSED
;    dw 0                        ; MinorImageVersion UNUSED
b:
    mov bx,0xF           ; 3 bytes  ; video page, video attribute
    mov bp,0x7C00+x86    ; 3 bytes
    jmp c                ; 2 bytes

    dw 4                        ; MajorSubsystemVersion
    dw 0                        ; MinorSubsystemVersion UNUSED
;    dd 0                        ; Win32VersionValue UNUSED
x86: db "x86",0
    dd 1024                     ; SizeOfImage
    dd 1                        ; SizeOfHeaders          nonzero for Windows XP
    dd 0                        ; CheckSum UNUSED
    dw 3                        ; Subsystem (Console)
    dw 0                        ; DllCharacteristics UNUSED
    dd 0                        ; SizeOfStackReserve
    dd 0                        ; SizeOfStackCommit
    dd 0                        ; SizeOfHeapReserve
    dd 0                        ; SizeOfHeapCommit UNUSED
    dd 0                        ; LoaderFlags UNUSED
    dd 2                        ; NumberOfRvaAndSizes    for Windows 10; UNUSED in Windows XP

;
; Data directories (part of optional header)
;
    dd 0, 0                     ; Export Table UNUSED
    dd idata, 0                 ; Import Table

opthdrsize equ $ - opthdr

;
; Code section header
;

    db ".text", 0, 0, 0         ; Name
    dd codesize                 ; VirtualSize
    dd code                     ; VirtualAddress
    dd codesize                 ; SizeOfRawData
    dd code                     ; PointerToRawData
;    dd 0                        ; PointerToRelocations UNUSED
;    dd 0                        ; PointerToLinenumbers UNUSED
;    dw 0                        ; NumberOfRelocations UNUSED
c:
    mov cx,3      ; 3 bytes  ; text length
    mov dx,0      ; 3 bytes  ; text position
    int 0x10      ; 2 bytes  ; print text
    jmp $         ; 2 bytes  ; enter infinite loop

    dw 0                        ; NumberOfLinenumbers UNUSED
    dd 0                        ; Characteristics UNUSED

;
; Code section data
;

align 4, db 0

code:

;
; Entry point
;

bits 32
start:
    push base + PE
    call [base + puts]
    call [base + exit]

;
; Import address table (array of IMAGE_THUNK_DATA structures)
;

iat:
puts:   dd puts_                ; Import puts by name
exit:   dd exit_                ; Import exit by name
        dd 0                    ; terminator

;
; Import table (array of IMAGE_IMPORT_DESCRIPTOR structures)
;

idata:
    dd 0                        ; OriginalFirstThunk UNUSED
    dd 0                        ; TimeDateStamp UNUSED
    dd 0                        ; ForwarderChain UNUSED
    dd crt                      ; Name
    dd iat                      ; FirstThunk
    times 5 dd 0                ; terminator

codesize equ $ - code

db "*/",13,"main(){puts(",34,"C",34,");}"

Try it online in bash/C/Ruby/Python2.
Portable Executable polyglot.exe was tested on Windows 10 2004 64-bit and Windows XP SP3 32-bit.
Raw x86 was tested in QEMU 6.2.0: qemu-system-x86_64 -no-fd-bootchk -fda polyglot.

Inspired by/based on αcτµαlly pδrταblε εxεcµταblε, which is a PE/bash/x86 polyglot. Also based on this hello world PE.

Portable Executable

Main differences from hello world:

  • DOS and NT headers don't overlap here, NT header immediately follows DOS header
  • puts and exit are imported by name

As mentioned in hello world PE answer, the minimal distance between the start of NT headers and end of file on Windows 10 is 264 bytes, so minimal PE file size with non-overlapping DOS and NT headers on Windows 10 is 64+264=328 bytes (64 == sizeof(IMAGE_DOS_HEADER)). It means that all but 2 bytes of C code at the end of the file are required for this file to work on Windows 10.

The program prints its own PE signature, which is kinda cute.

x86

αpε uses jno 0x4a jo 0x4a to jump to the main boot code. I ran out of space in the DOS header and didn't want to rearrange the code, so I use the less robust single jnz a instruction. This means I rely on BIOS to not set bp to 1 before calling boot sector (M in MZ is dec bp). QEMU and Bochs set bp to 0. Unconditional jmp is not used because its code is 0xEB, on the other hand almost all short conditional jumps have ASCII codes, see here.

Main code:

    mov ax,2
    int 0x10            ; clear screen
    
    mov ax,0x1300
    mov bx,0xF          ; video page, video attribute
    mov bp,0x7C00+x86
    mov cx,3            ; text length
    mov dx,0            ; text position
    int 0x10            ; print text
    
    jmp $               ; enter infinite loop
    
    x86: db "x86"

This code is split into 3 parts (a:,b:,c:) to fit inside unused fields of NT headers. It looks like both b and c would fit inside section header, but it breaks PE on Windows XP for some reason.

bash/C/Ruby/Python2

MZuD='\'';
#/*
';echo bash #';print (0and'Ruby')or'Python2'# ... */␍main(){puts("C");}

Pretty standard stuff:

  • bash: \ inside '' does not escape
  • C: allows single # on a line
  • Ruby: 0 is truthy

Also, I used the fact that C treats \r as newline, unlike bash/Ruby/Python2 (link). This allows to use just # in bash/Ruby/Python2 to comment out the rest of the polyglot.

\$\endgroup\$
1
\$\begingroup\$

JScript, EcmaScript Edition 3, 5, 6, 2016, 2017, Node, Mozilla JavaScript (score = .174193548387), CoffeeScript (as whitespace-significant languages can be horrible for golfing).

$=this,y="EcmaScript ",($.WScript||alert)(x=Object.values?y+2017:$.module?"Node":$.uneval?"Mozilla JavaScript":[].includes?y+2016:$.Map?y+6:[].map?y+5:y+3)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.