Break OO privacy: Difference between revisions

m
syntax highlighting fixup automation
(Added Lua.)
m (syntax highlighting fixup automation)
Line 33:
Similar to C++, ABAP allows the declaration of friends which can be both classes and interfaces. All subclasses of friend classes are automatically friends of the source class. For example if classA (source) has classB as a friend and classC is a subclass of classB then classC is a friend of classA. Similarly all implementing classes of friend interfaces are friends of the source class. Also all interfaces which contain the befriended interface as a component are friends of the source class.
 
<langsyntaxhighlight lang=ABAP>class friendly_class definition deferred.
 
class my_class definition friends friendly_class .
Line 74:
 
endclass.
</syntaxhighlight>
</lang>
 
=={{header|Ada}}==
Line 80:
One of the great criticisms of Pascal was "there is no escape". The reason was that sometimes you have to convert the incompatible. We start with a package, which defines the data type which holds the secret.
 
<langsyntaxhighlight lang=Ada>package OO_Privacy is
 
type Confidential_Stuff is tagged private;
Line 89:
Password: Password_Type := "default!"; -- the "secret"
end record;
end OO_Privacy;</langsyntaxhighlight>
 
When we later define an object C of type Confidential_Stuff, we can't read read the password stored in C -- except by breaking / bypassing OO privacy rules.
Line 97:
One way to read the password is by using the generic function Unchecked_Conversion:
 
<langsyntaxhighlight lang=Ada>with OO_Privacy, Ada.Unchecked_Conversion, Ada.Text_IO;
 
procedure OO_Break_Privacy is
Line 112:
begin
Ada.Text_IO.Put_Line("The secret password is """ & Hack(C).Password & """");
end OO_Break_Privacy;</langsyntaxhighlight>
 
The output shows that C holds, surprise, surprise, the default password:
Line 122:
Another way to bypass privacy is using a child package. Ada child packages have access to their parents' private data structures (somewhat similar to "friends" in C++"):
 
<langsyntaxhighlight lang=Ada>package OO_Privacy.Friend is -- child package of OO.Privacy
function Get_Password(Secret: Confidential_Stuff) return String;
end OO_Privacy.Friend;</langsyntaxhighlight>
 
<langsyntaxhighlight lang=Ada>package body OO_Privacy.Friend is -- implementation of the child package
function Get_Password(Secret: Confidential_Stuff) return String is
(Secret.Password);
end OO_Privacy.Friend;</langsyntaxhighlight>
 
Now here is the program that uses the child package, to read the secret:
 
<langsyntaxhighlight lang=Ada>with OO_Privacy.Friend, Ada.Text_IO;
procedure Bypass_OO_Privacy is
Line 147:
OO_Privacy.Friend.Get_Password(C) &
"""");
end Bypass_OO_Privacy;</langsyntaxhighlight>
 
Once again, we have been too lazy to overwrite the default password:
Line 156:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang=csharp>using System;
using System.Reflection;
 
Line 173:
Console.WriteLine(answer);
}
}</langsyntaxhighlight>
{{out}}
<syntaxhighlight lang=text>42</langsyntaxhighlight>
 
=={{header|C++}}==
Line 181:
C++ has the 'friend' keyword to indicate that one class should have access to the private data of another. Here's a simple use case. (Please note that this code is not thread-safe.)
 
<langsyntaxhighlight lang=cpp>#include <iostream>
 
class CWidget; // Forward-declare that we have a class named CWidget.
Line 247:
delete pWidget3;
delete pWidget2;
}</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang=text>Widget spawning. There are now 1 Widgets instanciated.
Widget spawning. There are now 2 Widgets instanciated.
Widget dieing. There are now 1 Widgets instanciated.
Widget spawning. There are now 2 Widgets instanciated.
Widget dieing. There are now 1 Widgets instanciated.
Widget dieing. There are now 0 Widgets instanciated.</langsyntaxhighlight>
 
Without the "friend" mechanism, it's still possible to meaningfully modify any member in another class, as long as you know that member's address in memory, and its type. Here's the same program as above, but using a pointer to m_uicount, rather a reference to the factory:
 
<langsyntaxhighlight lang=cpp>#include <iostream>
 
class CWidget; // Forward-declare that we have a class named CWidget.
Line 323:
delete pWidget3;
delete pWidget2;
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
You can use the var-quote macro to get values from private variables. Here's an example of a variable 'priv' marked private in namespace 'a':
<langsyntaxhighlight lang=clojure>
(ns a)
(def ^:private priv :secret)
Line 335:
user=> @#'a/priv ; succeeds
:secret
</syntaxhighlight>
</lang>
 
Clojure can also access Java private variables with the same strategy that Java uses. As a convenience, use the [http://clojuredocs.org/clojure_contrib/clojure.contrib.reflect/get-field get-field] function from clojure.contrib.reflect. Here's an example of grabbing the private field "serialVersionUID" from java.lang.Double:
<langsyntaxhighlight lang=clojure>
user=> (get-field Double "serialVersionUID" (Double/valueOf 1.0))
-9172774392245257468
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
Line 358:
A symbol can be present in more than one package, such that it can be internal in some of them, and external in others.
 
<langsyntaxhighlight lang=lisp>(defpackage :funky
;; only these symbols are public
(:export :widget :get-wobbliness)
Line 402:
;; even read and evaluated. The symbol is internal and so cannot be used.
(format t "wobbliness: ~a~%" (slot-value *w* 'funky:wobbliness))
</syntaxhighlight>
</lang>
 
{{Out}} using CLISP:
Line 416:
 
breakingprivacy.d:
<langsyntaxhighlight lang=D>module breakingprivacy;
 
struct Foo
Line 426:
string str;
float f;
}</langsyntaxhighlight>
 
app.d:
<langsyntaxhighlight lang=D>import std.stdio;
import breakingprivacy;
 
Line 444:
__traits(getMember, foo, "str") = "Not so private anymore!";
writeln("Modified foo: ", foo);
}</langsyntaxhighlight>
 
{{out}}
<langsyntaxhighlight lang=text>Foo([1, 2, 3], 42, "Hello World!", 3.14)
foo.x = 42
Modified foo: Foo([1, 2, 3], 42, "Not so private anymore!", 3.14)</langsyntaxhighlight>
 
=={{header|E}}==
Line 459:
=={{header|F_Sharp|F#}}==
{{trans|C#}}
<langsyntaxhighlight lang=fsharp>open System
open System.Reflection
 
Line 474:
let answer = fieldInfo.GetValue(myInstance)
printfn "%s = %A" (answer.GetType().ToString()) answer
0</langsyntaxhighlight>
{{out}}
<pre>System.Int32 = 42</pre>
Line 483:
This example uses the private word ''sequence/tester'' from the vocabulary ''sets.private''. It tries to count the elements in an intersection of two sets.
 
<langsyntaxhighlight lang=factor>( scratchpad ) USING: sets sets.private ;
( scratchpad ) { 1 2 3 } { 1 2 4 } sequence/tester count .
2</langsyntaxhighlight>
 
There is better way to do the same, without any private words.
 
<langsyntaxhighlight lang=factor>( scratchpad ) USE: sets
( scratchpad ) { 1 2 3 } { 1 2 4 } intersect length .
2</langsyntaxhighlight>
 
=={{header|Forth}}==
Line 499:
Needs the FMS-SI (single inheritance) library code located here:
http://soton.mpeforth.com/flag/fms/index.html
<langsyntaxhighlight lang=forth>include FMS-SI.f
 
99 value x \ create a global variable named x
Line 516:
50 .. f1.x ! \ use the dot parser to access the private x without a message
f1 print \ 50
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
Line 522:
 
However, as usual, macros come to the rescue and one can easily access non-public members by the simple expedient (or, if you prefer, 'dirty hack') of redefining the Private and Protected keywords to mean Public:
<langsyntaxhighlight lang=freebasic>'FB 1.05.0 Win64
 
#Undef Private
Line 542:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 555:
A relevant Go Blog article is
[http://blog.golang.org/laws-of-reflection The Laws of Reflection].
<langsyntaxhighlight lang=go>package main
 
import (
Line 642:
_, err := r.ReadByte()
fmt.Println("bufio.ReadByte returned error:", err)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 664:
 
Note: Unicon can be translated via a command line switch into icon which allows for classes to be shared with Icon code (assuming no other incompatibilities exist).
<langsyntaxhighlight lang=unicon>link printf
 
procedure main()
Line 680:
printf("foo var1=%i, var2=%i, var3=%i\n",var1,var2,var3)
end
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 700:
=={{header|Java}}==
Private fields (and in general all members) of a Java class can be accessed via reflection, but must pass a security check in order to do so. There are two such security checks, one for discovering the field at all, and another for granting access to it in order to be able to read and write it. (This in turn means that trusted applications can do this — it is in fact a mechanism used by important frameworks like Spring — but untrusted applets cannot.)
<langsyntaxhighlight lang=java>import java.lang.reflect.*;
class Example {
Line 728:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 737:
 
(Note: somewhere between Java 8 and Java 11 this stopped working because the <code>value</code> field of <code>String</code> is <code>final</code>. The reflective access is still possible, but changing a final field isn't.)
<langsyntaxhighlight lang=Java>import java.lang.reflect.*;
public class BreakString{
public static void main(String... args) throws Exception{
Line 747:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 760:
=={{header|Kotlin}}==
For tasks such as this, reflection is your friend:
<langsyntaxhighlight lang=scala>import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.jvm.isAccessible
 
Line 775:
println("${prop.name} -> ${prop.get(tbb)}")
}
}</langsyntaxhighlight>
 
{{out}}
Line 786:
 
In the following example, a prototype is used for simplicity.
<langsyntaxhighlight lang=logtalk>:- object(foo).
 
% be sure that context switching calls are allowed
Line 797:
bar(3).
 
:- end_object.</langsyntaxhighlight>
After compiling and loading the above object, we can use the following query to access the private method:
<langsyntaxhighlight lang=logtalk>| ?- foo<<bar(X).
X = 1 ;
X = 2 ;
X = 3
true</langsyntaxhighlight>
 
=={{header|Lua}}==
Line 811:
These can be accessed indirectly through the [https://www.lua.org/manual/5.1/manual.html#5.9 debug library].
 
<langsyntaxhighlight lang=Lua>local function Counter()
-- These two variables are "private" to this function and can normally
-- only be accessed from within this scope, including by any function
Line 840:
break
end
end</langsyntaxhighlight>
 
{{out}}
Line 851:
=={{header|M2000 Interpreter}}==
We want to read two private variables, and change values without using a public method (a module or a function), and without attach a temporary method (we can do that in M2000). There is a variant in READ statemend to set references from group members (for variables and arrays, and objects) to names with a reference for each. So using these names (here in the exaample K, M) we can read and write private variables.
<langsyntaxhighlight lang=M2000 Interpreter>
Module CheckIt {
Group Alfa {
Line 872:
}
CheckIt
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
File oo.nim:
<langsyntaxhighlight lang=nim>type Foo* = object
a: string
b: string
Line 882:
 
proc createFoo*(a, b, c): Foo =
Foo(a: a, b: b, c: c)</langsyntaxhighlight>
By not adding a <code>*</code> to <code>Foo</code>'s members we don't export them. When we import this module we can't use them directly:
<langsyntaxhighlight lang=nim>var x = createFoo("this a", "this b", 12)
 
echo x.a # compile time error</langsyntaxhighlight>
The easiest way to get a debug view of any data:
<syntaxhighlight lang =nim>echo repr(x)</langsyntaxhighlight>
Output:
<pre>[a = 0x7f6bb87a7050"this a",
Line 894:
c = 12]</pre>
More fine-grained:
<langsyntaxhighlight lang=nim>import typeinfo
 
for key, val in fields(toAny(x)):
Line 904:
echo " is an integer with value: ", val.getBiggestInt
else:
echo " is an unknown with value: ", val.repr</langsyntaxhighlight>
Output:
<pre>Key a
Line 919:
One solution is to use Key-Value Coding. It treats properties and instance variables as "keys" that you can get and set using key-value coding methods.
 
<langsyntaxhighlight lang=objc>#import <Foundation/Foundation.h>
 
@interface Example : NSObject {
Line 954:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 964:
Another solution is to use a category to add methods to the class (you can have categories in your code modify any class, even classes compiled by someone else, including system classes). Since the new method is in the class, it can use the class's private instance variables with no problem.
 
<langsyntaxhighlight lang=objc>#import <Foundation/Foundation.h>
 
@interface Example : NSObject {
Line 1,013:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,023:
Finally, you can access the instance variable directly using runtime functions.
 
<langsyntaxhighlight lang=objc>#import <Foundation/Foundation.h>
#import <objc/runtime.h>
 
Line 1,060:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,077:
The reader is advised to stop reading here.
 
<langsyntaxhighlight lang=ocaml>class point x y =
object
val mutable x = x
Line 1,109:
Printf.printf "Broken coord: (%d, %d)\n" x y;
evil_reset p
p#print</langsyntaxhighlight>
 
{{out}}
Line 1,126:
=={{header|Perl}}==
Perl's object model does not enforce privacy. An object is just a blessed reference, and a blessed reference can be dereferenced just like an ordinary reference.
<langsyntaxhighlight lang=perl>package Foo;
sub new {
my $class = shift;
Line 1,140:
package main;
my $foo = Foo->new();
print "$_\n" for $foo->get_bar(), $foo->{_bar};</langsyntaxhighlight>
{{out}}
<pre>I am ostensibly private
Line 1,150:
We can easily break that privacy mechanism via low-level routines with the required simulated/fake context,<br>
and at the same time be reasonably confident that no-one is ever going to manage to achieve that by accident.
<!--<langsyntaxhighlight lang=Phix>(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (no class under p2js)</span>
<span style="color: #008080;">class</span> <span style="color: #000000;">test</span>
Line 1,167:
<span style="color: #000000;">structs</span><span style="color: #0000FF;">:</span><span style="color: #000000;">store_field</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"msg"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"this breaks privacy"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ctx</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">t</span><span style="color: #0000FF;">.</span><span style="color: #000000;">show</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
<small>(Obviously you could inline the ctx values rather than create a separate constant.)</small>
{{out}}
Line 1,180:
 
{{works with|PHP|5.1}}
<langsyntaxhighlight lang=php><?php
class SimpleClass {
private $answer = "hello\"world\nforever :)";
Line 1,198:
 
$new_class = eval($class_content);
echo $new_class['answer'];</langsyntaxhighlight>
 
Another way commonly used to access private and protected variables in PHP is to cast the object to an array. It's probably unintentional though looking on how casted array contains null bytes (probably "private" mark). This works unless a magic method for the cast operation is implemented:
Line 1,204:
{{works with|PHP|4.x}}
{{works with|PHP|5.x}}
<langsyntaxhighlight lang=php><?php
class SimpleClass {
private $answer = 42;
Line 1,211:
$class = new SimpleClass;
$classvars = (array)$class;
echo $classvars["\0SimpleClass\0answer"];</langsyntaxhighlight>
 
{{works with|PHP|5.3}}
Since php 5.3, one can easily read and write any protected and private member in a object via reflection.
<langsyntaxhighlight lang=php><?php
class fragile {
private $foo = 'bar';
Line 1,226:
$rp->setValue($fragile, 'haxxorz!');
var_dump($rp->getValue($fragile));
var_dump($fragile);</langsyntaxhighlight>
{{out}}
<pre>
Line 1,240:
PicoLisp uses [http://software-lab.de/doc/ref.html#transient "transient symbols"] for variables, functions, methods etc. inaccessible from other parts of the program. Lexically, a transient symbol is enclosed by double quotes.
The only way to access a transient symbol outside its namespace is to search for its name in other (public) structures. This is done by the '[http://software-lab.de/doc/refL.html#loc loc]' function.
<langsyntaxhighlight lang=PicoLisp>(class +Example)
# "_name"
 
Line 1,251:
(====) # Close transient scope
 
(setq Foo (new '(+Example) "Eric"))</langsyntaxhighlight>
Test:
<langsyntaxhighlight lang=PicoLisp>: (string> Foo) # Access via method call
-> "Hello, I am Eric"
 
Line 1,272:
 
: (get Foo (loc "_name" +Example))
-> "Edith"</langsyntaxhighlight>
 
=={{header|Python}}==
Python isn't heavily into private class names. Although private class names can be defined by using a double underscore at the start of the name, such names are accessible as they are mangled into the original name preceded by the name of its class as shown in this example:
<langsyntaxhighlight lang=python>>>> class MyClassName:
__private = 123
non_private = __private * 2
Line 1,291:
>>> mine._MyClassName__private
123
>>> </langsyntaxhighlight>
 
=={{header|Raku}}==
Line 1,297:
{{works with|Rakudo|2015.12}}
We may call into the MOP (Meta-Object Protocol) via the <tt>.^</tt> operator, and the MOP knows all about the object, including any supposedly private bits. We ask for its attributes, find the correct one, and get its value.
<syntaxhighlight lang=raku perl6line>class Foo {
has $!shyguy = 42;
}
my Foo $foo .= new;
 
say $foo.^attributes.first('$!shyguy').get_value($foo);</langsyntaxhighlight>
{{out}}
<pre>42</pre>
Line 1,308:
=={{header|Ruby}}==
Ruby lets you redefine great parts of the object model at runtime and provides several methods to do so conveniently. For a list of all available methods look up the documentation of <code>Object</code> and <code>Module</code> or call informative methods at runtime (<code>puts Object.methods</code>).
<langsyntaxhighlight lang=ruby>
class Example
def initialize
Line 1,326:
p example.instance_variable_set :@private_data, 42 # => 42
p example.instance_variable_get :@private_data # => 42
</syntaxhighlight>
</lang>
 
=={{header|Scala}}==
{{libheader|Scala}}<langsyntaxhighlight lang=scala>class Example(private var name: String) {
override def toString = s"Hello, I am $name"
}
Line 1,341:
field.set(foo, "Edith")
println(foo)
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
Sidef's object model does not enforce privacy, but it allows storing private attributes inside the container of an object, which is an hash:
<langsyntaxhighlight lang=ruby>class Example {
has public = "foo"
method init {
Line 1,359:
 
# Access private attributes
say obj{:private}; #=> "secret"</langsyntaxhighlight>
 
=={{header|Swift}}==
Swift reflection provides a Collection of label-value pairs for struct properties
<langsyntaxhighlight lang=Swift>struct Example {
var notSoSecret = "Hello!"
private var secret = 42
Line 1,374:
print("Value of the secret is \(secret)")
}
</syntaxhighlight>
</lang>
{{out}}
<pre>Value of the secret is 42</pre>
Line 1,380:
=={{header|Tcl}}==
Tcl's object properties are just variables in the a per-instance namespace; all that's required to get hold of them is to discover the name of the namespace concerned:
<langsyntaxhighlight lang=tcl>package require Tcl 8.6
 
oo::class create Example {
Line 1,390:
$e print
set [info object namespace $e]::name "Edith"
$e print</langsyntaxhighlight>{{out}}
Hello, I am Eric
Hello, I am Edith
Line 1,400:
Like the other .NET languages, VB can use Reflection ([https://docs.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/reflection Microsoft docs]).
 
<langsyntaxhighlight lang=vbnet>Imports System.Reflection
 
' MyClass is a VB keyword.
Line 1,414:
Console.WriteLine(answer)
End Sub
End Class</langsyntaxhighlight>
 
{{out}}
Line 1,423:
 
However, there is no such thing as a private method. Although conventionally methods which are not intended to be called from outside the class are suffixed with an underscore, this doesn't prevent anyone from accessing them as the following example shows.
<langsyntaxhighlight lang=ecmascript>class Safe {
construct new() { _safe = 42 } // the field _safe is private
safe { _safe } // provides public access to field
Line 1,432:
var s = Safe.new()
var a = [s.safe, s.doubleSafe, s.notSoSafe_]
for (e in a) System.print(e)</langsyntaxhighlight>
 
{{out}}
Line 1,443:
=={{header|zkl}}==
In zkl, privacy is more convention than enforced (unlike const or protected).
<langsyntaxhighlight lang=zkl>class C{var [private] v; fcn [private] f{123} class [private] D {}}
C.v; C.f; C.D; // all generate NotFoundError exceptions
However:
Line 1,449:
C.fcns[1]() //-->123
C.classes //-->L(Class(D))
C.vars //-->L(L("",Void)) (name,value) pairs</langsyntaxhighlight>
In the case of private vars, the name isn't saved.
 
10,333

edits